blob: 7320bc6b0480d1c820aec16d700ba9a8cbbcfbc3 [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()) {
John McCalle61b02b2010-05-04 01:53:42 +0000301 // Merge the old default argument into the new parameter.
302 // It's important to use getInit() here; getDefaultArg()
303 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000304 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000305 if (OldParam->hasUninstantiatedDefaultArg())
306 NewParam->setUninstantiatedDefaultArg(
307 OldParam->getUninstantiatedDefaultArg());
308 else
John McCalle61b02b2010-05-04 01:53:42 +0000309 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000310 } else if (NewParam->hasDefaultArg()) {
311 if (New->getDescribedFunctionTemplate()) {
312 // Paragraph 4, quoted above, only applies to non-template functions.
313 Diag(NewParam->getLocation(),
314 diag::err_param_default_argument_template_redecl)
315 << NewParam->getDefaultArgRange();
316 Diag(Old->getLocation(), diag::note_template_prev_declaration)
317 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000318 } else if (New->getTemplateSpecializationKind()
319 != TSK_ImplicitInstantiation &&
320 New->getTemplateSpecializationKind() != TSK_Undeclared) {
321 // C++ [temp.expr.spec]p21:
322 // Default function arguments shall not be specified in a declaration
323 // or a definition for one of the following explicit specializations:
324 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000325 // - the explicit specialization of a member function template;
326 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000327 // template where the class template specialization to which the
328 // member function specialization belongs is implicitly
329 // instantiated.
330 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
331 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
332 << New->getDeclName()
333 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000334 } else if (New->getDeclContext()->isDependentContext()) {
335 // C++ [dcl.fct.default]p6 (DR217):
336 // Default arguments for a member function of a class template shall
337 // be specified on the initial declaration of the member function
338 // within the class template.
339 //
340 // Reading the tea leaves a bit in DR217 and its reference to DR205
341 // leads me to the conclusion that one cannot add default function
342 // arguments for an out-of-line definition of a member function of a
343 // dependent type.
344 int WhichKind = 2;
345 if (CXXRecordDecl *Record
346 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
347 if (Record->getDescribedClassTemplate())
348 WhichKind = 0;
349 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
350 WhichKind = 1;
351 else
352 WhichKind = 2;
353 }
354
355 Diag(NewParam->getLocation(),
356 diag::err_param_default_argument_member_template_redecl)
357 << WhichKind
358 << NewParam->getDefaultArgRange();
359 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000360 }
361 }
362
Douglas Gregorf40863c2010-02-12 07:32:17 +0000363 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000364 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000365
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000366 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000367}
368
369/// CheckCXXDefaultArguments - Verify that the default arguments for a
370/// function declaration are well-formed according to C++
371/// [dcl.fct.default].
372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
373 unsigned NumParams = FD->getNumParams();
374 unsigned p;
375
376 // Find first parameter with a default argument
377 for (p = 0; p < NumParams; ++p) {
378 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000379 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000380 break;
381 }
382
383 // C++ [dcl.fct.default]p4:
384 // In a given function declaration, all parameters
385 // subsequent to a parameter with a default argument shall
386 // have default arguments supplied in this or previous
387 // declarations. A default argument shall not be redefined
388 // by a later declaration (not even to the same value).
389 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000390 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000391 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000392 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000393 if (Param->isInvalidDecl())
394 /* We already complained about this parameter. */;
395 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000397 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000398 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 else
Mike Stump11289f42009-09-09 15:08:12 +0000400 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000401 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner199abbc2008-04-08 05:04:30 +0000403 LastMissingDefaultArg = p;
404 }
405 }
406
407 if (LastMissingDefaultArg > 0) {
408 // Some default arguments were missing. Clear out all of the
409 // default arguments up to (and including) the last missing
410 // default argument, so that we leave the function parameters
411 // in a semantically valid state.
412 for (p = 0; p <= LastMissingDefaultArg; ++p) {
413 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000414 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000415 if (!Param->hasUnparsedDefaultArg())
416 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000417 Param->setDefaultArg(0);
418 }
419 }
420 }
421}
Douglas Gregor556877c2008-04-13 21:30:24 +0000422
Douglas Gregor61956c42008-10-31 09:07:45 +0000423/// isCurrentClassName - Determine whether the identifier II is the
424/// name of the class type currently being defined. In the case of
425/// nested classes, this will only return true if II is the name of
426/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000427bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
428 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000429 assert(getLangOptions().CPlusPlus && "No class names in C!");
430
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000431 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000432 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000433 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
435 } else
436 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
437
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000438 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000439 return &II == CurDecl->getIdentifier();
440 else
441 return false;
442}
443
Mike Stump11289f42009-09-09 15:08:12 +0000444/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000445///
446/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
447/// and returns NULL otherwise.
448CXXBaseSpecifier *
449Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
450 SourceRange SpecifierRange,
451 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000452 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000453 SourceLocation BaseLoc) {
454 // C++ [class.union]p1:
455 // A union shall not have base classes.
456 if (Class->isUnion()) {
457 Diag(Class->getLocation(), diag::err_base_clause_on_union)
458 << SpecifierRange;
459 return 0;
460 }
461
462 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000463 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000464 Class->getTagKind() == TTK_Class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000465 Access, BaseType);
466
467 // Base specifiers must be record types.
468 if (!BaseType->isRecordType()) {
469 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.union]p1:
474 // A union shall not be used as a base class.
475 if (BaseType->isUnionType()) {
476 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
477 return 0;
478 }
479
480 // C++ [class.derived]p2:
481 // The class-name in a base-specifier shall not be an incompletely
482 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000483 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000484 PDiag(diag::err_incomplete_base_class)
485 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 return 0;
487
Eli Friedmanc96d4962009-08-15 21:55:26 +0000488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000491 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000495
Alexis Hunt96d5c762009-11-21 08:43:09 +0000496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
497 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000501 return 0;
502 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000503
Eli Friedman89c038e2009-12-05 23:03:49 +0000504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000505
506 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000507 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000508 Class->getTagKind() == TTK_Class,
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000509 Access, BaseType);
510}
511
512void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
513 const CXXRecordDecl *BaseClass,
514 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000515 // A class with a non-empty base class is not empty.
516 // FIXME: Standard ref?
517 if (!BaseClass->isEmpty())
518 Class->setEmpty(false);
519
520 // C++ [class.virtual]p1:
521 // A class that [...] inherits a virtual function is called a polymorphic
522 // class.
523 if (BaseClass->isPolymorphic())
524 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000525
Douglas Gregor463421d2009-03-03 04:44:36 +0000526 // C++ [dcl.init.aggr]p1:
527 // An aggregate is [...] a class with [...] no base classes [...].
528 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000529
530 // C++ [class]p4:
531 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000532 Class->setPOD(false);
533
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000535 // C++ [class.ctor]p5:
536 // A constructor is trivial if its class has no virtual base classes.
537 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000538
539 // C++ [class.copy]p6:
540 // A copy constructor is trivial if its class has no virtual base classes.
541 Class->setHasTrivialCopyConstructor(false);
542
543 // C++ [class.copy]p11:
544 // A copy assignment operator is trivial if its class has no virtual
545 // base classes.
546 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000547
548 // C++0x [meta.unary.prop] is_empty:
549 // T is a class type, but not a union type, with ... no virtual base
550 // classes
551 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000552 } else {
553 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000554 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000555 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000556 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000557 Class->setHasTrivialConstructor(false);
558
559 // C++ [class.copy]p6:
560 // A copy constructor is trivial if all the direct base classes of its
561 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000563 Class->setHasTrivialCopyConstructor(false);
564
565 // C++ [class.copy]p11:
566 // A copy assignment operator is trivial if all the direct base classes
567 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000568 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000569 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000570 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000571
572 // C++ [class.ctor]p3:
573 // A destructor is trivial if all the direct base classes of its class
574 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000575 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000576 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000577}
578
Douglas Gregor556877c2008-04-13 21:30:24 +0000579/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
580/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000581/// example:
582/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000583/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000584Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000585Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 bool Virtual, AccessSpecifier Access,
587 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000588 if (!classdecl)
589 return true;
590
Douglas Gregorc40290e2009-03-09 23:48:35 +0000591 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000592 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
593 if (!Class)
594 return true;
595
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000596 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
598 Virtual, Access,
599 BaseType, BaseLoc))
600 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregor463421d2009-03-03 04:44:36 +0000602 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000603}
Douglas Gregor556877c2008-04-13 21:30:24 +0000604
Douglas Gregor463421d2009-03-03 04:44:36 +0000605/// \brief Performs the actual work of attaching the given base class
606/// specifiers to a C++ class.
607bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
608 unsigned NumBases) {
609 if (NumBases == 0)
610 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000611
612 // Used to keep track of which base types we have already seen, so
613 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614 // that the key is always the unqualified canonical type of the base
615 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
617
618 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000619 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000620 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000621 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000622 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000623 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000624 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
Douglas Gregor29a92472008-10-22 17:49:05 +0000626 if (KnownBaseTypes[NewBaseType]) {
627 // C++ [class.mi]p3:
628 // A class shall not be specified as a direct base class of a
629 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000630 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000631 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000632 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000633 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000634
635 // Delete the duplicate base class specifier; we're going to
636 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000637 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000638
639 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000640 } else {
641 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000642 KnownBaseTypes[NewBaseType] = Bases[idx];
643 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000644 }
645 }
646
647 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000648 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000649
650 // Delete the remaining (good) base class specifiers, since their
651 // data has been copied into the CXXRecordDecl.
652 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000653 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000654
655 return Invalid;
656}
657
658/// ActOnBaseSpecifiers - Attach the given base specifiers to the
659/// class, after checking whether there are any duplicate base
660/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000661void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000662 unsigned NumBases) {
663 if (!ClassDecl || !Bases || !NumBases)
664 return;
665
666 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000667 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000668 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000669}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000670
John McCalle78aac42010-03-10 03:28:59 +0000671static CXXRecordDecl *GetClassForType(QualType T) {
672 if (const RecordType *RT = T->getAs<RecordType>())
673 return cast<CXXRecordDecl>(RT->getDecl());
674 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
675 return ICT->getDecl();
676 else
677 return 0;
678}
679
Douglas Gregor36d1b142009-10-06 17:59:45 +0000680/// \brief Determine whether the type \p Derived is a C++ class that is
681/// derived from the type \p Base.
682bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
683 if (!getLangOptions().CPlusPlus)
684 return false;
John McCalle78aac42010-03-10 03:28:59 +0000685
686 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
687 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return false;
689
John McCalle78aac42010-03-10 03:28:59 +0000690 CXXRecordDecl *BaseRD = GetClassForType(Base);
691 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000692 return false;
693
John McCall67da35c2010-02-04 22:26:26 +0000694 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
695 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000696}
697
698/// \brief Determine whether the type \p Derived is a C++ class that is
699/// derived from the type \p Base.
700bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
701 if (!getLangOptions().CPlusPlus)
702 return false;
703
John McCalle78aac42010-03-10 03:28:59 +0000704 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
705 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000706 return false;
707
John McCalle78aac42010-03-10 03:28:59 +0000708 CXXRecordDecl *BaseRD = GetClassForType(Base);
709 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000710 return false;
711
Douglas Gregor36d1b142009-10-06 17:59:45 +0000712 return DerivedRD->isDerivedFrom(BaseRD, Paths);
713}
714
Anders Carlssona70cff62010-04-24 19:06:50 +0000715void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
716 CXXBaseSpecifierArray &BasePathArray) {
717 assert(BasePathArray.empty() && "Base path array must be empty!");
718 assert(Paths.isRecordingPaths() && "Must record paths!");
719
720 const CXXBasePath &Path = Paths.front();
721
722 // We first go backward and check if we have a virtual base.
723 // FIXME: It would be better if CXXBasePath had the base specifier for
724 // the nearest virtual base.
725 unsigned Start = 0;
726 for (unsigned I = Path.size(); I != 0; --I) {
727 if (Path[I - 1].Base->isVirtual()) {
728 Start = I - 1;
729 break;
730 }
731 }
732
733 // Now add all bases.
734 for (unsigned I = Start, E = Path.size(); I != E; ++I)
735 BasePathArray.push_back(Path[I].Base);
736}
737
Douglas Gregor36d1b142009-10-06 17:59:45 +0000738/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
739/// conversion (where Derived and Base are class types) is
740/// well-formed, meaning that the conversion is unambiguous (and
741/// that all of the base classes are accessible). Returns true
742/// and emits a diagnostic if the code is ill-formed, returns false
743/// otherwise. Loc is the location where this routine should point to
744/// if there is an error, and Range is the source range to highlight
745/// if there is an error.
746bool
747Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000748 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000749 unsigned AmbigiousBaseConvID,
750 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000751 DeclarationName Name,
752 CXXBaseSpecifierArray *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000753 // First, determine whether the path from Derived to Base is
754 // ambiguous. This is slightly more expensive than checking whether
755 // the Derived to Base conversion exists, because here we need to
756 // explore multiple paths to determine if there is an ambiguity.
757 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
758 /*DetectVirtual=*/false);
759 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
760 assert(DerivationOkay &&
761 "Can only be used with a derived-to-base conversion");
762 (void)DerivationOkay;
763
764 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000765 if (InaccessibleBaseID) {
766 // Check that the base class can be accessed.
767 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
768 InaccessibleBaseID)) {
769 case AR_inaccessible:
770 return true;
771 case AR_accessible:
772 case AR_dependent:
773 case AR_delayed:
774 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000775 }
John McCall5b0829a2010-02-10 09:31:12 +0000776 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000777
778 // Build a base path if necessary.
779 if (BasePath)
780 BuildBasePathArray(Paths, *BasePath);
781 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000782 }
783
784 // We know that the derived-to-base conversion is ambiguous, and
785 // we're going to produce a diagnostic. Perform the derived-to-base
786 // search just one more time to compute all of the possible paths so
787 // that we can print them out. This is more expensive than any of
788 // the previous derived-to-base checks we've done, but at this point
789 // performance isn't as much of an issue.
790 Paths.clear();
791 Paths.setRecordingPaths(true);
792 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
793 assert(StillOkay && "Can only be used with a derived-to-base conversion");
794 (void)StillOkay;
795
796 // Build up a textual representation of the ambiguous paths, e.g.,
797 // D -> B -> A, that will be used to illustrate the ambiguous
798 // conversions in the diagnostic. We only print one of the paths
799 // to each base class subobject.
800 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
801
802 Diag(Loc, AmbigiousBaseConvID)
803 << Derived << Base << PathDisplayStr << Range << Name;
804 return true;
805}
806
807bool
808Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000809 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000810 CXXBaseSpecifierArray *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000811 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000812 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000813 IgnoreAccess ? 0
814 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000815 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000816 Loc, Range, DeclarationName(),
817 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000818}
819
820
821/// @brief Builds a string representing ambiguous paths from a
822/// specific derived class to different subobjects of the same base
823/// class.
824///
825/// This function builds a string that can be used in error messages
826/// to show the different paths that one can take through the
827/// inheritance hierarchy to go from the derived class to different
828/// subobjects of a base class. The result looks something like this:
829/// @code
830/// struct D -> struct B -> struct A
831/// struct D -> struct C -> struct A
832/// @endcode
833std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
834 std::string PathDisplayStr;
835 std::set<unsigned> DisplayedPaths;
836 for (CXXBasePaths::paths_iterator Path = Paths.begin();
837 Path != Paths.end(); ++Path) {
838 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
839 // We haven't displayed a path to this particular base
840 // class subobject yet.
841 PathDisplayStr += "\n ";
842 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
843 for (CXXBasePath::const_iterator Element = Path->begin();
844 Element != Path->end(); ++Element)
845 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
846 }
847 }
848
849 return PathDisplayStr;
850}
851
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000852//===----------------------------------------------------------------------===//
853// C++ class member Handling
854//===----------------------------------------------------------------------===//
855
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000856/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
857/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
858/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000859/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000860Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000861Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000862 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000863 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
864 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000865 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000866 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000867 Expr *BitWidth = static_cast<Expr*>(BW);
868 Expr *Init = static_cast<Expr*>(InitExpr);
869 SourceLocation Loc = D.getIdentifierLoc();
870
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000871 bool isFunc = D.isFunctionDeclarator();
872
John McCall07e91c02009-08-06 02:15:43 +0000873 assert(!DS.isFriendSpecified());
874
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000875 // C++ 9.2p6: A member shall not be declared to have automatic storage
876 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000877 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
878 // data members and cannot be applied to names declared const or static,
879 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000880 switch (DS.getStorageClassSpec()) {
881 case DeclSpec::SCS_unspecified:
882 case DeclSpec::SCS_typedef:
883 case DeclSpec::SCS_static:
884 // FALL THROUGH.
885 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000886 case DeclSpec::SCS_mutable:
887 if (isFunc) {
888 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000889 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000890 else
Chris Lattner3b054132008-11-19 05:08:23 +0000891 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000892
Sebastian Redl8071edb2008-11-17 23:24:37 +0000893 // FIXME: It would be nicer if the keyword was ignored only for this
894 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000895 D.getMutableDeclSpec().ClearStorageClassSpecs();
896 } else {
897 QualType T = GetTypeForDeclarator(D, S);
898 diag::kind err = static_cast<diag::kind>(0);
899 if (T->isReferenceType())
900 err = diag::err_mutable_reference;
901 else if (T.isConstQualified())
902 err = diag::err_mutable_const;
903 if (err != 0) {
904 if (DS.getStorageClassSpecLoc().isValid())
905 Diag(DS.getStorageClassSpecLoc(), err);
906 else
907 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000908 // FIXME: It would be nicer if the keyword was ignored only for this
909 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000910 D.getMutableDeclSpec().ClearStorageClassSpecs();
911 }
912 }
913 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000914 default:
915 if (DS.getStorageClassSpecLoc().isValid())
916 Diag(DS.getStorageClassSpecLoc(),
917 diag::err_storageclass_invalid_for_member);
918 else
919 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
920 D.getMutableDeclSpec().ClearStorageClassSpecs();
921 }
922
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000923 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000924 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000925 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000926 // Check also for this case:
927 //
928 // typedef int f();
929 // f a;
930 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000931 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000932 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000933 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000934
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000935 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
936 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000937 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000938
939 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000940 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000941 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000942 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
943 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000944 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000945 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000946 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000947 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000948 if (!Member) {
949 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000950 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000951 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000952
953 // Non-instance-fields can't have a bitfield.
954 if (BitWidth) {
955 if (Member->isInvalidDecl()) {
956 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000957 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000958 // C++ 9.6p3: A bit-field shall not be a static member.
959 // "static member 'A' cannot be a bit-field"
960 Diag(Loc, diag::err_static_not_bitfield)
961 << Name << BitWidth->getSourceRange();
962 } else if (isa<TypedefDecl>(Member)) {
963 // "typedef member 'x' cannot be a bit-field"
964 Diag(Loc, diag::err_typedef_not_bitfield)
965 << Name << BitWidth->getSourceRange();
966 } else {
967 // A function typedef ("typedef int f(); f a;").
968 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
969 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000970 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000971 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
Chris Lattnerd26760a2009-03-05 23:01:03 +0000974 DeleteExpr(BitWidth);
975 BitWidth = 0;
976 Member->setInvalidDecl();
977 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000978
979 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregor3447e762009-08-20 22:52:58 +0000981 // If we have declared a member function template, set the access of the
982 // templated declaration as well.
983 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
984 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000985 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000986
Douglas Gregor92751d42008-11-17 22:58:34 +0000987 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000988
Douglas Gregor0c880302009-03-11 23:00:04 +0000989 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000990 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000991 if (Deleted) // FIXME: Source location is not very good.
992 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000993
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000994 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000995 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000996 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000998 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000999}
1000
Douglas Gregor15e77a22009-12-31 09:10:24 +00001001/// \brief Find the direct and/or virtual base specifiers that
1002/// correspond to the given base type, for use in base initialization
1003/// within a constructor.
1004static bool FindBaseInitializer(Sema &SemaRef,
1005 CXXRecordDecl *ClassDecl,
1006 QualType BaseType,
1007 const CXXBaseSpecifier *&DirectBaseSpec,
1008 const CXXBaseSpecifier *&VirtualBaseSpec) {
1009 // First, check for a direct base class.
1010 DirectBaseSpec = 0;
1011 for (CXXRecordDecl::base_class_const_iterator Base
1012 = ClassDecl->bases_begin();
1013 Base != ClassDecl->bases_end(); ++Base) {
1014 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1015 // We found a direct base of this type. That's what we're
1016 // initializing.
1017 DirectBaseSpec = &*Base;
1018 break;
1019 }
1020 }
1021
1022 // Check for a virtual base class.
1023 // FIXME: We might be able to short-circuit this if we know in advance that
1024 // there are no virtual bases.
1025 VirtualBaseSpec = 0;
1026 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1027 // We haven't found a base yet; search the class hierarchy for a
1028 // virtual base class.
1029 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1030 /*DetectVirtual=*/false);
1031 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1032 BaseType, Paths)) {
1033 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1034 Path != Paths.end(); ++Path) {
1035 if (Path->back().Base->isVirtual()) {
1036 VirtualBaseSpec = Path->back().Base;
1037 break;
1038 }
1039 }
1040 }
1041 }
1042
1043 return DirectBaseSpec || VirtualBaseSpec;
1044}
1045
Douglas Gregore8381c02008-11-05 04:29:56 +00001046/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001047Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001048Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001049 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001050 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001051 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001052 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001053 SourceLocation IdLoc,
1054 SourceLocation LParenLoc,
1055 ExprTy **Args, unsigned NumArgs,
1056 SourceLocation *CommaLocs,
1057 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001058 if (!ConstructorD)
1059 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001060
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001061 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001062
1063 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001064 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001065 if (!Constructor) {
1066 // The user wrote a constructor initializer on a function that is
1067 // not a C++ constructor. Ignore the error for now, because we may
1068 // have more member initializers coming; we'll diagnose it just
1069 // once in ActOnMemInitializers.
1070 return true;
1071 }
1072
1073 CXXRecordDecl *ClassDecl = Constructor->getParent();
1074
1075 // C++ [class.base.init]p2:
1076 // Names in a mem-initializer-id are looked up in the scope of the
1077 // constructor’s class and, if not found in that scope, are looked
1078 // up in the scope containing the constructor’s
1079 // definition. [Note: if the constructor’s class contains a member
1080 // with the same name as a direct or virtual base class of the
1081 // class, a mem-initializer-id naming the member or base class and
1082 // composed of a single identifier refers to the class member. A
1083 // mem-initializer-id for the hidden base class may be specified
1084 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001085 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001086 // Look for a member, first.
1087 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001088 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001089 = ClassDecl->lookup(MemberOrBase);
1090 if (Result.first != Result.second)
1091 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001092
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001093 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001094
Eli Friedman8e1433b2009-07-29 19:44:27 +00001095 if (Member)
1096 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001097 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001098 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001099 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001100 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001101 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001102
1103 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001104 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001105 } else {
1106 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1107 LookupParsedName(R, S, &SS);
1108
1109 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1110 if (!TyD) {
1111 if (R.isAmbiguous()) return true;
1112
John McCallda6841b2010-04-09 19:01:14 +00001113 // We don't want access-control diagnostics here.
1114 R.suppressDiagnostics();
1115
Douglas Gregora3b624a2010-01-19 06:46:48 +00001116 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1117 bool NotUnknownSpecialization = false;
1118 DeclContext *DC = computeDeclContext(SS, false);
1119 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1120 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1121
1122 if (!NotUnknownSpecialization) {
1123 // When the scope specifier can refer to a member of an unknown
1124 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001125 BaseType = CheckTypenameType(ETK_None,
1126 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora3b624a2010-01-19 06:46:48 +00001127 *MemberOrBase, SS.getRange());
Douglas Gregor281c4862010-03-07 23:26:22 +00001128 if (BaseType.isNull())
1129 return true;
1130
Douglas Gregora3b624a2010-01-19 06:46:48 +00001131 R.clear();
1132 }
1133 }
1134
Douglas Gregor15e77a22009-12-31 09:10:24 +00001135 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001136 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001137 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1138 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001139 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1140 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1141 // We have found a non-static data member with a similar
1142 // name to what was typed; complain and initialize that
1143 // member.
1144 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1145 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001146 << FixItHint::CreateReplacement(R.getNameLoc(),
1147 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001148 Diag(Member->getLocation(), diag::note_previous_decl)
1149 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001150
1151 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1152 LParenLoc, RParenLoc);
1153 }
1154 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1155 const CXXBaseSpecifier *DirectBaseSpec;
1156 const CXXBaseSpecifier *VirtualBaseSpec;
1157 if (FindBaseInitializer(*this, ClassDecl,
1158 Context.getTypeDeclType(Type),
1159 DirectBaseSpec, VirtualBaseSpec)) {
1160 // We have found a direct or virtual base class with a
1161 // similar name to what was typed; complain and initialize
1162 // that base class.
1163 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1164 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001165 << FixItHint::CreateReplacement(R.getNameLoc(),
1166 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001167
1168 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1169 : VirtualBaseSpec;
1170 Diag(BaseSpec->getSourceRange().getBegin(),
1171 diag::note_base_class_specified_here)
1172 << BaseSpec->getType()
1173 << BaseSpec->getSourceRange();
1174
Douglas Gregor15e77a22009-12-31 09:10:24 +00001175 TyD = Type;
1176 }
1177 }
1178 }
1179
Douglas Gregora3b624a2010-01-19 06:46:48 +00001180 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001181 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1182 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1183 return true;
1184 }
John McCallb5a0d312009-12-21 10:41:20 +00001185 }
1186
Douglas Gregora3b624a2010-01-19 06:46:48 +00001187 if (BaseType.isNull()) {
1188 BaseType = Context.getTypeDeclType(TyD);
1189 if (SS.isSet()) {
1190 NestedNameSpecifier *Qualifier =
1191 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001192
Douglas Gregora3b624a2010-01-19 06:46:48 +00001193 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001194 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001195 }
John McCallb5a0d312009-12-21 10:41:20 +00001196 }
1197 }
Mike Stump11289f42009-09-09 15:08:12 +00001198
John McCallbcd03502009-12-07 02:54:59 +00001199 if (!TInfo)
1200 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001201
John McCallbcd03502009-12-07 02:54:59 +00001202 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001203 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001204}
1205
John McCalle22a04a2009-11-04 23:02:40 +00001206/// Checks an initializer expression for use of uninitialized fields, such as
1207/// containing the field that is being initialized. Returns true if there is an
1208/// uninitialized field was used an updates the SourceLocation parameter; false
1209/// otherwise.
1210static bool InitExprContainsUninitializedFields(const Stmt* S,
1211 const FieldDecl* LhsField,
1212 SourceLocation* L) {
1213 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1214 if (ME) {
1215 const NamedDecl* RhsField = ME->getMemberDecl();
1216 if (RhsField == LhsField) {
1217 // Initializing a field with itself. Throw a warning.
1218 // But wait; there are exceptions!
1219 // Exception #1: The field may not belong to this record.
1220 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1221 const Expr* base = ME->getBase();
1222 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1223 // Even though the field matches, it does not belong to this record.
1224 return false;
1225 }
1226 // None of the exceptions triggered; return true to indicate an
1227 // uninitialized field was used.
1228 *L = ME->getMemberLoc();
1229 return true;
1230 }
1231 }
1232 bool found = false;
1233 for (Stmt::const_child_iterator it = S->child_begin();
1234 it != S->child_end() && found == false;
1235 ++it) {
1236 if (isa<CallExpr>(S)) {
1237 // Do not descend into function calls or constructors, as the use
1238 // of an uninitialized field may be valid. One would have to inspect
1239 // the contents of the function/ctor to determine if it is safe or not.
1240 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1241 // may be safe, depending on what the function/ctor does.
1242 continue;
1243 }
1244 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1245 }
1246 return found;
1247}
1248
Eli Friedman8e1433b2009-07-29 19:44:27 +00001249Sema::MemInitResult
1250Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1251 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001252 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001253 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001254 // Diagnose value-uses of fields to initialize themselves, e.g.
1255 // foo(foo)
1256 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001257 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001258 for (unsigned i = 0; i < NumArgs; ++i) {
1259 SourceLocation L;
1260 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1261 // FIXME: Return true in the case when other fields are used before being
1262 // uninitialized. For example, let this field be the i'th field. When
1263 // initializing the i'th field, throw a warning if any of the >= i'th
1264 // fields are used, as they are not yet initialized.
1265 // Right now we are only handling the case where the i'th field uses
1266 // itself in its initializer.
1267 Diag(L, diag::warn_field_is_uninit);
1268 }
1269 }
1270
Eli Friedman8e1433b2009-07-29 19:44:27 +00001271 bool HasDependentArg = false;
1272 for (unsigned i = 0; i < NumArgs; i++)
1273 HasDependentArg |= Args[i]->isTypeDependent();
1274
Eli Friedman8e1433b2009-07-29 19:44:27 +00001275 QualType FieldType = Member->getType();
1276 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1277 FieldType = Array->getElementType();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001278 if (FieldType->isDependentType() || HasDependentArg) {
1279 // Can't check initialization for a member of dependent type or when
1280 // any of the arguments are type-dependent expressions.
1281 OwningExprResult Init
1282 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1283 RParenLoc));
1284
1285 // Erase any temporaries within this evaluation context; we're not
1286 // going to track them in the AST, since we'll be rebuilding the
1287 // ASTs during template instantiation.
1288 ExprTemporaries.erase(
1289 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1290 ExprTemporaries.end());
1291
1292 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1293 LParenLoc,
1294 Init.takeAs<Expr>(),
1295 RParenLoc);
1296
Douglas Gregore8381c02008-11-05 04:29:56 +00001297 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001298
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001299 if (Member->isInvalidDecl())
1300 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001301
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001302 // Initialize the member.
1303 InitializedEntity MemberEntity =
1304 InitializedEntity::InitializeMember(Member, 0);
1305 InitializationKind Kind =
1306 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1307
1308 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1309
1310 OwningExprResult MemberInit =
1311 InitSeq.Perform(*this, MemberEntity, Kind,
1312 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1313 if (MemberInit.isInvalid())
1314 return true;
1315
1316 // C++0x [class.base.init]p7:
1317 // The initialization of each base and member constitutes a
1318 // full-expression.
1319 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1320 if (MemberInit.isInvalid())
1321 return true;
1322
1323 // If we are in a dependent context, template instantiation will
1324 // perform this type-checking again. Just save the arguments that we
1325 // received in a ParenListExpr.
1326 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1327 // of the information that we have about the member
1328 // initializer. However, deconstructing the ASTs is a dicey process,
1329 // and this approach is far more likely to get the corner cases right.
1330 if (CurContext->isDependentContext()) {
1331 // Bump the reference count of all of the arguments.
1332 for (unsigned I = 0; I != NumArgs; ++I)
1333 Args[I]->Retain();
1334
1335 OwningExprResult Init
1336 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1337 RParenLoc));
1338 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1339 LParenLoc,
1340 Init.takeAs<Expr>(),
1341 RParenLoc);
1342 }
1343
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001344 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001345 LParenLoc,
1346 MemberInit.takeAs<Expr>(),
1347 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001348}
1349
1350Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001351Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001352 Expr **Args, unsigned NumArgs,
1353 SourceLocation LParenLoc, SourceLocation RParenLoc,
1354 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001355 bool HasDependentArg = false;
1356 for (unsigned i = 0; i < NumArgs; i++)
1357 HasDependentArg |= Args[i]->isTypeDependent();
1358
John McCallbcd03502009-12-07 02:54:59 +00001359 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001360 if (BaseType->isDependentType() || HasDependentArg) {
1361 // Can't check initialization for a base of dependent type or when
1362 // any of the arguments are type-dependent expressions.
1363 OwningExprResult BaseInit
1364 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1365 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001366
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001367 // Erase any temporaries within this evaluation context; we're not
1368 // going to track them in the AST, since we'll be rebuilding the
1369 // ASTs during template instantiation.
1370 ExprTemporaries.erase(
1371 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1372 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001373
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001374 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001375 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001376 LParenLoc,
1377 BaseInit.takeAs<Expr>(),
1378 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001379 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001380
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001381 if (!BaseType->isRecordType())
1382 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1383 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1384
1385 // C++ [class.base.init]p2:
1386 // [...] Unless the mem-initializer-id names a nonstatic data
1387 // member of the constructor’s class or a direct or virtual base
1388 // of that class, the mem-initializer is ill-formed. A
1389 // mem-initializer-list can initialize a base class using any
1390 // name that denotes that base class type.
1391
1392 // Check for direct and virtual base classes.
1393 const CXXBaseSpecifier *DirectBaseSpec = 0;
1394 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1395 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1396 VirtualBaseSpec);
1397
1398 // C++ [base.class.init]p2:
1399 // If a mem-initializer-id is ambiguous because it designates both
1400 // a direct non-virtual base class and an inherited virtual base
1401 // class, the mem-initializer is ill-formed.
1402 if (DirectBaseSpec && VirtualBaseSpec)
1403 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1404 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1405 // C++ [base.class.init]p2:
1406 // Unless the mem-initializer-id names a nonstatic data membeer of the
1407 // constructor's class ot a direst or virtual base of that class, the
1408 // mem-initializer is ill-formed.
1409 if (!DirectBaseSpec && !VirtualBaseSpec)
1410 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall1e67dd62010-04-27 01:43:38 +00001411 << BaseType << Context.getTypeDeclType(ClassDecl)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001412 << BaseTInfo->getTypeLoc().getSourceRange();
1413
1414 CXXBaseSpecifier *BaseSpec
1415 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1416 if (!BaseSpec)
1417 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1418
1419 // Initialize the base.
1420 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001421 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001422 InitializationKind Kind =
1423 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1424
1425 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1426
1427 OwningExprResult BaseInit =
1428 InitSeq.Perform(*this, BaseEntity, Kind,
1429 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1430 if (BaseInit.isInvalid())
1431 return true;
1432
1433 // C++0x [class.base.init]p7:
1434 // The initialization of each base and member constitutes a
1435 // full-expression.
1436 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1437 if (BaseInit.isInvalid())
1438 return true;
1439
1440 // If we are in a dependent context, template instantiation will
1441 // perform this type-checking again. Just save the arguments that we
1442 // received in a ParenListExpr.
1443 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1444 // of the information that we have about the base
1445 // initializer. However, deconstructing the ASTs is a dicey process,
1446 // and this approach is far more likely to get the corner cases right.
1447 if (CurContext->isDependentContext()) {
1448 // Bump the reference count of all of the arguments.
1449 for (unsigned I = 0; I != NumArgs; ++I)
1450 Args[I]->Retain();
1451
1452 OwningExprResult Init
1453 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1454 RParenLoc));
1455 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001456 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001457 LParenLoc,
1458 Init.takeAs<Expr>(),
1459 RParenLoc);
1460 }
1461
1462 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001463 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001464 LParenLoc,
1465 BaseInit.takeAs<Expr>(),
1466 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001467}
1468
Anders Carlsson1b00e242010-04-23 03:10:23 +00001469/// ImplicitInitializerKind - How an implicit base or member initializer should
1470/// initialize its base or member.
1471enum ImplicitInitializerKind {
1472 IIK_Default,
1473 IIK_Copy,
1474 IIK_Move
1475};
1476
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001477static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001478BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001479 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001480 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001481 bool IsInheritedVirtualBase,
1482 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001483 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001484 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1485 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001486
Anders Carlsson1b00e242010-04-23 03:10:23 +00001487 Sema::OwningExprResult BaseInit(SemaRef);
1488
1489 switch (ImplicitInitKind) {
1490 case IIK_Default: {
1491 InitializationKind InitKind
1492 = InitializationKind::CreateDefault(Constructor->getLocation());
1493 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1494 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1495 Sema::MultiExprArg(SemaRef, 0, 0));
1496 break;
1497 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001498
Anders Carlsson1b00e242010-04-23 03:10:23 +00001499 case IIK_Copy: {
1500 ParmVarDecl *Param = Constructor->getParamDecl(0);
1501 QualType ParamType = Param->getType().getNonReferenceType();
1502
1503 Expr *CopyCtorArg =
1504 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001505 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001506
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001507 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001508 QualType ArgTy =
1509 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1510 ParamType.getQualifiers());
1511 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001512 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson36db0d92010-04-24 22:54:32 +00001513 /*isLvalue=*/true,
1514 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001515
Anders Carlsson1b00e242010-04-23 03:10:23 +00001516 InitializationKind InitKind
1517 = InitializationKind::CreateDirect(Constructor->getLocation(),
1518 SourceLocation(), SourceLocation());
1519 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1520 &CopyCtorArg, 1);
1521 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1522 Sema::MultiExprArg(SemaRef,
1523 (void**)&CopyCtorArg, 1));
1524 break;
1525 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001526
Anders Carlsson1b00e242010-04-23 03:10:23 +00001527 case IIK_Move:
1528 assert(false && "Unhandled initializer kind!");
1529 }
1530
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001531 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1532 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001533 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001534
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001535 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001536 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1537 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1538 SourceLocation()),
1539 BaseSpec->isVirtual(),
1540 SourceLocation(),
1541 BaseInit.takeAs<Expr>(),
1542 SourceLocation());
1543
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001544 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001545}
1546
Anders Carlsson3c1db572010-04-23 02:15:47 +00001547static bool
1548BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001549 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001550 FieldDecl *Field,
1551 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlsson423f5d82010-04-23 16:04:08 +00001552 if (ImplicitInitKind == IIK_Copy) {
Douglas Gregor94f9a482010-05-05 05:51:00 +00001553 SourceLocation Loc = Constructor->getLocation();
Anders Carlsson423f5d82010-04-23 16:04:08 +00001554 ParmVarDecl *Param = Constructor->getParamDecl(0);
1555 QualType ParamType = Param->getType().getNonReferenceType();
1556
1557 Expr *MemberExprBase =
1558 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001559 Loc, ParamType, 0);
1560
1561 // Build a reference to this field within the parameter.
1562 CXXScopeSpec SS;
1563 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1564 Sema::LookupMemberName);
1565 MemberLookup.addDecl(Field, AS_public);
1566 MemberLookup.resolveKind();
1567 Sema::OwningExprResult CopyCtorArg
1568 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1569 ParamType, Loc,
1570 /*IsArrow=*/false,
1571 SS,
1572 /*FirstQualifierInScope=*/0,
1573 MemberLookup,
1574 /*TemplateArgs=*/0);
1575 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001576 return true;
1577
Douglas Gregor94f9a482010-05-05 05:51:00 +00001578 // When the field we are copying is an array, create index variables for
1579 // each dimension of the array. We use these index variables to subscript
1580 // the source array, and other clients (e.g., CodeGen) will perform the
1581 // necessary iteration with these index variables.
1582 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1583 QualType BaseType = Field->getType();
1584 QualType SizeType = SemaRef.Context.getSizeType();
1585 while (const ConstantArrayType *Array
1586 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1587 // Create the iteration variable for this array index.
1588 IdentifierInfo *IterationVarName = 0;
1589 {
1590 llvm::SmallString<8> Str;
1591 llvm::raw_svector_ostream OS(Str);
1592 OS << "__i" << IndexVariables.size();
1593 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1594 }
1595 VarDecl *IterationVar
1596 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1597 IterationVarName, SizeType,
1598 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1599 VarDecl::None, VarDecl::None);
1600 IndexVariables.push_back(IterationVar);
1601
1602 // Create a reference to the iteration variable.
1603 Sema::OwningExprResult IterationVarRef
1604 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1605 assert(!IterationVarRef.isInvalid() &&
1606 "Reference to invented variable cannot fail!");
1607
1608 // Subscript the array with this iteration variable.
1609 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1610 Loc,
1611 move(IterationVarRef),
1612 Loc);
1613 if (CopyCtorArg.isInvalid())
1614 return true;
1615
1616 BaseType = Array->getElementType();
1617 }
1618
1619 // Construct the entity that we will be initializing. For an array, this
1620 // will be first element in the array, which may require several levels
1621 // of array-subscript entities.
1622 llvm::SmallVector<InitializedEntity, 4> Entities;
1623 Entities.reserve(1 + IndexVariables.size());
1624 Entities.push_back(InitializedEntity::InitializeMember(Field));
1625 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1626 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1627 0,
1628 Entities.back()));
1629
1630 // Direct-initialize to use the copy constructor.
1631 InitializationKind InitKind =
1632 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1633
1634 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1635 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1636 &CopyCtorArgE, 1);
1637
1638 Sema::OwningExprResult MemberInit
1639 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1640 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1641 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1642 if (MemberInit.isInvalid())
1643 return true;
1644
1645 CXXMemberInit
1646 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1647 MemberInit.takeAs<Expr>(), Loc,
1648 IndexVariables.data(),
1649 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001650 return false;
1651 }
1652
Anders Carlsson423f5d82010-04-23 16:04:08 +00001653 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1654
Anders Carlsson3c1db572010-04-23 02:15:47 +00001655 QualType FieldBaseElementType =
1656 SemaRef.Context.getBaseElementType(Field->getType());
1657
Anders Carlsson3c1db572010-04-23 02:15:47 +00001658 if (FieldBaseElementType->isRecordType()) {
1659 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001660 InitializationKind InitKind =
1661 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001662
1663 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1664 Sema::OwningExprResult MemberInit =
1665 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1666 Sema::MultiExprArg(SemaRef, 0, 0));
1667 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1668 if (MemberInit.isInvalid())
1669 return true;
1670
1671 CXXMemberInit =
1672 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1673 Field, SourceLocation(),
1674 SourceLocation(),
1675 MemberInit.takeAs<Expr>(),
1676 SourceLocation());
1677 return false;
1678 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001679
1680 if (FieldBaseElementType->isReferenceType()) {
1681 SemaRef.Diag(Constructor->getLocation(),
1682 diag::err_uninitialized_member_in_ctor)
1683 << (int)Constructor->isImplicit()
1684 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1685 << 0 << Field->getDeclName();
1686 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1687 return true;
1688 }
1689
1690 if (FieldBaseElementType.isConstQualified()) {
1691 SemaRef.Diag(Constructor->getLocation(),
1692 diag::err_uninitialized_member_in_ctor)
1693 << (int)Constructor->isImplicit()
1694 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1695 << 1 << Field->getDeclName();
1696 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1697 return true;
1698 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001699
1700 // Nothing to initialize.
1701 CXXMemberInit = 0;
1702 return false;
1703}
1704
Eli Friedman9cf6b592009-11-09 19:20:36 +00001705bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001706Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001707 CXXBaseOrMemberInitializer **Initializers,
1708 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001709 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001710 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001711 // Just store the initializers as written, they will be checked during
1712 // instantiation.
1713 if (NumInitializers > 0) {
1714 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1715 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1716 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1717 memcpy(baseOrMemberInitializers, Initializers,
1718 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1719 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1720 }
1721
1722 return false;
1723 }
1724
Anders Carlsson1b00e242010-04-23 03:10:23 +00001725 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1726
1727 // FIXME: Handle implicit move constructors.
1728 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1729 ImplicitInitKind = IIK_Copy;
1730
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001731 // We need to build the initializer AST according to order of construction
1732 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001733 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001734 if (!ClassDecl)
1735 return true;
1736
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001737 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1738 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001739 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001740
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001741 for (unsigned i = 0; i < NumInitializers; i++) {
1742 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001743
1744 if (Member->isBaseInitializer())
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001745 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001746 else
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001747 AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001748 }
1749
Anders Carlsson43c64af2010-04-21 19:52:01 +00001750 // Keep track of the direct virtual bases.
1751 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1752 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1753 E = ClassDecl->bases_end(); I != E; ++I) {
1754 if (I->isVirtual())
1755 DirectVBases.insert(I);
1756 }
1757
Anders Carlssondb0a9652010-04-02 06:26:44 +00001758 // Push virtual bases before others.
1759 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1760 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1761
1762 if (CXXBaseOrMemberInitializer *Value
1763 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1764 AllToInit.push_back(Value);
1765 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001766 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001767 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001768 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1769 VBase, IsInheritedVirtualBase,
1770 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001771 HadError = true;
1772 continue;
1773 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001774
Anders Carlssondb0a9652010-04-02 06:26:44 +00001775 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001776 }
1777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
Anders Carlssondb0a9652010-04-02 06:26:44 +00001779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1780 E = ClassDecl->bases_end(); Base != E; ++Base) {
1781 // Virtuals are in the virtual base list and already constructed.
1782 if (Base->isVirtual())
1783 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001784
Anders Carlssondb0a9652010-04-02 06:26:44 +00001785 if (CXXBaseOrMemberInitializer *Value
1786 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1787 AllToInit.push_back(Value);
1788 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001789 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001790 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1791 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001792 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001793 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001794 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001795 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001796
Anders Carlssondb0a9652010-04-02 06:26:44 +00001797 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001798 }
1799 }
Mike Stump11289f42009-09-09 15:08:12 +00001800
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001801 // non-static data members.
1802 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1803 E = ClassDecl->field_end(); Field != E; ++Field) {
1804 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001805 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001806 Field->getType()->getAs<RecordType>()) {
1807 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001808 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001809 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001810 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1811 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1812 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1813 // set to the anonymous union data member used in the initializer
1814 // list.
1815 Value->setMember(*Field);
1816 Value->setAnonUnionMember(*FA);
1817 AllToInit.push_back(Value);
1818 break;
1819 }
1820 }
1821 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00001822
1823 if (ImplicitInitKind == IIK_Default)
1824 continue;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001825 }
1826 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1827 AllToInit.push_back(Value);
1828 continue;
1829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001831 if (AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001832 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001833
Anders Carlsson3c1db572010-04-23 02:15:47 +00001834 CXXBaseOrMemberInitializer *Member;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001835 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1836 *Field, Member)) {
Anders Carlsson3c1db572010-04-23 02:15:47 +00001837 HadError = true;
1838 continue;
1839 }
1840
1841 // If the member doesn't need to be initialized, it will be null.
1842 if (Member)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001843 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001846 NumInitializers = AllToInit.size();
1847 if (NumInitializers > 0) {
1848 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1849 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1850 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCalla6309952010-03-16 21:39:52 +00001851 memcpy(baseOrMemberInitializers, AllToInit.data(),
1852 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001853 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001854
John McCalla6309952010-03-16 21:39:52 +00001855 // Constructors implicitly reference the base and member
1856 // destructors.
1857 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1858 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001859 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001860
1861 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001862}
1863
Eli Friedman952c15d2009-07-21 19:28:10 +00001864static void *GetKeyForTopLevelField(FieldDecl *Field) {
1865 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001866 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001867 if (RT->getDecl()->isAnonymousStructOrUnion())
1868 return static_cast<void *>(RT->getDecl());
1869 }
1870 return static_cast<void *>(Field);
1871}
1872
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001873static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1874 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001875}
1876
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001877static void *GetKeyForMember(ASTContext &Context,
1878 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001879 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001880 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001881 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001882
Eli Friedman952c15d2009-07-21 19:28:10 +00001883 // For fields injected into the class via declaration of an anonymous union,
1884 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001885 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001886
Anders Carlssona942dcd2010-03-30 15:39:27 +00001887 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1888 // data member of the class. Data member used in the initializer list is
1889 // in AnonUnionMember field.
1890 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1891 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001892
John McCall23eebd92010-04-10 09:28:51 +00001893 // If the field is a member of an anonymous struct or union, our key
1894 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001895 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001896 if (RD->isAnonymousStructOrUnion()) {
1897 while (true) {
1898 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1899 if (Parent->isAnonymousStructOrUnion())
1900 RD = Parent;
1901 else
1902 break;
1903 }
1904
Anders Carlsson83ac3122010-03-30 16:19:37 +00001905 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlssona942dcd2010-03-30 15:39:27 +00001908 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001909}
1910
Anders Carlssone857b292010-04-02 03:37:03 +00001911static void
1912DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001913 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001914 CXXBaseOrMemberInitializer **Inits,
1915 unsigned NumInits) {
1916 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001917 return;
Mike Stump11289f42009-09-09 15:08:12 +00001918
John McCallbb7b6582010-04-10 07:37:23 +00001919 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1920 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001921 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001922
John McCallbb7b6582010-04-10 07:37:23 +00001923 // Build the list of bases and members in the order that they'll
1924 // actually be initialized. The explicit initializers should be in
1925 // this same order but may be missing things.
1926 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00001927
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001928 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1929
John McCallbb7b6582010-04-10 07:37:23 +00001930 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001931 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001932 ClassDecl->vbases_begin(),
1933 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001934 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001935
John McCallbb7b6582010-04-10 07:37:23 +00001936 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001937 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001938 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001939 if (Base->isVirtual())
1940 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001941 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001942 }
Mike Stump11289f42009-09-09 15:08:12 +00001943
John McCallbb7b6582010-04-10 07:37:23 +00001944 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001945 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1946 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00001947 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001948
John McCallbb7b6582010-04-10 07:37:23 +00001949 unsigned NumIdealInits = IdealInitKeys.size();
1950 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00001951
John McCallbb7b6582010-04-10 07:37:23 +00001952 CXXBaseOrMemberInitializer *PrevInit = 0;
1953 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1954 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1955 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1956
1957 // Scan forward to try to find this initializer in the idealized
1958 // initializers list.
1959 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1960 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001961 break;
John McCallbb7b6582010-04-10 07:37:23 +00001962
1963 // If we didn't find this initializer, it must be because we
1964 // scanned past it on a previous iteration. That can only
1965 // happen if we're out of order; emit a warning.
1966 if (IdealIndex == NumIdealInits) {
1967 assert(PrevInit && "initializer not found in initializer list");
1968
1969 Sema::SemaDiagnosticBuilder D =
1970 SemaRef.Diag(PrevInit->getSourceLocation(),
1971 diag::warn_initializer_out_of_order);
1972
1973 if (PrevInit->isMemberInitializer())
1974 D << 0 << PrevInit->getMember()->getDeclName();
1975 else
1976 D << 1 << PrevInit->getBaseClassInfo()->getType();
1977
1978 if (Init->isMemberInitializer())
1979 D << 0 << Init->getMember()->getDeclName();
1980 else
1981 D << 1 << Init->getBaseClassInfo()->getType();
1982
1983 // Move back to the initializer's location in the ideal list.
1984 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1985 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001986 break;
John McCallbb7b6582010-04-10 07:37:23 +00001987
1988 assert(IdealIndex != NumIdealInits &&
1989 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001990 }
John McCallbb7b6582010-04-10 07:37:23 +00001991
1992 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001993 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001994}
1995
John McCall23eebd92010-04-10 09:28:51 +00001996namespace {
1997bool CheckRedundantInit(Sema &S,
1998 CXXBaseOrMemberInitializer *Init,
1999 CXXBaseOrMemberInitializer *&PrevInit) {
2000 if (!PrevInit) {
2001 PrevInit = Init;
2002 return false;
2003 }
2004
2005 if (FieldDecl *Field = Init->getMember())
2006 S.Diag(Init->getSourceLocation(),
2007 diag::err_multiple_mem_initialization)
2008 << Field->getDeclName()
2009 << Init->getSourceRange();
2010 else {
2011 Type *BaseClass = Init->getBaseClass();
2012 assert(BaseClass && "neither field nor base");
2013 S.Diag(Init->getSourceLocation(),
2014 diag::err_multiple_base_initialization)
2015 << QualType(BaseClass, 0)
2016 << Init->getSourceRange();
2017 }
2018 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2019 << 0 << PrevInit->getSourceRange();
2020
2021 return true;
2022}
2023
2024typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2025typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2026
2027bool CheckRedundantUnionInit(Sema &S,
2028 CXXBaseOrMemberInitializer *Init,
2029 RedundantUnionMap &Unions) {
2030 FieldDecl *Field = Init->getMember();
2031 RecordDecl *Parent = Field->getParent();
2032 if (!Parent->isAnonymousStructOrUnion())
2033 return false;
2034
2035 NamedDecl *Child = Field;
2036 do {
2037 if (Parent->isUnion()) {
2038 UnionEntry &En = Unions[Parent];
2039 if (En.first && En.first != Child) {
2040 S.Diag(Init->getSourceLocation(),
2041 diag::err_multiple_mem_union_initialization)
2042 << Field->getDeclName()
2043 << Init->getSourceRange();
2044 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2045 << 0 << En.second->getSourceRange();
2046 return true;
2047 } else if (!En.first) {
2048 En.first = Child;
2049 En.second = Init;
2050 }
2051 }
2052
2053 Child = Parent;
2054 Parent = cast<RecordDecl>(Parent->getDeclContext());
2055 } while (Parent->isAnonymousStructOrUnion());
2056
2057 return false;
2058}
2059}
2060
Anders Carlssone857b292010-04-02 03:37:03 +00002061/// ActOnMemInitializers - Handle the member initializers for a constructor.
2062void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2063 SourceLocation ColonLoc,
2064 MemInitTy **meminits, unsigned NumMemInits,
2065 bool AnyErrors) {
2066 if (!ConstructorDecl)
2067 return;
2068
2069 AdjustDeclIfTemplate(ConstructorDecl);
2070
2071 CXXConstructorDecl *Constructor
2072 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2073
2074 if (!Constructor) {
2075 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2076 return;
2077 }
2078
2079 CXXBaseOrMemberInitializer **MemInits =
2080 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002081
2082 // Mapping for the duplicate initializers check.
2083 // For member initializers, this is keyed with a FieldDecl*.
2084 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002085 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002086
2087 // Mapping for the inconsistent anonymous-union initializers check.
2088 RedundantUnionMap MemberUnions;
2089
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002090 bool HadError = false;
2091 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002092 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002093
John McCall23eebd92010-04-10 09:28:51 +00002094 if (Init->isMemberInitializer()) {
2095 FieldDecl *Field = Init->getMember();
2096 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2097 CheckRedundantUnionInit(*this, Init, MemberUnions))
2098 HadError = true;
2099 } else {
2100 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2101 if (CheckRedundantInit(*this, Init, Members[Key]))
2102 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002103 }
Anders Carlssone857b292010-04-02 03:37:03 +00002104 }
2105
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002106 if (HadError)
2107 return;
2108
Anders Carlssone857b292010-04-02 03:37:03 +00002109 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002110
2111 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002112}
2113
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002114void
John McCalla6309952010-03-16 21:39:52 +00002115Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2116 CXXRecordDecl *ClassDecl) {
2117 // Ignore dependent contexts.
2118 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002119 return;
John McCall1064d7e2010-03-16 05:22:47 +00002120
2121 // FIXME: all the access-control diagnostics are positioned on the
2122 // field/base declaration. That's probably good; that said, the
2123 // user might reasonably want to know why the destructor is being
2124 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002125
Anders Carlssondee9a302009-11-17 04:44:12 +00002126 // Non-static data members.
2127 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2128 E = ClassDecl->field_end(); I != E; ++I) {
2129 FieldDecl *Field = *I;
2130
2131 QualType FieldType = Context.getBaseElementType(Field->getType());
2132
2133 const RecordType* RT = FieldType->getAs<RecordType>();
2134 if (!RT)
2135 continue;
2136
2137 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2138 if (FieldClassDecl->hasTrivialDestructor())
2139 continue;
2140
John McCall1064d7e2010-03-16 05:22:47 +00002141 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2142 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002143 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002144 << Field->getDeclName()
2145 << FieldType);
2146
John McCalla6309952010-03-16 21:39:52 +00002147 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002148 }
2149
John McCall1064d7e2010-03-16 05:22:47 +00002150 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2151
Anders Carlssondee9a302009-11-17 04:44:12 +00002152 // Bases.
2153 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2154 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002155 // Bases are always records in a well-formed non-dependent class.
2156 const RecordType *RT = Base->getType()->getAs<RecordType>();
2157
2158 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002159 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002160 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002161
2162 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002164 if (BaseClassDecl->hasTrivialDestructor())
2165 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002166
2167 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2168
2169 // FIXME: caret should be on the start of the class name
2170 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002171 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002172 << Base->getType()
2173 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002174
John McCalla6309952010-03-16 21:39:52 +00002175 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002176 }
2177
2178 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002179 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2180 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002181
2182 // Bases are always records in a well-formed non-dependent class.
2183 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2184
2185 // Ignore direct virtual bases.
2186 if (DirectVirtualBases.count(RT))
2187 continue;
2188
Anders Carlssondee9a302009-11-17 04:44:12 +00002189 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002190 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002191 if (BaseClassDecl->hasTrivialDestructor())
2192 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002193
2194 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2195 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002196 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002197 << VBase->getType());
2198
John McCalla6309952010-03-16 21:39:52 +00002199 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002200 }
2201}
2202
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002203void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002204 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002205 return;
Mike Stump11289f42009-09-09 15:08:12 +00002206
Mike Stump11289f42009-09-09 15:08:12 +00002207 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002208 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002209 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002210}
2211
Mike Stump11289f42009-09-09 15:08:12 +00002212bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002213 unsigned DiagID, AbstractDiagSelID SelID,
2214 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002215 if (SelID == -1)
2216 return RequireNonAbstractType(Loc, T,
2217 PDiag(DiagID), CurrentRD);
2218 else
2219 return RequireNonAbstractType(Loc, T,
2220 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002221}
2222
Anders Carlssoneabf7702009-08-27 00:13:57 +00002223bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2224 const PartialDiagnostic &PD,
2225 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002226 if (!getLangOptions().CPlusPlus)
2227 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002228
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002229 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002230 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002231 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002233 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002234 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002235 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002236 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002237
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002238 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002239 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002240 }
Mike Stump11289f42009-09-09 15:08:12 +00002241
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002242 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002243 if (!RT)
2244 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002245
John McCall67da35c2010-02-04 22:26:26 +00002246 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002247
Anders Carlssonb57738b2009-03-24 17:23:42 +00002248 if (CurrentRD && CurrentRD != RD)
2249 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002250
John McCall67da35c2010-02-04 22:26:26 +00002251 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002252 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002253 return false;
2254
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002255 if (!RD->isAbstract())
2256 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002257
Anders Carlssoneabf7702009-08-27 00:13:57 +00002258 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002259
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002260 // Check if we've already emitted the list of pure virtual functions for this
2261 // class.
2262 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2263 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002264
Douglas Gregor4165bd62010-03-23 23:47:56 +00002265 CXXFinalOverriderMap FinalOverriders;
2266 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002267
Douglas Gregor4165bd62010-03-23 23:47:56 +00002268 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2269 MEnd = FinalOverriders.end();
2270 M != MEnd;
2271 ++M) {
2272 for (OverridingMethods::iterator SO = M->second.begin(),
2273 SOEnd = M->second.end();
2274 SO != SOEnd; ++SO) {
2275 // C++ [class.abstract]p4:
2276 // A class is abstract if it contains or inherits at least one
2277 // pure virtual function for which the final overrider is pure
2278 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002279
Douglas Gregor4165bd62010-03-23 23:47:56 +00002280 //
2281 if (SO->second.size() != 1)
2282 continue;
2283
2284 if (!SO->second.front().Method->isPure())
2285 continue;
2286
2287 Diag(SO->second.front().Method->getLocation(),
2288 diag::note_pure_virtual_function)
2289 << SO->second.front().Method->getDeclName();
2290 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002291 }
2292
2293 if (!PureVirtualClassDiagSet)
2294 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2295 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002296
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002297 return true;
2298}
2299
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002300namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002301 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002302 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2303 Sema &SemaRef;
2304 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002305
Anders Carlssonb57738b2009-03-24 17:23:42 +00002306 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002307 bool Invalid = false;
2308
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002309 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2310 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002311 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002312
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002313 return Invalid;
2314 }
Mike Stump11289f42009-09-09 15:08:12 +00002315
Anders Carlssonb57738b2009-03-24 17:23:42 +00002316 public:
2317 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2318 : SemaRef(SemaRef), AbstractClass(ac) {
2319 Visit(SemaRef.Context.getTranslationUnitDecl());
2320 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002321
Anders Carlssonb57738b2009-03-24 17:23:42 +00002322 bool VisitFunctionDecl(const FunctionDecl *FD) {
2323 if (FD->isThisDeclarationADefinition()) {
2324 // No need to do the check if we're in a definition, because it requires
2325 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002326 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002327 return VisitDeclContext(FD);
2328 }
Mike Stump11289f42009-09-09 15:08:12 +00002329
Anders Carlssonb57738b2009-03-24 17:23:42 +00002330 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002331 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002332 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002333 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2334 diag::err_abstract_type_in_decl,
2335 Sema::AbstractReturnType,
2336 AbstractClass);
2337
Mike Stump11289f42009-09-09 15:08:12 +00002338 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002339 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002340 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002341 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002342 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002343 VD->getOriginalType(),
2344 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002345 Sema::AbstractParamType,
2346 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002347 }
2348
2349 return Invalid;
2350 }
Mike Stump11289f42009-09-09 15:08:12 +00002351
Anders Carlssonb57738b2009-03-24 17:23:42 +00002352 bool VisitDecl(const Decl* D) {
2353 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2354 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002355
Anders Carlssonb57738b2009-03-24 17:23:42 +00002356 return false;
2357 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002358 };
2359}
2360
Douglas Gregorc99f1552009-12-03 18:33:45 +00002361/// \brief Perform semantic checks on a class definition that has been
2362/// completing, introducing implicitly-declared members, checking for
2363/// abstract types, etc.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002364void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002365 if (!Record || Record->isInvalidDecl())
2366 return;
2367
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002368 if (!Record->isDependentType())
Douglas Gregorb93b6062010-04-12 17:09:20 +00002369 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002370
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002371 if (Record->isInvalidDecl())
2372 return;
2373
John McCall2cb94162010-01-28 07:38:46 +00002374 // Set access bits correctly on the directly-declared conversions.
2375 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2376 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2377 Convs->setAccess(I, (*I)->getAccess());
2378
Douglas Gregor4165bd62010-03-23 23:47:56 +00002379 // Determine whether we need to check for final overriders. We do
2380 // this either when there are virtual base classes (in which case we
2381 // may end up finding multiple final overriders for a given virtual
2382 // function) or any of the base classes is abstract (in which case
2383 // we might detect that this class is abstract).
2384 bool CheckFinalOverriders = false;
2385 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2386 !Record->isDependentType()) {
2387 if (Record->getNumVBases())
2388 CheckFinalOverriders = true;
2389 else if (!Record->isAbstract()) {
2390 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2391 BEnd = Record->bases_end();
2392 B != BEnd; ++B) {
2393 CXXRecordDecl *BaseDecl
2394 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2395 if (BaseDecl->isAbstract()) {
2396 CheckFinalOverriders = true;
2397 break;
2398 }
2399 }
2400 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002401 }
2402
Douglas Gregor4165bd62010-03-23 23:47:56 +00002403 if (CheckFinalOverriders) {
2404 CXXFinalOverriderMap FinalOverriders;
2405 Record->getFinalOverriders(FinalOverriders);
2406
2407 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2408 MEnd = FinalOverriders.end();
2409 M != MEnd; ++M) {
2410 for (OverridingMethods::iterator SO = M->second.begin(),
2411 SOEnd = M->second.end();
2412 SO != SOEnd; ++SO) {
2413 assert(SO->second.size() > 0 &&
2414 "All virtual functions have overridding virtual functions");
2415 if (SO->second.size() == 1) {
2416 // C++ [class.abstract]p4:
2417 // A class is abstract if it contains or inherits at least one
2418 // pure virtual function for which the final overrider is pure
2419 // virtual.
2420 if (SO->second.front().Method->isPure())
2421 Record->setAbstract(true);
2422 continue;
2423 }
2424
2425 // C++ [class.virtual]p2:
2426 // In a derived class, if a virtual member function of a base
2427 // class subobject has more than one final overrider the
2428 // program is ill-formed.
2429 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2430 << (NamedDecl *)M->first << Record;
2431 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2432 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2433 OMEnd = SO->second.end();
2434 OM != OMEnd; ++OM)
2435 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2436 << (NamedDecl *)M->first << OM->Method->getParent();
2437
2438 Record->setInvalidDecl();
2439 }
2440 }
2441 }
2442
2443 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregorc99f1552009-12-03 18:33:45 +00002444 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-04-15 00:00:53 +00002445
2446 // If this is not an aggregate type and has no user-declared constructor,
2447 // complain about any non-static data members of reference or const scalar
2448 // type, since they will never get initializers.
2449 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2450 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2451 bool Complained = false;
2452 for (RecordDecl::field_iterator F = Record->field_begin(),
2453 FEnd = Record->field_end();
2454 F != FEnd; ++F) {
2455 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002456 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002457 if (!Complained) {
2458 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2459 << Record->getTagKind() << Record;
2460 Complained = true;
2461 }
2462
2463 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2464 << F->getType()->isReferenceType()
2465 << F->getDeclName();
2466 }
2467 }
2468 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002469}
2470
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002471void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002472 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002473 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002474 SourceLocation RBrac,
2475 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002476 if (!TagDecl)
2477 return;
Mike Stump11289f42009-09-09 15:08:12 +00002478
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002479 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002480
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002481 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002482 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002483 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002484
Douglas Gregorb93b6062010-04-12 17:09:20 +00002485 CheckCompletedCXXClass(S,
Douglas Gregorc99f1552009-12-03 18:33:45 +00002486 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002487}
2488
Douglas Gregor05379422008-11-03 17:51:48 +00002489/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2490/// special functions, such as the default constructor, copy
2491/// constructor, or destructor, to the given C++ class (C++
2492/// [special]p1). This routine can only be executed just before the
2493/// definition of the class is complete.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002494///
2495/// The scope, if provided, is the class scope.
2496void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2497 CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002498 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002499 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002500
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002501 // FIXME: Implicit declarations have exception specifications, which are
2502 // the union of the specifications of the implicitly called functions.
2503
Douglas Gregor05379422008-11-03 17:51:48 +00002504 if (!ClassDecl->hasUserDeclaredConstructor()) {
2505 // C++ [class.ctor]p5:
2506 // A default constructor for a class X is a constructor of class X
2507 // that can be called without an argument. If there is no
2508 // user-declared constructor for class X, a default constructor is
2509 // implicitly declared. An implicitly-declared default constructor
2510 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002511 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002512 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002513 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002514 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002515 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002516 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002517 0, 0, false, 0,
2518 /*FIXME*/false, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002519 0, 0,
2520 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002521 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002522 /*isExplicit=*/false,
2523 /*isInline=*/true,
2524 /*isImplicitlyDeclared=*/true);
2525 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002526 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002527 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002528 if (S)
2529 PushOnScopeChains(DefaultCon, S, true);
2530 else
2531 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002532 }
2533
2534 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2535 // C++ [class.copy]p4:
2536 // If the class definition does not explicitly declare a copy
2537 // constructor, one is declared implicitly.
2538
2539 // C++ [class.copy]p5:
2540 // The implicitly-declared copy constructor for a class X will
2541 // have the form
2542 //
2543 // X::X(const X&)
2544 //
2545 // if
2546 bool HasConstCopyConstructor = true;
2547
2548 // -- each direct or virtual base class B of X has a copy
2549 // constructor whose first parameter is of type const B& or
2550 // const volatile B&, and
2551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2552 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2553 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002554 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002555 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002556 = BaseClassDecl->hasConstCopyConstructor(Context);
2557 }
2558
2559 // -- for all the nonstatic data members of X that are of a
2560 // class type M (or array thereof), each such class type
2561 // has a copy constructor whose first parameter is of type
2562 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002563 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2564 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002565 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002566 QualType FieldType = (*Field)->getType();
2567 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2568 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002569 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002570 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002571 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002572 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002573 = FieldClassDecl->hasConstCopyConstructor(Context);
2574 }
2575 }
2576
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002577 // Otherwise, the implicitly declared copy constructor will have
2578 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002579 //
2580 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002581 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002582 if (HasConstCopyConstructor)
2583 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002584 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002585
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002586 // An implicitly-declared copy constructor is an inline public
2587 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002588 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002589 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002590 CXXConstructorDecl *CopyConstructor
2591 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002592 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002593 Context.getFunctionType(Context.VoidTy,
2594 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002595 false, 0,
2596 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002597 false, 0, 0,
2598 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002599 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002600 /*isExplicit=*/false,
2601 /*isInline=*/true,
2602 /*isImplicitlyDeclared=*/true);
2603 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002604 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002605 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002606
2607 // Add the parameter to the constructor.
2608 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2609 ClassDecl->getLocation(),
2610 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002611 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002612 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002613 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002614 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregorb93b6062010-04-12 17:09:20 +00002615 if (S)
2616 PushOnScopeChains(CopyConstructor, S, true);
2617 else
2618 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002619 }
2620
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002621 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2622 // Note: The following rules are largely analoguous to the copy
2623 // constructor rules. Note that virtual bases are not taken into account
2624 // for determining the argument type of the operator. Note also that
2625 // operators taking an object instead of a reference are allowed.
2626 //
2627 // C++ [class.copy]p10:
2628 // If the class definition does not explicitly declare a copy
2629 // assignment operator, one is declared implicitly.
2630 // The implicitly-defined copy assignment operator for a class X
2631 // will have the form
2632 //
2633 // X& X::operator=(const X&)
2634 //
2635 // if
2636 bool HasConstCopyAssignment = true;
2637
2638 // -- each direct base class B of X has a copy assignment operator
2639 // whose parameter is of type const B&, const volatile B& or B,
2640 // and
2641 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2642 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002643 assert(!Base->getType()->isDependentType() &&
2644 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002645 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002646 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002647 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002648 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002649 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002650 }
2651
2652 // -- for all the nonstatic data members of X that are of a class
2653 // type M (or array thereof), each such class type has a copy
2654 // assignment operator whose parameter is of type const M&,
2655 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002656 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2657 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002658 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002659 QualType FieldType = (*Field)->getType();
2660 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2661 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002662 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002663 const CXXRecordDecl *FieldClassDecl
2664 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002665 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002666 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002667 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002668 }
2669 }
2670
2671 // Otherwise, the implicitly declared copy assignment operator will
2672 // have the form
2673 //
2674 // X& X::operator=(X&)
2675 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002676 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002677 if (HasConstCopyAssignment)
2678 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002679 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002680
2681 // An implicitly-declared copy assignment operator is an inline public
2682 // member of its class.
2683 DeclarationName Name =
2684 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2685 CXXMethodDecl *CopyAssignment =
2686 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2687 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002688 false, 0,
2689 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002690 false, 0, 0,
2691 FunctionType::ExtInfo()),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002692 /*TInfo=*/0, /*isStatic=*/false,
2693 /*StorageClassAsWritten=*/FunctionDecl::None,
2694 /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002695 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002696 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002697 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002698 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002699
2700 // Add the parameter to the operator.
2701 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2702 ClassDecl->getLocation(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00002703 /*Id=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002704 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002705 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002706 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002707 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002708
2709 // Don't call addedAssignmentOperator. There is no way to distinguish an
2710 // implicit from an explicit assignment operator.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002711 if (S)
2712 PushOnScopeChains(CopyAssignment, S, true);
2713 else
2714 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002715 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002716 }
2717
Douglas Gregor1349b452008-12-15 21:24:18 +00002718 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002719 // C++ [class.dtor]p2:
2720 // If a class has no user-declared destructor, a destructor is
2721 // declared implicitly. An implicitly-declared destructor is an
2722 // inline public member of its class.
John McCall58f10c32010-03-11 09:03:00 +00002723 QualType Ty = Context.getFunctionType(Context.VoidTy,
2724 0, 0, false, 0,
2725 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002726 false, 0, 0, FunctionType::ExtInfo());
John McCall58f10c32010-03-11 09:03:00 +00002727
Mike Stump11289f42009-09-09 15:08:12 +00002728 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002729 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002730 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002731 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall58f10c32010-03-11 09:03:00 +00002732 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002733 /*isInline=*/true,
2734 /*isImplicitlyDeclared=*/true);
2735 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002736 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002737 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002738 if (S)
2739 PushOnScopeChains(Destructor, S, true);
2740 else
2741 ClassDecl->addDecl(Destructor);
John McCall58f10c32010-03-11 09:03:00 +00002742
2743 // This could be uniqued if it ever proves significant.
2744 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002745
2746 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002747 }
Douglas Gregor05379422008-11-03 17:51:48 +00002748}
2749
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002750void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002751 Decl *D = TemplateD.getAs<Decl>();
2752 if (!D)
2753 return;
2754
2755 TemplateParameterList *Params = 0;
2756 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2757 Params = Template->getTemplateParameters();
2758 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2759 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2760 Params = PartialSpec->getTemplateParameters();
2761 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002762 return;
2763
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002764 for (TemplateParameterList::iterator Param = Params->begin(),
2765 ParamEnd = Params->end();
2766 Param != ParamEnd; ++Param) {
2767 NamedDecl *Named = cast<NamedDecl>(*Param);
2768 if (Named->getDeclName()) {
2769 S->AddDecl(DeclPtrTy::make(Named));
2770 IdResolver.AddDecl(Named);
2771 }
2772 }
2773}
2774
John McCall6df5fef2009-12-19 10:49:29 +00002775void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2776 if (!RecordD) return;
2777 AdjustDeclIfTemplate(RecordD);
2778 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2779 PushDeclContext(S, Record);
2780}
2781
2782void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2783 if (!RecordD) return;
2784 PopDeclContext();
2785}
2786
Douglas Gregor4d87df52008-12-16 21:30:33 +00002787/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2788/// parsing a top-level (non-nested) C++ class, and we are now
2789/// parsing those parts of the given Method declaration that could
2790/// not be parsed earlier (C++ [class.mem]p2), such as default
2791/// arguments. This action should enter the scope of the given
2792/// Method declaration as if we had just parsed the qualified method
2793/// name. However, it should not bring the parameters into scope;
2794/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002795void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002796}
2797
2798/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2799/// C++ method declaration. We're (re-)introducing the given
2800/// function parameter into scope for use in parsing later parts of
2801/// the method declaration. For example, we could see an
2802/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002803void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002804 if (!ParamD)
2805 return;
Mike Stump11289f42009-09-09 15:08:12 +00002806
Chris Lattner83f095c2009-03-28 19:18:32 +00002807 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002808
2809 // If this parameter has an unparsed default argument, clear it out
2810 // to make way for the parsed default argument.
2811 if (Param->hasUnparsedDefaultArg())
2812 Param->setDefaultArg(0);
2813
Chris Lattner83f095c2009-03-28 19:18:32 +00002814 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002815 if (Param->getDeclName())
2816 IdResolver.AddDecl(Param);
2817}
2818
2819/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2820/// processing the delayed method declaration for Method. The method
2821/// declaration is now considered finished. There may be a separate
2822/// ActOnStartOfFunctionDef action later (not necessarily
2823/// immediately!) for this method, if it was also defined inside the
2824/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002825void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002826 if (!MethodD)
2827 return;
Mike Stump11289f42009-09-09 15:08:12 +00002828
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002829 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002830
Chris Lattner83f095c2009-03-28 19:18:32 +00002831 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002832
2833 // Now that we have our default arguments, check the constructor
2834 // again. It could produce additional diagnostics or affect whether
2835 // the class has implicitly-declared destructors, among other
2836 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002837 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2838 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002839
2840 // Check the default arguments, which we may have added.
2841 if (!Method->isInvalidDecl())
2842 CheckCXXDefaultArguments(Method);
2843}
2844
Douglas Gregor831c93f2008-11-05 20:51:48 +00002845/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002846/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002847/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002848/// emit diagnostics and set the invalid bit to true. In any case, the type
2849/// will be updated to reflect a well-formed type for the constructor and
2850/// returned.
2851QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2852 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002853 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002854
2855 // C++ [class.ctor]p3:
2856 // A constructor shall not be virtual (10.3) or static (9.4). A
2857 // constructor can be invoked for a const, volatile or const
2858 // volatile object. A constructor shall not be declared const,
2859 // volatile, or const volatile (9.3.2).
2860 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002861 if (!D.isInvalidType())
2862 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2863 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2864 << SourceRange(D.getIdentifierLoc());
2865 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002866 }
2867 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002868 if (!D.isInvalidType())
2869 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2870 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2871 << SourceRange(D.getIdentifierLoc());
2872 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002873 SC = FunctionDecl::None;
2874 }
Mike Stump11289f42009-09-09 15:08:12 +00002875
Chris Lattner38378bf2009-04-25 08:28:21 +00002876 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2877 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002878 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002879 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2880 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002881 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002882 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2883 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002884 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002885 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2886 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
Douglas Gregor831c93f2008-11-05 20:51:48 +00002889 // Rebuild the function type "R" without any type qualifiers (in
2890 // case any of the errors above fired) and with "void" as the
2891 // return type, since constructors don't have return types. We
2892 // *always* have to do this, because GetTypeForDeclarator will
2893 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002894 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002895 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2896 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002897 Proto->isVariadic(), 0,
2898 Proto->hasExceptionSpec(),
2899 Proto->hasAnyExceptionSpec(),
2900 Proto->getNumExceptions(),
2901 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002902 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002903}
2904
Douglas Gregor4d87df52008-12-16 21:30:33 +00002905/// CheckConstructor - Checks a fully-formed constructor for
2906/// well-formedness, issuing any diagnostics required. Returns true if
2907/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002908void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002909 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002910 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2911 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002912 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002913
2914 // C++ [class.copy]p3:
2915 // A declaration of a constructor for a class X is ill-formed if
2916 // its first parameter is of type (optionally cv-qualified) X and
2917 // either there are no other parameters or else all other
2918 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002919 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002920 ((Constructor->getNumParams() == 1) ||
2921 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002922 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2923 Constructor->getTemplateSpecializationKind()
2924 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002925 QualType ParamType = Constructor->getParamDecl(0)->getType();
2926 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2927 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002928 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2929 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregora771f462010-03-31 17:46:05 +00002930 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002931
2932 // FIXME: Rather that making the constructor invalid, we should endeavor
2933 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002934 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002935 }
2936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
John McCall43314ab2010-04-13 07:45:41 +00002938 // Notify the class that we've added a constructor. In principle we
2939 // don't need to do this for out-of-line declarations; in practice
2940 // we only instantiate the most recent declaration of a method, so
2941 // we have to call this for everything but friends.
2942 if (!Constructor->getFriendObjectKind())
2943 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002944}
2945
Anders Carlsson26a807d2009-11-30 21:24:50 +00002946/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2947/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002948bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002949 CXXRecordDecl *RD = Destructor->getParent();
2950
2951 if (Destructor->isVirtual()) {
2952 SourceLocation Loc;
2953
2954 if (!Destructor->isImplicit())
2955 Loc = Destructor->getLocation();
2956 else
2957 Loc = RD->getLocation();
2958
2959 // If we have a virtual destructor, look up the deallocation function
2960 FunctionDecl *OperatorDelete = 0;
2961 DeclarationName Name =
2962 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002963 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002964 return true;
2965
2966 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002967 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002968
2969 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002970}
2971
Mike Stump11289f42009-09-09 15:08:12 +00002972static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002973FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2974 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2975 FTI.ArgInfo[0].Param &&
2976 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2977}
2978
Douglas Gregor831c93f2008-11-05 20:51:48 +00002979/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2980/// the well-formednes of the destructor declarator @p D with type @p
2981/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002982/// emit diagnostics and set the declarator to invalid. Even if this happens,
2983/// will be updated to reflect a well-formed type for the destructor and
2984/// returned.
2985QualType Sema::CheckDestructorDeclarator(Declarator &D,
2986 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002987 // C++ [class.dtor]p1:
2988 // [...] A typedef-name that names a class is a class-name
2989 // (7.1.3); however, a typedef-name that names a class shall not
2990 // be used as the identifier in the declarator for a destructor
2991 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002992 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002993 if (isa<TypedefType>(DeclaratorType)) {
2994 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002995 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002996 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002997 }
2998
2999 // C++ [class.dtor]p2:
3000 // A destructor is used to destroy objects of its class type. A
3001 // destructor takes no parameters, and no return type can be
3002 // specified for it (not even void). The address of a destructor
3003 // shall not be taken. A destructor shall not be static. A
3004 // destructor can be invoked for a const, volatile or const
3005 // volatile object. A destructor shall not be declared const,
3006 // volatile or const volatile (9.3.2).
3007 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003008 if (!D.isInvalidType())
3009 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3010 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3011 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003012 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00003013 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003014 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003015 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003016 // Destructors don't have return types, but the parser will
3017 // happily parse something like:
3018 //
3019 // class X {
3020 // float ~X();
3021 // };
3022 //
3023 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003024 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3025 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3026 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003027 }
Mike Stump11289f42009-09-09 15:08:12 +00003028
Chris Lattner38378bf2009-04-25 08:28:21 +00003029 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3030 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003031 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003032 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3033 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003034 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003035 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3036 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003037 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003038 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3039 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003040 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003041 }
3042
3043 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003044 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003045 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3046
3047 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003048 FTI.freeArgs();
3049 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003050 }
3051
Mike Stump11289f42009-09-09 15:08:12 +00003052 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003053 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003054 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003055 D.setInvalidType();
3056 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003057
3058 // Rebuild the function type "R" without any type qualifiers or
3059 // parameters (in case any of the errors above fired) and with
3060 // "void" as the return type, since destructors don't have return
3061 // types. We *always* have to do this, because GetTypeForDeclarator
3062 // will put in a result type of "int" when none was specified.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003063 // FIXME: Exceptions!
3064 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003065 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003066}
3067
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003068/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3069/// well-formednes of the conversion function declarator @p D with
3070/// type @p R. If there are any errors in the declarator, this routine
3071/// will emit diagnostics and return true. Otherwise, it will return
3072/// false. Either way, the type @p R will be updated to reflect a
3073/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003074void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003075 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003076 // C++ [class.conv.fct]p1:
3077 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003078 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003079 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003080 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003081 if (!D.isInvalidType())
3082 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3083 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3084 << SourceRange(D.getIdentifierLoc());
3085 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003086 SC = FunctionDecl::None;
3087 }
John McCall212fa2e2010-04-13 00:04:31 +00003088
3089 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3090
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003091 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003092 // Conversion functions don't have return types, but the parser will
3093 // happily parse something like:
3094 //
3095 // class X {
3096 // float operator bool();
3097 // };
3098 //
3099 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003100 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3101 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3102 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003103 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003104 }
3105
John McCall212fa2e2010-04-13 00:04:31 +00003106 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3107
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003108 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003109 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003110 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3111
3112 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003113 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003114 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003115 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003116 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003117 D.setInvalidType();
3118 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003119
John McCall212fa2e2010-04-13 00:04:31 +00003120 // Diagnose "&operator bool()" and other such nonsense. This
3121 // is actually a gcc extension which we don't support.
3122 if (Proto->getResultType() != ConvType) {
3123 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3124 << Proto->getResultType();
3125 D.setInvalidType();
3126 ConvType = Proto->getResultType();
3127 }
3128
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003129 // C++ [class.conv.fct]p4:
3130 // The conversion-type-id shall not represent a function type nor
3131 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003132 if (ConvType->isArrayType()) {
3133 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3134 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003135 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003136 } else if (ConvType->isFunctionType()) {
3137 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3138 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003139 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003140 }
3141
3142 // Rebuild the function type "R" without any parameters (in case any
3143 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003144 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003145 if (D.isInvalidType()) {
3146 R = Context.getFunctionType(ConvType, 0, 0, false,
3147 Proto->getTypeQuals(),
3148 Proto->hasExceptionSpec(),
3149 Proto->hasAnyExceptionSpec(),
3150 Proto->getNumExceptions(),
3151 Proto->exception_begin(),
3152 Proto->getExtInfo());
3153 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003154
Douglas Gregor5fb53972009-01-14 15:45:31 +00003155 // C++0x explicit conversion operators.
3156 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003157 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003158 diag::warn_explicit_conversion_functions)
3159 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003160}
3161
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003162/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3163/// the declaration of the given C++ conversion function. This routine
3164/// is responsible for recording the conversion function in the C++
3165/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00003166Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003167 assert(Conversion && "Expected to receive a conversion function declaration");
3168
Douglas Gregor4287b372008-12-12 08:25:50 +00003169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003170
3171 // Make sure we aren't redeclaring the conversion function.
3172 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173
3174 // C++ [class.conv.fct]p1:
3175 // [...] A conversion function is never used to convert a
3176 // (possibly cv-qualified) object to the (possibly cv-qualified)
3177 // same object type (or a reference to it), to a (possibly
3178 // cv-qualified) base class of that type (or a reference to it),
3179 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003180 // FIXME: Suppress this warning if the conversion function ends up being a
3181 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003182 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003183 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003184 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003185 ConvType = ConvTypeRef->getPointeeType();
3186 if (ConvType->isRecordType()) {
3187 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3188 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003189 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003190 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003191 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003192 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003193 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003194 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003195 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003196 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003197 }
3198
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003199 if (Conversion->getPrimaryTemplate()) {
3200 // ignore specializations
3201 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003202 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003203 = Conversion->getDescribedFunctionTemplate()) {
3204 if (ClassDecl->replaceConversion(
3205 ConversionTemplate->getPreviousDeclaration(),
3206 ConversionTemplate))
3207 return DeclPtrTy::make(ConversionTemplate);
3208 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3209 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00003210 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003211 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003212 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003213 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003214 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003215 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003216 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003217
Chris Lattner83f095c2009-03-28 19:18:32 +00003218 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003219}
3220
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003221//===----------------------------------------------------------------------===//
3222// Namespace Handling
3223//===----------------------------------------------------------------------===//
3224
3225/// ActOnStartNamespaceDef - This is called at the start of a namespace
3226/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00003227Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3228 SourceLocation IdentLoc,
3229 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003230 SourceLocation LBrace,
3231 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003232 NamespaceDecl *Namespc =
3233 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3234 Namespc->setLBracLoc(LBrace);
3235
3236 Scope *DeclRegionScope = NamespcScope->getParent();
3237
Anders Carlssona7bcade2010-02-07 01:09:23 +00003238 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3239
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003240 if (II) {
3241 // C++ [namespace.def]p2:
3242 // The identifier in an original-namespace-definition shall not have been
3243 // previously defined in the declarative region in which the
3244 // original-namespace-definition appears. The identifier in an
3245 // original-namespace-definition is the name of the namespace. Subsequently
3246 // in that declarative region, it is treated as an original-namespace-name.
3247
John McCall9f3059a2009-10-09 21:13:30 +00003248 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003249 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003250 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003251
Douglas Gregor91f84212008-12-11 16:49:14 +00003252 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3253 // This is an extended namespace definition.
3254 // Attach this namespace decl to the chain of extended namespace
3255 // definitions.
3256 OrigNS->setNextNamespace(Namespc);
3257 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003258
Mike Stump11289f42009-09-09 15:08:12 +00003259 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003260 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003261 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003262 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003263 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003264 } else if (PrevDecl) {
3265 // This is an invalid name redefinition.
3266 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3267 << Namespc->getDeclName();
3268 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3269 Namespc->setInvalidDecl();
3270 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003271 } else if (II->isStr("std") &&
3272 CurContext->getLookupContext()->isTranslationUnit()) {
3273 // This is the first "real" definition of the namespace "std", so update
3274 // our cache of the "std" namespace to point at this definition.
3275 if (StdNamespace) {
3276 // We had already defined a dummy namespace "std". Link this new
3277 // namespace definition to the dummy namespace "std".
3278 StdNamespace->setNextNamespace(Namespc);
3279 StdNamespace->setLocation(IdentLoc);
3280 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3281 }
3282
3283 // Make our StdNamespace cache point at the first real definition of the
3284 // "std" namespace.
3285 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003286 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003287
3288 PushOnScopeChains(Namespc, DeclRegionScope);
3289 } else {
John McCall4fa53422009-10-01 00:25:31 +00003290 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003291 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003292
3293 // Link the anonymous namespace into its parent.
3294 NamespaceDecl *PrevDecl;
3295 DeclContext *Parent = CurContext->getLookupContext();
3296 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3297 PrevDecl = TU->getAnonymousNamespace();
3298 TU->setAnonymousNamespace(Namespc);
3299 } else {
3300 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3301 PrevDecl = ND->getAnonymousNamespace();
3302 ND->setAnonymousNamespace(Namespc);
3303 }
3304
3305 // Link the anonymous namespace with its previous declaration.
3306 if (PrevDecl) {
3307 assert(PrevDecl->isAnonymousNamespace());
3308 assert(!PrevDecl->getNextNamespace());
3309 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3310 PrevDecl->setNextNamespace(Namespc);
3311 }
John McCall4fa53422009-10-01 00:25:31 +00003312
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003313 CurContext->addDecl(Namespc);
3314
John McCall4fa53422009-10-01 00:25:31 +00003315 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3316 // behaves as if it were replaced by
3317 // namespace unique { /* empty body */ }
3318 // using namespace unique;
3319 // namespace unique { namespace-body }
3320 // where all occurrences of 'unique' in a translation unit are
3321 // replaced by the same identifier and this identifier differs
3322 // from all other identifiers in the entire program.
3323
3324 // We just create the namespace with an empty name and then add an
3325 // implicit using declaration, just like the standard suggests.
3326 //
3327 // CodeGen enforces the "universally unique" aspect by giving all
3328 // declarations semantically contained within an anonymous
3329 // namespace internal linkage.
3330
John McCall0db42252009-12-16 02:06:49 +00003331 if (!PrevDecl) {
3332 UsingDirectiveDecl* UD
3333 = UsingDirectiveDecl::Create(Context, CurContext,
3334 /* 'using' */ LBrace,
3335 /* 'namespace' */ SourceLocation(),
3336 /* qualifier */ SourceRange(),
3337 /* NNS */ NULL,
3338 /* identifier */ SourceLocation(),
3339 Namespc,
3340 /* Ancestor */ CurContext);
3341 UD->setImplicit();
3342 CurContext->addDecl(UD);
3343 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003344 }
3345
3346 // Although we could have an invalid decl (i.e. the namespace name is a
3347 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003348 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3349 // for the namespace has the declarations that showed up in that particular
3350 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003351 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003352 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003353}
3354
Sebastian Redla6602e92009-11-23 15:34:23 +00003355/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3356/// is a namespace alias, returns the namespace it points to.
3357static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3358 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3359 return AD->getNamespace();
3360 return dyn_cast_or_null<NamespaceDecl>(D);
3361}
3362
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003363/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3364/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003365void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3366 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003367 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3368 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3369 Namespc->setRBracLoc(RBrace);
3370 PopDeclContext();
3371}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003372
Chris Lattner83f095c2009-03-28 19:18:32 +00003373Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3374 SourceLocation UsingLoc,
3375 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003376 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003377 SourceLocation IdentLoc,
3378 IdentifierInfo *NamespcName,
3379 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003380 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3381 assert(NamespcName && "Invalid NamespcName.");
3382 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003383 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003384
Douglas Gregor889ceb72009-02-03 19:21:40 +00003385 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003386
Douglas Gregor34074322009-01-14 22:20:51 +00003387 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003388 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3389 LookupParsedName(R, S, &SS);
3390 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003391 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003392
John McCall9f3059a2009-10-09 21:13:30 +00003393 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003394 NamedDecl *Named = R.getFoundDecl();
3395 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3396 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003397 // C++ [namespace.udir]p1:
3398 // A using-directive specifies that the names in the nominated
3399 // namespace can be used in the scope in which the
3400 // using-directive appears after the using-directive. During
3401 // unqualified name lookup (3.4.1), the names appear as if they
3402 // were declared in the nearest enclosing namespace which
3403 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003404 // namespace. [Note: in this context, "contains" means "contains
3405 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003406
3407 // Find enclosing context containing both using-directive and
3408 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003409 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003410 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3411 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3412 CommonAncestor = CommonAncestor->getParent();
3413
Sebastian Redla6602e92009-11-23 15:34:23 +00003414 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003415 SS.getRange(),
3416 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003417 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003418 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003419 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003420 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003421 }
3422
Douglas Gregor889ceb72009-02-03 19:21:40 +00003423 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003424 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003425 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003426}
3427
3428void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3429 // If scope has associated entity, then using directive is at namespace
3430 // or translation unit scope. We add UsingDirectiveDecls, into
3431 // it's lookup structure.
3432 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003433 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003434 else
3435 // Otherwise it is block-sope. using-directives will affect lookup
3436 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003437 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003438}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003439
Douglas Gregorfec52632009-06-20 00:51:54 +00003440
3441Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003442 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003443 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003444 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003445 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003446 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003447 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003448 bool IsTypeName,
3449 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003450 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003451
Douglas Gregor220f4272009-11-04 16:30:06 +00003452 switch (Name.getKind()) {
3453 case UnqualifiedId::IK_Identifier:
3454 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003455 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003456 case UnqualifiedId::IK_ConversionFunctionId:
3457 break;
3458
3459 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003460 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003461 // C++0x inherited constructors.
3462 if (getLangOptions().CPlusPlus0x) break;
3463
Douglas Gregor220f4272009-11-04 16:30:06 +00003464 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3465 << SS.getRange();
3466 return DeclPtrTy();
3467
3468 case UnqualifiedId::IK_DestructorName:
3469 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3470 << SS.getRange();
3471 return DeclPtrTy();
3472
3473 case UnqualifiedId::IK_TemplateId:
3474 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3475 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3476 return DeclPtrTy();
3477 }
3478
3479 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003480 if (!TargetName)
3481 return DeclPtrTy();
3482
John McCalla0097262009-12-11 02:10:03 +00003483 // Warn about using declarations.
3484 // TODO: store that the declaration was written without 'using' and
3485 // talk about access decls instead of using decls in the
3486 // diagnostics.
3487 if (!HasUsingKeyword) {
3488 UsingLoc = Name.getSourceRange().getBegin();
3489
3490 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003491 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003492 }
3493
John McCall3f746822009-11-17 05:59:44 +00003494 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003495 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003496 TargetName, AttrList,
3497 /* IsInstantiation */ false,
3498 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003499 if (UD)
3500 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003501
Anders Carlsson696a3f12009-08-28 05:40:36 +00003502 return DeclPtrTy::make(UD);
3503}
3504
John McCall84d87672009-12-10 09:41:52 +00003505/// Determines whether to create a using shadow decl for a particular
3506/// decl, given the set of decls existing prior to this using lookup.
3507bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3508 const LookupResult &Previous) {
3509 // Diagnose finding a decl which is not from a base class of the
3510 // current class. We do this now because there are cases where this
3511 // function will silently decide not to build a shadow decl, which
3512 // will pre-empt further diagnostics.
3513 //
3514 // We don't need to do this in C++0x because we do the check once on
3515 // the qualifier.
3516 //
3517 // FIXME: diagnose the following if we care enough:
3518 // struct A { int foo; };
3519 // struct B : A { using A::foo; };
3520 // template <class T> struct C : A {};
3521 // template <class T> struct D : C<T> { using B::foo; } // <---
3522 // This is invalid (during instantiation) in C++03 because B::foo
3523 // resolves to the using decl in B, which is not a base class of D<T>.
3524 // We can't diagnose it immediately because C<T> is an unknown
3525 // specialization. The UsingShadowDecl in D<T> then points directly
3526 // to A::foo, which will look well-formed when we instantiate.
3527 // The right solution is to not collapse the shadow-decl chain.
3528 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3529 DeclContext *OrigDC = Orig->getDeclContext();
3530
3531 // Handle enums and anonymous structs.
3532 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3533 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3534 while (OrigRec->isAnonymousStructOrUnion())
3535 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3536
3537 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3538 if (OrigDC == CurContext) {
3539 Diag(Using->getLocation(),
3540 diag::err_using_decl_nested_name_specifier_is_current_class)
3541 << Using->getNestedNameRange();
3542 Diag(Orig->getLocation(), diag::note_using_decl_target);
3543 return true;
3544 }
3545
3546 Diag(Using->getNestedNameRange().getBegin(),
3547 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3548 << Using->getTargetNestedNameDecl()
3549 << cast<CXXRecordDecl>(CurContext)
3550 << Using->getNestedNameRange();
3551 Diag(Orig->getLocation(), diag::note_using_decl_target);
3552 return true;
3553 }
3554 }
3555
3556 if (Previous.empty()) return false;
3557
3558 NamedDecl *Target = Orig;
3559 if (isa<UsingShadowDecl>(Target))
3560 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3561
John McCalla17e83e2009-12-11 02:33:26 +00003562 // If the target happens to be one of the previous declarations, we
3563 // don't have a conflict.
3564 //
3565 // FIXME: but we might be increasing its access, in which case we
3566 // should redeclare it.
3567 NamedDecl *NonTag = 0, *Tag = 0;
3568 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3569 I != E; ++I) {
3570 NamedDecl *D = (*I)->getUnderlyingDecl();
3571 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3572 return false;
3573
3574 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3575 }
3576
John McCall84d87672009-12-10 09:41:52 +00003577 if (Target->isFunctionOrFunctionTemplate()) {
3578 FunctionDecl *FD;
3579 if (isa<FunctionTemplateDecl>(Target))
3580 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3581 else
3582 FD = cast<FunctionDecl>(Target);
3583
3584 NamedDecl *OldDecl = 0;
3585 switch (CheckOverload(FD, Previous, OldDecl)) {
3586 case Ovl_Overload:
3587 return false;
3588
3589 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003590 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003591 break;
3592
3593 // We found a decl with the exact signature.
3594 case Ovl_Match:
3595 if (isa<UsingShadowDecl>(OldDecl)) {
3596 // Silently ignore the possible conflict.
3597 return false;
3598 }
3599
3600 // If we're in a record, we want to hide the target, so we
3601 // return true (without a diagnostic) to tell the caller not to
3602 // build a shadow decl.
3603 if (CurContext->isRecord())
3604 return true;
3605
3606 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003607 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003608 break;
3609 }
3610
3611 Diag(Target->getLocation(), diag::note_using_decl_target);
3612 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3613 return true;
3614 }
3615
3616 // Target is not a function.
3617
John McCall84d87672009-12-10 09:41:52 +00003618 if (isa<TagDecl>(Target)) {
3619 // No conflict between a tag and a non-tag.
3620 if (!Tag) return false;
3621
John McCalle29c5cd2009-12-10 19:51:03 +00003622 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003623 Diag(Target->getLocation(), diag::note_using_decl_target);
3624 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3625 return true;
3626 }
3627
3628 // No conflict between a tag and a non-tag.
3629 if (!NonTag) return false;
3630
John McCalle29c5cd2009-12-10 19:51:03 +00003631 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003632 Diag(Target->getLocation(), diag::note_using_decl_target);
3633 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3634 return true;
3635}
3636
John McCall3f746822009-11-17 05:59:44 +00003637/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003638UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003639 UsingDecl *UD,
3640 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003641
3642 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003643 NamedDecl *Target = Orig;
3644 if (isa<UsingShadowDecl>(Target)) {
3645 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3646 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003647 }
3648
3649 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003650 = UsingShadowDecl::Create(Context, CurContext,
3651 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003652 UD->addShadowDecl(Shadow);
3653
3654 if (S)
John McCall3969e302009-12-08 07:46:18 +00003655 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003656 else
John McCall3969e302009-12-08 07:46:18 +00003657 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003658 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003659
John McCallda4458e2010-03-31 01:36:47 +00003660 // Register it as a conversion if appropriate.
3661 if (Shadow->getDeclName().getNameKind()
3662 == DeclarationName::CXXConversionFunctionName)
3663 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3664
John McCall3969e302009-12-08 07:46:18 +00003665 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3666 Shadow->setInvalidDecl();
3667
John McCall84d87672009-12-10 09:41:52 +00003668 return Shadow;
3669}
John McCall3969e302009-12-08 07:46:18 +00003670
John McCall84d87672009-12-10 09:41:52 +00003671/// Hides a using shadow declaration. This is required by the current
3672/// using-decl implementation when a resolvable using declaration in a
3673/// class is followed by a declaration which would hide or override
3674/// one or more of the using decl's targets; for example:
3675///
3676/// struct Base { void foo(int); };
3677/// struct Derived : Base {
3678/// using Base::foo;
3679/// void foo(int);
3680/// };
3681///
3682/// The governing language is C++03 [namespace.udecl]p12:
3683///
3684/// When a using-declaration brings names from a base class into a
3685/// derived class scope, member functions in the derived class
3686/// override and/or hide member functions with the same name and
3687/// parameter types in a base class (rather than conflicting).
3688///
3689/// There are two ways to implement this:
3690/// (1) optimistically create shadow decls when they're not hidden
3691/// by existing declarations, or
3692/// (2) don't create any shadow decls (or at least don't make them
3693/// visible) until we've fully parsed/instantiated the class.
3694/// The problem with (1) is that we might have to retroactively remove
3695/// a shadow decl, which requires several O(n) operations because the
3696/// decl structures are (very reasonably) not designed for removal.
3697/// (2) avoids this but is very fiddly and phase-dependent.
3698void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003699 if (Shadow->getDeclName().getNameKind() ==
3700 DeclarationName::CXXConversionFunctionName)
3701 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3702
John McCall84d87672009-12-10 09:41:52 +00003703 // Remove it from the DeclContext...
3704 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003705
John McCall84d87672009-12-10 09:41:52 +00003706 // ...and the scope, if applicable...
3707 if (S) {
3708 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3709 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003710 }
3711
John McCall84d87672009-12-10 09:41:52 +00003712 // ...and the using decl.
3713 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3714
3715 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003716 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003717}
3718
John McCalle61f2ba2009-11-18 02:36:19 +00003719/// Builds a using declaration.
3720///
3721/// \param IsInstantiation - Whether this call arises from an
3722/// instantiation of an unresolved using declaration. We treat
3723/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003724NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3725 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003726 CXXScopeSpec &SS,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003727 SourceLocation IdentLoc,
3728 DeclarationName Name,
3729 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003730 bool IsInstantiation,
3731 bool IsTypeName,
3732 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003733 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3734 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003735
Anders Carlssonf038fc22009-08-28 05:49:21 +00003736 // FIXME: We ignore attributes for now.
3737 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003738
Anders Carlsson59140b32009-08-28 03:16:11 +00003739 if (SS.isEmpty()) {
3740 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003741 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003742 }
Mike Stump11289f42009-09-09 15:08:12 +00003743
John McCall84d87672009-12-10 09:41:52 +00003744 // Do the redeclaration lookup in the current scope.
3745 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3746 ForRedeclaration);
3747 Previous.setHideTags(false);
3748 if (S) {
3749 LookupName(Previous, S);
3750
3751 // It is really dumb that we have to do this.
3752 LookupResult::Filter F = Previous.makeFilter();
3753 while (F.hasNext()) {
3754 NamedDecl *D = F.next();
3755 if (!isDeclInScope(D, CurContext, S))
3756 F.erase();
3757 }
3758 F.done();
3759 } else {
3760 assert(IsInstantiation && "no scope in non-instantiation");
3761 assert(CurContext->isRecord() && "scope not record in instantiation");
3762 LookupQualifiedName(Previous, CurContext);
3763 }
3764
Mike Stump11289f42009-09-09 15:08:12 +00003765 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003766 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3767
John McCall84d87672009-12-10 09:41:52 +00003768 // Check for invalid redeclarations.
3769 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3770 return 0;
3771
3772 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003773 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3774 return 0;
3775
John McCall84c16cf2009-11-12 03:15:40 +00003776 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003777 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003778 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003779 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003780 // FIXME: not all declaration name kinds are legal here
3781 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3782 UsingLoc, TypenameLoc,
3783 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003784 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003785 } else {
3786 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3787 UsingLoc, SS.getRange(), NNS,
3788 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003789 }
John McCallb96ec562009-12-04 22:46:56 +00003790 } else {
3791 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3792 SS.getRange(), UsingLoc, NNS, Name,
3793 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003794 }
John McCallb96ec562009-12-04 22:46:56 +00003795 D->setAccess(AS);
3796 CurContext->addDecl(D);
3797
3798 if (!LookupContext) return D;
3799 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003800
John McCall0b66eb32010-05-01 00:40:08 +00003801 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003802 UD->setInvalidDecl();
3803 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003804 }
3805
John McCall3969e302009-12-08 07:46:18 +00003806 // Look up the target name.
3807
John McCall27b18f82009-11-17 02:14:36 +00003808 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003809
John McCall3969e302009-12-08 07:46:18 +00003810 // Unlike most lookups, we don't always want to hide tag
3811 // declarations: tag names are visible through the using declaration
3812 // even if hidden by ordinary names, *except* in a dependent context
3813 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003814 if (!IsInstantiation)
3815 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003816
John McCall27b18f82009-11-17 02:14:36 +00003817 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003818
John McCall9f3059a2009-10-09 21:13:30 +00003819 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003820 Diag(IdentLoc, diag::err_no_member)
3821 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003822 UD->setInvalidDecl();
3823 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003824 }
3825
John McCallb96ec562009-12-04 22:46:56 +00003826 if (R.isAmbiguous()) {
3827 UD->setInvalidDecl();
3828 return UD;
3829 }
Mike Stump11289f42009-09-09 15:08:12 +00003830
John McCalle61f2ba2009-11-18 02:36:19 +00003831 if (IsTypeName) {
3832 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003833 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003834 Diag(IdentLoc, diag::err_using_typename_non_type);
3835 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3836 Diag((*I)->getUnderlyingDecl()->getLocation(),
3837 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003838 UD->setInvalidDecl();
3839 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003840 }
3841 } else {
3842 // If we asked for a non-typename and we got a type, error out,
3843 // but only if this is an instantiation of an unresolved using
3844 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003845 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003846 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3847 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003848 UD->setInvalidDecl();
3849 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003850 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003851 }
3852
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003853 // C++0x N2914 [namespace.udecl]p6:
3854 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003855 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003856 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3857 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003858 UD->setInvalidDecl();
3859 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
John McCall84d87672009-12-10 09:41:52 +00003862 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3863 if (!CheckUsingShadowDecl(UD, *I, Previous))
3864 BuildUsingShadowDecl(S, UD, *I);
3865 }
John McCall3f746822009-11-17 05:59:44 +00003866
3867 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003868}
3869
John McCall84d87672009-12-10 09:41:52 +00003870/// Checks that the given using declaration is not an invalid
3871/// redeclaration. Note that this is checking only for the using decl
3872/// itself, not for any ill-formedness among the UsingShadowDecls.
3873bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3874 bool isTypeName,
3875 const CXXScopeSpec &SS,
3876 SourceLocation NameLoc,
3877 const LookupResult &Prev) {
3878 // C++03 [namespace.udecl]p8:
3879 // C++0x [namespace.udecl]p10:
3880 // A using-declaration is a declaration and can therefore be used
3881 // repeatedly where (and only where) multiple declarations are
3882 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003883 //
3884 // That's in non-member contexts.
3885 if (!CurContext->getLookupContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003886 return false;
3887
3888 NestedNameSpecifier *Qual
3889 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3890
3891 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3892 NamedDecl *D = *I;
3893
3894 bool DTypename;
3895 NestedNameSpecifier *DQual;
3896 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3897 DTypename = UD->isTypeName();
3898 DQual = UD->getTargetNestedNameDecl();
3899 } else if (UnresolvedUsingValueDecl *UD
3900 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3901 DTypename = false;
3902 DQual = UD->getTargetNestedNameSpecifier();
3903 } else if (UnresolvedUsingTypenameDecl *UD
3904 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3905 DTypename = true;
3906 DQual = UD->getTargetNestedNameSpecifier();
3907 } else continue;
3908
3909 // using decls differ if one says 'typename' and the other doesn't.
3910 // FIXME: non-dependent using decls?
3911 if (isTypeName != DTypename) continue;
3912
3913 // using decls differ if they name different scopes (but note that
3914 // template instantiation can cause this check to trigger when it
3915 // didn't before instantiation).
3916 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3917 Context.getCanonicalNestedNameSpecifier(DQual))
3918 continue;
3919
3920 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003921 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003922 return true;
3923 }
3924
3925 return false;
3926}
3927
John McCall3969e302009-12-08 07:46:18 +00003928
John McCallb96ec562009-12-04 22:46:56 +00003929/// Checks that the given nested-name qualifier used in a using decl
3930/// in the current context is appropriately related to the current
3931/// scope. If an error is found, diagnoses it and returns true.
3932bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3933 const CXXScopeSpec &SS,
3934 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003935 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003936
John McCall3969e302009-12-08 07:46:18 +00003937 if (!CurContext->isRecord()) {
3938 // C++03 [namespace.udecl]p3:
3939 // C++0x [namespace.udecl]p8:
3940 // A using-declaration for a class member shall be a member-declaration.
3941
3942 // If we weren't able to compute a valid scope, it must be a
3943 // dependent class scope.
3944 if (!NamedContext || NamedContext->isRecord()) {
3945 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3946 << SS.getRange();
3947 return true;
3948 }
3949
3950 // Otherwise, everything is known to be fine.
3951 return false;
3952 }
3953
3954 // The current scope is a record.
3955
3956 // If the named context is dependent, we can't decide much.
3957 if (!NamedContext) {
3958 // FIXME: in C++0x, we can diagnose if we can prove that the
3959 // nested-name-specifier does not refer to a base class, which is
3960 // still possible in some cases.
3961
3962 // Otherwise we have to conservatively report that things might be
3963 // okay.
3964 return false;
3965 }
3966
3967 if (!NamedContext->isRecord()) {
3968 // Ideally this would point at the last name in the specifier,
3969 // but we don't have that level of source info.
3970 Diag(SS.getRange().getBegin(),
3971 diag::err_using_decl_nested_name_specifier_is_not_class)
3972 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3973 return true;
3974 }
3975
3976 if (getLangOptions().CPlusPlus0x) {
3977 // C++0x [namespace.udecl]p3:
3978 // In a using-declaration used as a member-declaration, the
3979 // nested-name-specifier shall name a base class of the class
3980 // being defined.
3981
3982 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3983 cast<CXXRecordDecl>(NamedContext))) {
3984 if (CurContext == NamedContext) {
3985 Diag(NameLoc,
3986 diag::err_using_decl_nested_name_specifier_is_current_class)
3987 << SS.getRange();
3988 return true;
3989 }
3990
3991 Diag(SS.getRange().getBegin(),
3992 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3993 << (NestedNameSpecifier*) SS.getScopeRep()
3994 << cast<CXXRecordDecl>(CurContext)
3995 << SS.getRange();
3996 return true;
3997 }
3998
3999 return false;
4000 }
4001
4002 // C++03 [namespace.udecl]p4:
4003 // A using-declaration used as a member-declaration shall refer
4004 // to a member of a base class of the class being defined [etc.].
4005
4006 // Salient point: SS doesn't have to name a base class as long as
4007 // lookup only finds members from base classes. Therefore we can
4008 // diagnose here only if we can prove that that can't happen,
4009 // i.e. if the class hierarchies provably don't intersect.
4010
4011 // TODO: it would be nice if "definitely valid" results were cached
4012 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4013 // need to be repeated.
4014
4015 struct UserData {
4016 llvm::DenseSet<const CXXRecordDecl*> Bases;
4017
4018 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4019 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4020 Data->Bases.insert(Base);
4021 return true;
4022 }
4023
4024 bool hasDependentBases(const CXXRecordDecl *Class) {
4025 return !Class->forallBases(collect, this);
4026 }
4027
4028 /// Returns true if the base is dependent or is one of the
4029 /// accumulated base classes.
4030 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4031 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4032 return !Data->Bases.count(Base);
4033 }
4034
4035 bool mightShareBases(const CXXRecordDecl *Class) {
4036 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4037 }
4038 };
4039
4040 UserData Data;
4041
4042 // Returns false if we find a dependent base.
4043 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4044 return false;
4045
4046 // Returns false if the class has a dependent base or if it or one
4047 // of its bases is present in the base set of the current context.
4048 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4049 return false;
4050
4051 Diag(SS.getRange().getBegin(),
4052 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4053 << (NestedNameSpecifier*) SS.getScopeRep()
4054 << cast<CXXRecordDecl>(CurContext)
4055 << SS.getRange();
4056
4057 return true;
John McCallb96ec562009-12-04 22:46:56 +00004058}
4059
Mike Stump11289f42009-09-09 15:08:12 +00004060Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004061 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004062 SourceLocation AliasLoc,
4063 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004064 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004065 SourceLocation IdentLoc,
4066 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004067
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004068 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004069 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4070 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004071
Anders Carlssondca83c42009-03-28 06:23:46 +00004072 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004073 NamedDecl *PrevDecl
4074 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4075 ForRedeclaration);
4076 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4077 PrevDecl = 0;
4078
4079 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004080 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004081 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004082 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004083 // FIXME: At some point, we'll want to create the (redundant)
4084 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004085 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004086 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004087 return DeclPtrTy();
4088 }
Mike Stump11289f42009-09-09 15:08:12 +00004089
Anders Carlssondca83c42009-03-28 06:23:46 +00004090 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4091 diag::err_redefinition_different_kind;
4092 Diag(AliasLoc, DiagID) << Alias;
4093 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004094 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004095 }
4096
John McCall27b18f82009-11-17 02:14:36 +00004097 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004098 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004099
John McCall9f3059a2009-10-09 21:13:30 +00004100 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00004101 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004102 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00004103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004105 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004106 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4107 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004108 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004109 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004110
John McCalld8d0d432010-02-16 06:53:13 +00004111 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004112 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004113}
4114
Douglas Gregora57478e2010-05-01 15:04:51 +00004115namespace {
4116 /// \brief Scoped object used to handle the state changes required in Sema
4117 /// to implicitly define the body of a C++ member function;
4118 class ImplicitlyDefinedFunctionScope {
4119 Sema &S;
4120 DeclContext *PreviousContext;
4121
4122 public:
4123 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4124 : S(S), PreviousContext(S.CurContext)
4125 {
4126 S.CurContext = Method;
4127 S.PushFunctionScope();
4128 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4129 }
4130
4131 ~ImplicitlyDefinedFunctionScope() {
4132 S.PopExpressionEvaluationContext();
4133 S.PopFunctionOrBlockScope();
4134 S.CurContext = PreviousContext;
4135 }
4136 };
4137}
4138
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004139void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4140 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004141 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4142 !Constructor->isUsed()) &&
4143 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004144
Anders Carlsson423f5d82010-04-23 16:04:08 +00004145 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004146 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004147
Douglas Gregora57478e2010-05-01 15:04:51 +00004148 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004149 ErrorTrap Trap(*this);
4150 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4151 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004152 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004153 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004154 Constructor->setInvalidDecl();
4155 } else {
4156 Constructor->setUsed();
Douglas Gregor54818f02010-05-12 16:39:35 +00004157 MaybeMarkVirtualMembersReferenced(CurrentLocation, Constructor);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004158 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004159}
4160
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004161void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004162 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004163 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4164 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004165 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004166 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004167
Douglas Gregor54818f02010-05-12 16:39:35 +00004168 if (Destructor->isInvalidDecl())
4169 return;
4170
Douglas Gregora57478e2010-05-01 15:04:51 +00004171 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004172
Douglas Gregor54818f02010-05-12 16:39:35 +00004173 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004174 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4175 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004176
Douglas Gregor54818f02010-05-12 16:39:35 +00004177 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004178 Diag(CurrentLocation, diag::note_member_synthesized_at)
4179 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4180
4181 Destructor->setInvalidDecl();
4182 return;
4183 }
4184
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004185 Destructor->setUsed();
Douglas Gregor54818f02010-05-12 16:39:35 +00004186 MaybeMarkVirtualMembersReferenced(CurrentLocation, Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004187}
4188
Douglas Gregorb139cd52010-05-01 20:49:11 +00004189/// \brief Builds a statement that copies the given entity from \p From to
4190/// \c To.
4191///
4192/// This routine is used to copy the members of a class with an
4193/// implicitly-declared copy assignment operator. When the entities being
4194/// copied are arrays, this routine builds for loops to copy them.
4195///
4196/// \param S The Sema object used for type-checking.
4197///
4198/// \param Loc The location where the implicit copy is being generated.
4199///
4200/// \param T The type of the expressions being copied. Both expressions must
4201/// have this type.
4202///
4203/// \param To The expression we are copying to.
4204///
4205/// \param From The expression we are copying from.
4206///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004207/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4208/// Otherwise, it's a non-static member subobject.
4209///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004210/// \param Depth Internal parameter recording the depth of the recursion.
4211///
4212/// \returns A statement or a loop that copies the expressions.
4213static Sema::OwningStmtResult
4214BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4215 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004216 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004217 typedef Sema::OwningStmtResult OwningStmtResult;
4218 typedef Sema::OwningExprResult OwningExprResult;
4219
4220 // C++0x [class.copy]p30:
4221 // Each subobject is assigned in the manner appropriate to its type:
4222 //
4223 // - if the subobject is of class type, the copy assignment operator
4224 // for the class is used (as if by explicit qualification; that is,
4225 // ignoring any possible virtual overriding functions in more derived
4226 // classes);
4227 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4228 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4229
4230 // Look for operator=.
4231 DeclarationName Name
4232 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4233 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4234 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4235
4236 // Filter out any result that isn't a copy-assignment operator.
4237 LookupResult::Filter F = OpLookup.makeFilter();
4238 while (F.hasNext()) {
4239 NamedDecl *D = F.next();
4240 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4241 if (Method->isCopyAssignmentOperator())
4242 continue;
4243
4244 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004245 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004246 F.done();
4247
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004248 // Suppress the protected check (C++ [class.protected]) for each of the
4249 // assignment operators we found. This strange dance is required when
4250 // we're assigning via a base classes's copy-assignment operator. To
4251 // ensure that we're getting the right base class subobject (without
4252 // ambiguities), we need to cast "this" to that subobject type; to
4253 // ensure that we don't go through the virtual call mechanism, we need
4254 // to qualify the operator= name with the base class (see below). However,
4255 // this means that if the base class has a protected copy assignment
4256 // operator, the protected member access check will fail. So, we
4257 // rewrite "protected" access to "public" access in this case, since we
4258 // know by construction that we're calling from a derived class.
4259 if (CopyingBaseSubobject) {
4260 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4261 L != LEnd; ++L) {
4262 if (L.getAccess() == AS_protected)
4263 L.setAccess(AS_public);
4264 }
4265 }
4266
Douglas Gregorb139cd52010-05-01 20:49:11 +00004267 // Create the nested-name-specifier that will be used to qualify the
4268 // reference to operator=; this is required to suppress the virtual
4269 // call mechanism.
4270 CXXScopeSpec SS;
4271 SS.setRange(Loc);
4272 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4273 T.getTypePtr()));
4274
4275 // Create the reference to operator=.
4276 OwningExprResult OpEqualRef
4277 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4278 /*FirstQualifierInScope=*/0, OpLookup,
4279 /*TemplateArgs=*/0,
4280 /*SuppressQualifierCheck=*/true);
4281 if (OpEqualRef.isInvalid())
4282 return S.StmtError();
4283
4284 // Build the call to the assignment operator.
4285 Expr *FromE = From.takeAs<Expr>();
4286 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4287 OpEqualRef.takeAs<Expr>(),
4288 Loc, &FromE, 1, 0, Loc);
4289 if (Call.isInvalid())
4290 return S.StmtError();
4291
4292 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004293 }
John McCallab8c2732010-03-16 06:11:48 +00004294
Douglas Gregorb139cd52010-05-01 20:49:11 +00004295 // - if the subobject is of scalar type, the built-in assignment
4296 // operator is used.
4297 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4298 if (!ArrayTy) {
4299 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4300 BinaryOperator::Assign,
4301 To.takeAs<Expr>(),
4302 From.takeAs<Expr>());
4303 if (Assignment.isInvalid())
4304 return S.StmtError();
4305
4306 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004307 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004308
4309 // - if the subobject is an array, each element is assigned, in the
4310 // manner appropriate to the element type;
4311
4312 // Construct a loop over the array bounds, e.g.,
4313 //
4314 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4315 //
4316 // that will copy each of the array elements.
4317 QualType SizeType = S.Context.getSizeType();
4318
4319 // Create the iteration variable.
4320 IdentifierInfo *IterationVarName = 0;
4321 {
4322 llvm::SmallString<8> Str;
4323 llvm::raw_svector_ostream OS(Str);
4324 OS << "__i" << Depth;
4325 IterationVarName = &S.Context.Idents.get(OS.str());
4326 }
4327 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4328 IterationVarName, SizeType,
4329 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4330 VarDecl::None, VarDecl::None);
4331
4332 // Initialize the iteration variable to zero.
4333 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4334 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4335
4336 // Create a reference to the iteration variable; we'll use this several
4337 // times throughout.
4338 Expr *IterationVarRef
4339 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4340 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4341
4342 // Create the DeclStmt that holds the iteration variable.
4343 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4344
4345 // Create the comparison against the array bound.
4346 llvm::APInt Upper = ArrayTy->getSize();
4347 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4348 OwningExprResult Comparison
4349 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4350 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4351 BinaryOperator::NE, S.Context.BoolTy, Loc));
4352
4353 // Create the pre-increment of the iteration variable.
4354 OwningExprResult Increment
4355 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4356 UnaryOperator::PreInc,
4357 SizeType, Loc));
4358
4359 // Subscript the "from" and "to" expressions with the iteration variable.
4360 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4361 S.Owned(IterationVarRef->Retain()),
4362 Loc);
4363 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4364 S.Owned(IterationVarRef->Retain()),
4365 Loc);
4366 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4367 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4368
4369 // Build the copy for an individual element of the array.
4370 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4371 ArrayTy->getElementType(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004372 move(To), move(From),
4373 CopyingBaseSubobject, Depth+1);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004374 if (Copy.isInvalid()) {
4375 InitStmt->Destroy(S.Context);
4376 return S.StmtError();
4377 }
4378
4379 // Construct the loop that copies all elements of this array.
4380 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4381 S.MakeFullExpr(Comparison),
4382 Sema::DeclPtrTy(),
4383 S.MakeFullExpr(Increment),
4384 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004385}
4386
Douglas Gregorb139cd52010-05-01 20:49:11 +00004387void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4388 CXXMethodDecl *CopyAssignOperator) {
4389 assert((CopyAssignOperator->isImplicit() &&
4390 CopyAssignOperator->isOverloadedOperator() &&
4391 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4392 !CopyAssignOperator->isUsed()) &&
4393 "DefineImplicitCopyAssignment called for wrong function");
4394
4395 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4396
4397 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4398 CopyAssignOperator->setInvalidDecl();
4399 return;
4400 }
4401
4402 CopyAssignOperator->setUsed();
4403
4404 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004405 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004406
4407 // C++0x [class.copy]p30:
4408 // The implicitly-defined or explicitly-defaulted copy assignment operator
4409 // for a non-union class X performs memberwise copy assignment of its
4410 // subobjects. The direct base classes of X are assigned first, in the
4411 // order of their declaration in the base-specifier-list, and then the
4412 // immediate non-static data members of X are assigned, in the order in
4413 // which they were declared in the class definition.
4414
4415 // The statements that form the synthesized function body.
4416 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4417
4418 // The parameter for the "other" object, which we are copying from.
4419 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4420 Qualifiers OtherQuals = Other->getType().getQualifiers();
4421 QualType OtherRefType = Other->getType();
4422 if (const LValueReferenceType *OtherRef
4423 = OtherRefType->getAs<LValueReferenceType>()) {
4424 OtherRefType = OtherRef->getPointeeType();
4425 OtherQuals = OtherRefType.getQualifiers();
4426 }
4427
4428 // Our location for everything implicitly-generated.
4429 SourceLocation Loc = CopyAssignOperator->getLocation();
4430
4431 // Construct a reference to the "other" object. We'll be using this
4432 // throughout the generated ASTs.
4433 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4434 assert(OtherRef && "Reference to parameter cannot fail!");
4435
4436 // Construct the "this" pointer. We'll be using this throughout the generated
4437 // ASTs.
4438 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4439 assert(This && "Reference to this cannot fail!");
4440
4441 // Assign base classes.
4442 bool Invalid = false;
4443 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4444 E = ClassDecl->bases_end(); Base != E; ++Base) {
4445 // Form the assignment:
4446 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4447 QualType BaseType = Base->getType().getUnqualifiedType();
4448 CXXRecordDecl *BaseClassDecl = 0;
4449 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4450 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4451 else {
4452 Invalid = true;
4453 continue;
4454 }
4455
4456 // Construct the "from" expression, which is an implicit cast to the
4457 // appropriately-qualified base type.
4458 Expr *From = OtherRef->Retain();
4459 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4460 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4461 CXXBaseSpecifierArray(Base));
4462
4463 // Dereference "this".
4464 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4465 Owned(This->Retain()));
4466
4467 // Implicitly cast "this" to the appropriately-qualified base type.
4468 Expr *ToE = To.takeAs<Expr>();
4469 ImpCastExprToType(ToE,
4470 Context.getCVRQualifiedType(BaseType,
4471 CopyAssignOperator->getTypeQualifiers()),
4472 CastExpr::CK_UncheckedDerivedToBase,
4473 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4474 To = Owned(ToE);
4475
4476 // Build the copy.
4477 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004478 move(To), Owned(From),
4479 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004480 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004481 Diag(CurrentLocation, diag::note_member_synthesized_at)
4482 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4483 CopyAssignOperator->setInvalidDecl();
4484 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004485 }
4486
4487 // Success! Record the copy.
4488 Statements.push_back(Copy.takeAs<Expr>());
4489 }
4490
4491 // \brief Reference to the __builtin_memcpy function.
4492 Expr *BuiltinMemCpyRef = 0;
4493
4494 // Assign non-static members.
4495 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4496 FieldEnd = ClassDecl->field_end();
4497 Field != FieldEnd; ++Field) {
4498 // Check for members of reference type; we can't copy those.
4499 if (Field->getType()->isReferenceType()) {
4500 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4501 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4502 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004503 Diag(CurrentLocation, diag::note_member_synthesized_at)
4504 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004505 Invalid = true;
4506 continue;
4507 }
4508
4509 // Check for members of const-qualified, non-class type.
4510 QualType BaseType = Context.getBaseElementType(Field->getType());
4511 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4512 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4513 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4514 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004515 Diag(CurrentLocation, diag::note_member_synthesized_at)
4516 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004517 Invalid = true;
4518 continue;
4519 }
4520
4521 QualType FieldType = Field->getType().getNonReferenceType();
4522
4523 // Build references to the field in the object we're copying from and to.
4524 CXXScopeSpec SS; // Intentionally empty
4525 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4526 LookupMemberName);
4527 MemberLookup.addDecl(*Field);
4528 MemberLookup.resolveKind();
4529 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4530 OtherRefType,
4531 Loc, /*IsArrow=*/false,
4532 SS, 0, MemberLookup, 0);
4533 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4534 This->getType(),
4535 Loc, /*IsArrow=*/true,
4536 SS, 0, MemberLookup, 0);
4537 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4538 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4539
4540 // If the field should be copied with __builtin_memcpy rather than via
4541 // explicit assignments, do so. This optimization only applies for arrays
4542 // of scalars and arrays of class type with trivial copy-assignment
4543 // operators.
4544 if (FieldType->isArrayType() &&
4545 (!BaseType->isRecordType() ||
4546 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4547 ->hasTrivialCopyAssignment())) {
4548 // Compute the size of the memory buffer to be copied.
4549 QualType SizeType = Context.getSizeType();
4550 llvm::APInt Size(Context.getTypeSize(SizeType),
4551 Context.getTypeSizeInChars(BaseType).getQuantity());
4552 for (const ConstantArrayType *Array
4553 = Context.getAsConstantArrayType(FieldType);
4554 Array;
4555 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4556 llvm::APInt ArraySize = Array->getSize();
4557 ArraySize.zextOrTrunc(Size.getBitWidth());
4558 Size *= ArraySize;
4559 }
4560
4561 // Take the address of the field references for "from" and "to".
4562 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4563 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4564
4565 // Create a reference to the __builtin_memcpy builtin function.
4566 if (!BuiltinMemCpyRef) {
4567 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4568 LookupOrdinaryName);
4569 LookupName(R, TUScope, true);
4570
4571 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4572 if (!BuiltinMemCpy) {
4573 // Something went horribly wrong earlier, and we will have complained
4574 // about it.
4575 Invalid = true;
4576 continue;
4577 }
4578
4579 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4580 BuiltinMemCpy->getType(),
4581 Loc, 0).takeAs<Expr>();
4582 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4583 }
4584
4585 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4586 CallArgs.push_back(To.takeAs<Expr>());
4587 CallArgs.push_back(From.takeAs<Expr>());
4588 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4589 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4590 Commas.push_back(Loc);
4591 Commas.push_back(Loc);
4592 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4593 Owned(BuiltinMemCpyRef->Retain()),
4594 Loc, move_arg(CallArgs),
4595 Commas.data(), Loc);
4596 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4597 Statements.push_back(Call.takeAs<Expr>());
4598 continue;
4599 }
4600
4601 // Build the copy of this field.
4602 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004603 move(To), move(From),
4604 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004605 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004606 Diag(CurrentLocation, diag::note_member_synthesized_at)
4607 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4608 CopyAssignOperator->setInvalidDecl();
4609 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004610 }
4611
4612 // Success! Record the copy.
4613 Statements.push_back(Copy.takeAs<Stmt>());
4614 }
4615
4616 if (!Invalid) {
4617 // Add a "return *this;"
4618 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4619 Owned(This->Retain()));
4620
4621 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4622 if (Return.isInvalid())
4623 Invalid = true;
4624 else {
4625 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00004626
4627 if (Trap.hasErrorOccurred()) {
4628 Diag(CurrentLocation, diag::note_member_synthesized_at)
4629 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4630 Invalid = true;
4631 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004632 }
4633 }
4634
4635 if (Invalid) {
4636 CopyAssignOperator->setInvalidDecl();
4637 return;
4638 }
4639
4640 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4641 /*isStmtExpr=*/false);
4642 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4643 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00004644
4645 MaybeMarkVirtualMembersReferenced(CurrentLocation, CopyAssignOperator);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004646}
4647
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004648void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4649 CXXConstructorDecl *CopyConstructor,
4650 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00004651 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00004652 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004653 !CopyConstructor->isUsed()) &&
4654 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004655
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00004656 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004657 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004658
Douglas Gregora57478e2010-05-01 15:04:51 +00004659 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004660 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004661
Douglas Gregor54818f02010-05-12 16:39:35 +00004662 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
4663 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00004664 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00004665 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00004666 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00004667 } else {
4668 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
4669 CopyConstructor->getLocation(),
4670 MultiStmtArg(*this, 0, 0),
4671 /*isStmtExpr=*/false)
4672 .takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00004673 MaybeMarkVirtualMembersReferenced(CurrentLocation, CopyConstructor);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00004674 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00004675
4676 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004677}
4678
Anders Carlsson6eb55572009-08-25 05:12:04 +00004679Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004680Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00004681 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004682 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004683 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004684 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00004685 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00004686
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004687 // C++0x [class.copy]p34:
4688 // When certain criteria are met, an implementation is allowed to
4689 // omit the copy/move construction of a class object, even if the
4690 // copy/move constructor and/or destructor for the object have
4691 // side effects. [...]
4692 // - when a temporary class object that has not been bound to a
4693 // reference (12.2) would be copied/moved to a class object
4694 // with the same cv-unqualified type, the copy/move operation
4695 // can be omitted by constructing the temporary object
4696 // directly into the target of the omitted copy/move
4697 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4698 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4699 Elidable = SubExpr->isTemporaryObject() &&
4700 Context.hasSameUnqualifiedType(SubExpr->getType(),
4701 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00004702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703
4704 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004705 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004706 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00004707}
4708
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004709/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4710/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004711Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004712Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4713 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004714 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004715 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004716 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004717 unsigned NumExprs = ExprArgs.size();
4718 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004719
Douglas Gregor27381f32009-11-23 12:27:39 +00004720 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004721 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004722 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004723 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004724}
4725
Mike Stump11289f42009-09-09 15:08:12 +00004726bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004727 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004728 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004729 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004730 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004731 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004732 if (TempResult.isInvalid())
4733 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004734
Anders Carlsson6eb55572009-08-25 05:12:04 +00004735 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004736 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004737 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004738 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004739
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004740 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004741}
4742
John McCall03c48482010-02-02 09:10:11 +00004743void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4744 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004745 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4746 !ClassDecl->hasTrivialDestructor()) {
John McCall6781b052010-02-02 08:45:54 +00004747 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4748 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00004749 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00004750 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00004751 << VD->getDeclName()
4752 << VD->getType());
John McCall6781b052010-02-02 08:45:54 +00004753 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004754}
4755
Mike Stump11289f42009-09-09 15:08:12 +00004756/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004757/// ActOnDeclarator, when a C++ direct initializer is present.
4758/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004759void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4760 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004761 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004762 SourceLocation *CommaLocs,
4763 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004764 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004765 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004766
4767 // If there is no declaration, there was an error parsing it. Just ignore
4768 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004769 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004770 return;
Mike Stump11289f42009-09-09 15:08:12 +00004771
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004772 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4773 if (!VDecl) {
4774 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4775 RealDecl->setInvalidDecl();
4776 return;
4777 }
4778
Douglas Gregor402250f2009-08-26 21:14:46 +00004779 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004780 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004781 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4782 //
4783 // Clients that want to distinguish between the two forms, can check for
4784 // direct initializer using VarDecl::hasCXXDirectInitializer().
4785 // A major benefit is that clients that don't particularly care about which
4786 // exactly form was it (like the CodeGen) can handle both cases without
4787 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004788
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004789 // C++ 8.5p11:
4790 // The form of initialization (using parentheses or '=') is generally
4791 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004792 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004793 QualType DeclInitType = VDecl->getType();
4794 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004795 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004796
Douglas Gregor50dc2192010-02-11 22:55:30 +00004797 if (!VDecl->getType()->isDependentType() &&
4798 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004799 diag::err_typecheck_decl_incomplete_type)) {
4800 VDecl->setInvalidDecl();
4801 return;
4802 }
4803
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004804 // The variable can not have an abstract class type.
4805 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4806 diag::err_abstract_type_in_decl,
4807 AbstractVariableType))
4808 VDecl->setInvalidDecl();
4809
Sebastian Redl5ca79842010-02-01 20:16:42 +00004810 const VarDecl *Def;
4811 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004812 Diag(VDecl->getLocation(), diag::err_redefinition)
4813 << VDecl->getDeclName();
4814 Diag(Def->getLocation(), diag::note_previous_definition);
4815 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004816 return;
4817 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004818
4819 // If either the declaration has a dependent type or if any of the
4820 // expressions is type-dependent, we represent the initialization
4821 // via a ParenListExpr for later use during template instantiation.
4822 if (VDecl->getType()->isDependentType() ||
4823 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4824 // Let clients know that initialization was done with a direct initializer.
4825 VDecl->setCXXDirectInitializer(true);
4826
4827 // Store the initialization expressions as a ParenListExpr.
4828 unsigned NumExprs = Exprs.size();
4829 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4830 (Expr **)Exprs.release(),
4831 NumExprs, RParenLoc));
4832 return;
4833 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004834
4835 // Capture the variable that is being initialized and the style of
4836 // initialization.
4837 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4838
4839 // FIXME: Poor source location information.
4840 InitializationKind Kind
4841 = InitializationKind::CreateDirect(VDecl->getLocation(),
4842 LParenLoc, RParenLoc);
4843
4844 InitializationSequence InitSeq(*this, Entity, Kind,
4845 (Expr**)Exprs.get(), Exprs.size());
4846 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4847 if (Result.isInvalid()) {
4848 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004849 return;
4850 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004851
4852 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004853 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004854 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004855
John McCall03c48482010-02-02 09:10:11 +00004856 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4857 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004858}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004859
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004860/// \brief Given a constructor and the set of arguments provided for the
4861/// constructor, convert the arguments and add any required default arguments
4862/// to form a proper call to this constructor.
4863///
4864/// \returns true if an error occurred, false otherwise.
4865bool
4866Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4867 MultiExprArg ArgsPtr,
4868 SourceLocation Loc,
4869 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4870 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4871 unsigned NumArgs = ArgsPtr.size();
4872 Expr **Args = (Expr **)ArgsPtr.get();
4873
4874 const FunctionProtoType *Proto
4875 = Constructor->getType()->getAs<FunctionProtoType>();
4876 assert(Proto && "Constructor without a prototype?");
4877 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004878
4879 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004880 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004881 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004882 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004883 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004884
4885 VariadicCallType CallType =
4886 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4887 llvm::SmallVector<Expr *, 8> AllArgs;
4888 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4889 Proto, 0, Args, NumArgs, AllArgs,
4890 CallType);
4891 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4892 ConvertedArgs.push_back(AllArgs[i]);
4893 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004894}
4895
Anders Carlssone363c8e2009-12-12 00:32:00 +00004896static inline bool
4897CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4898 const FunctionDecl *FnDecl) {
4899 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4900 if (isa<NamespaceDecl>(DC)) {
4901 return SemaRef.Diag(FnDecl->getLocation(),
4902 diag::err_operator_new_delete_declared_in_namespace)
4903 << FnDecl->getDeclName();
4904 }
4905
4906 if (isa<TranslationUnitDecl>(DC) &&
4907 FnDecl->getStorageClass() == FunctionDecl::Static) {
4908 return SemaRef.Diag(FnDecl->getLocation(),
4909 diag::err_operator_new_delete_declared_static)
4910 << FnDecl->getDeclName();
4911 }
4912
Anders Carlsson60659a82009-12-12 02:43:16 +00004913 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004914}
4915
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004916static inline bool
4917CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4918 CanQualType ExpectedResultType,
4919 CanQualType ExpectedFirstParamType,
4920 unsigned DependentParamTypeDiag,
4921 unsigned InvalidParamTypeDiag) {
4922 QualType ResultType =
4923 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4924
4925 // Check that the result type is not dependent.
4926 if (ResultType->isDependentType())
4927 return SemaRef.Diag(FnDecl->getLocation(),
4928 diag::err_operator_new_delete_dependent_result_type)
4929 << FnDecl->getDeclName() << ExpectedResultType;
4930
4931 // Check that the result type is what we expect.
4932 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4933 return SemaRef.Diag(FnDecl->getLocation(),
4934 diag::err_operator_new_delete_invalid_result_type)
4935 << FnDecl->getDeclName() << ExpectedResultType;
4936
4937 // A function template must have at least 2 parameters.
4938 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4939 return SemaRef.Diag(FnDecl->getLocation(),
4940 diag::err_operator_new_delete_template_too_few_parameters)
4941 << FnDecl->getDeclName();
4942
4943 // The function decl must have at least 1 parameter.
4944 if (FnDecl->getNumParams() == 0)
4945 return SemaRef.Diag(FnDecl->getLocation(),
4946 diag::err_operator_new_delete_too_few_parameters)
4947 << FnDecl->getDeclName();
4948
4949 // Check the the first parameter type is not dependent.
4950 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4951 if (FirstParamType->isDependentType())
4952 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4953 << FnDecl->getDeclName() << ExpectedFirstParamType;
4954
4955 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004956 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004957 ExpectedFirstParamType)
4958 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4959 << FnDecl->getDeclName() << ExpectedFirstParamType;
4960
4961 return false;
4962}
4963
Anders Carlsson12308f42009-12-11 23:23:22 +00004964static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004965CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004966 // C++ [basic.stc.dynamic.allocation]p1:
4967 // A program is ill-formed if an allocation function is declared in a
4968 // namespace scope other than global scope or declared static in global
4969 // scope.
4970 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4971 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004972
4973 CanQualType SizeTy =
4974 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4975
4976 // C++ [basic.stc.dynamic.allocation]p1:
4977 // The return type shall be void*. The first parameter shall have type
4978 // std::size_t.
4979 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4980 SizeTy,
4981 diag::err_operator_new_dependent_param_type,
4982 diag::err_operator_new_param_type))
4983 return true;
4984
4985 // C++ [basic.stc.dynamic.allocation]p1:
4986 // The first parameter shall not have an associated default argument.
4987 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004988 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004989 diag::err_operator_new_default_arg)
4990 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4991
4992 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004993}
4994
4995static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004996CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4997 // C++ [basic.stc.dynamic.deallocation]p1:
4998 // A program is ill-formed if deallocation functions are declared in a
4999 // namespace scope other than global scope or declared static in global
5000 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005001 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5002 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005003
5004 // C++ [basic.stc.dynamic.deallocation]p2:
5005 // Each deallocation function shall return void and its first parameter
5006 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005007 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5008 SemaRef.Context.VoidPtrTy,
5009 diag::err_operator_delete_dependent_param_type,
5010 diag::err_operator_delete_param_type))
5011 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005012
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00005013 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5014 if (FirstParamType->isDependentType())
5015 return SemaRef.Diag(FnDecl->getLocation(),
5016 diag::err_operator_delete_dependent_param_type)
5017 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5018
5019 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
5020 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00005021 return SemaRef.Diag(FnDecl->getLocation(),
5022 diag::err_operator_delete_param_type)
5023 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00005024
5025 return false;
5026}
5027
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005028/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5029/// of this overloaded operator is well-formed. If so, returns false;
5030/// otherwise, emits appropriate diagnostics and returns true.
5031bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005032 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005033 "Expected an overloaded operator declaration");
5034
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005035 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5036
Mike Stump11289f42009-09-09 15:08:12 +00005037 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005038 // The allocation and deallocation functions, operator new,
5039 // operator new[], operator delete and operator delete[], are
5040 // described completely in 3.7.3. The attributes and restrictions
5041 // found in the rest of this subclause do not apply to them unless
5042 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005043 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005044 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005045
Anders Carlsson22f443f2009-12-12 00:26:23 +00005046 if (Op == OO_New || Op == OO_Array_New)
5047 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005048
5049 // C++ [over.oper]p6:
5050 // An operator function shall either be a non-static member
5051 // function or be a non-member function and have at least one
5052 // parameter whose type is a class, a reference to a class, an
5053 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005054 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5055 if (MethodDecl->isStatic())
5056 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005057 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005058 } else {
5059 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005060 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5061 ParamEnd = FnDecl->param_end();
5062 Param != ParamEnd; ++Param) {
5063 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005064 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5065 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005066 ClassOrEnumParam = true;
5067 break;
5068 }
5069 }
5070
Douglas Gregord69246b2008-11-17 16:14:12 +00005071 if (!ClassOrEnumParam)
5072 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005073 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005074 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005075 }
5076
5077 // C++ [over.oper]p8:
5078 // An operator function cannot have default arguments (8.3.6),
5079 // except where explicitly stated below.
5080 //
Mike Stump11289f42009-09-09 15:08:12 +00005081 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005082 // (C++ [over.call]p1).
5083 if (Op != OO_Call) {
5084 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5085 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005086 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005087 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005088 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005089 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005090 }
5091 }
5092
Douglas Gregor6cf08062008-11-10 13:38:07 +00005093 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5094 { false, false, false }
5095#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5096 , { Unary, Binary, MemberOnly }
5097#include "clang/Basic/OperatorKinds.def"
5098 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005099
Douglas Gregor6cf08062008-11-10 13:38:07 +00005100 bool CanBeUnaryOperator = OperatorUses[Op][0];
5101 bool CanBeBinaryOperator = OperatorUses[Op][1];
5102 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005103
5104 // C++ [over.oper]p8:
5105 // [...] Operator functions cannot have more or fewer parameters
5106 // than the number required for the corresponding operator, as
5107 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005108 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005109 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005110 if (Op != OO_Call &&
5111 ((NumParams == 1 && !CanBeUnaryOperator) ||
5112 (NumParams == 2 && !CanBeBinaryOperator) ||
5113 (NumParams < 1) || (NumParams > 2))) {
5114 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005115 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005116 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005117 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005118 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005119 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005120 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005121 assert(CanBeBinaryOperator &&
5122 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005123 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005124 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005125
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005126 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005127 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005128 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005129
Douglas Gregord69246b2008-11-17 16:14:12 +00005130 // Overloaded operators other than operator() cannot be variadic.
5131 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005132 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005133 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005134 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005135 }
5136
5137 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005138 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5139 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005140 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005141 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005142 }
5143
5144 // C++ [over.inc]p1:
5145 // The user-defined function called operator++ implements the
5146 // prefix and postfix ++ operator. If this function is a member
5147 // function with no parameters, or a non-member function with one
5148 // parameter of class or enumeration type, it defines the prefix
5149 // increment operator ++ for objects of that type. If the function
5150 // is a member function with one parameter (which shall be of type
5151 // int) or a non-member function with two parameters (the second
5152 // of which shall be of type int), it defines the postfix
5153 // increment operator ++ for objects of that type.
5154 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5155 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5156 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005157 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005158 ParamIsInt = BT->getKind() == BuiltinType::Int;
5159
Chris Lattner2b786902008-11-21 07:50:02 +00005160 if (!ParamIsInt)
5161 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005162 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005163 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005164 }
5165
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005166 // Notify the class if it got an assignment operator.
5167 if (Op == OO_Equal) {
5168 // Would have returned earlier otherwise.
5169 assert(isa<CXXMethodDecl>(FnDecl) &&
5170 "Overloaded = not member, but not filtered.");
5171 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5172 Method->getParent()->addedAssignmentOperator(Context, Method);
5173 }
5174
Douglas Gregord69246b2008-11-17 16:14:12 +00005175 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005176}
Chris Lattner3b024a32008-12-17 07:09:26 +00005177
Alexis Huntc88db062010-01-13 09:01:02 +00005178/// CheckLiteralOperatorDeclaration - Check whether the declaration
5179/// of this literal operator function is well-formed. If so, returns
5180/// false; otherwise, emits appropriate diagnostics and returns true.
5181bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5182 DeclContext *DC = FnDecl->getDeclContext();
5183 Decl::Kind Kind = DC->getDeclKind();
5184 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5185 Kind != Decl::LinkageSpec) {
5186 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5187 << FnDecl->getDeclName();
5188 return true;
5189 }
5190
5191 bool Valid = false;
5192
Alexis Hunt7dd26172010-04-07 23:11:06 +00005193 // template <char...> type operator "" name() is the only valid template
5194 // signature, and the only valid signature with no parameters.
5195 if (FnDecl->param_size() == 0) {
5196 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5197 // Must have only one template parameter
5198 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5199 if (Params->size() == 1) {
5200 NonTypeTemplateParmDecl *PmDecl =
5201 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005202
Alexis Hunt7dd26172010-04-07 23:11:06 +00005203 // The template parameter must be a char parameter pack.
5204 // FIXME: This test will always fail because non-type parameter packs
5205 // have not been implemented.
5206 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5207 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5208 Valid = true;
5209 }
5210 }
5211 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005212 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005213 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5214
Alexis Huntc88db062010-01-13 09:01:02 +00005215 QualType T = (*Param)->getType();
5216
Alexis Hunt079a6f72010-04-07 22:57:35 +00005217 // unsigned long long int, long double, and any character type are allowed
5218 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005219 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5220 Context.hasSameType(T, Context.LongDoubleTy) ||
5221 Context.hasSameType(T, Context.CharTy) ||
5222 Context.hasSameType(T, Context.WCharTy) ||
5223 Context.hasSameType(T, Context.Char16Ty) ||
5224 Context.hasSameType(T, Context.Char32Ty)) {
5225 if (++Param == FnDecl->param_end())
5226 Valid = true;
5227 goto FinishedParams;
5228 }
5229
Alexis Hunt079a6f72010-04-07 22:57:35 +00005230 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005231 const PointerType *PT = T->getAs<PointerType>();
5232 if (!PT)
5233 goto FinishedParams;
5234 T = PT->getPointeeType();
5235 if (!T.isConstQualified())
5236 goto FinishedParams;
5237 T = T.getUnqualifiedType();
5238
5239 // Move on to the second parameter;
5240 ++Param;
5241
5242 // If there is no second parameter, the first must be a const char *
5243 if (Param == FnDecl->param_end()) {
5244 if (Context.hasSameType(T, Context.CharTy))
5245 Valid = true;
5246 goto FinishedParams;
5247 }
5248
5249 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5250 // are allowed as the first parameter to a two-parameter function
5251 if (!(Context.hasSameType(T, Context.CharTy) ||
5252 Context.hasSameType(T, Context.WCharTy) ||
5253 Context.hasSameType(T, Context.Char16Ty) ||
5254 Context.hasSameType(T, Context.Char32Ty)))
5255 goto FinishedParams;
5256
5257 // The second and final parameter must be an std::size_t
5258 T = (*Param)->getType().getUnqualifiedType();
5259 if (Context.hasSameType(T, Context.getSizeType()) &&
5260 ++Param == FnDecl->param_end())
5261 Valid = true;
5262 }
5263
5264 // FIXME: This diagnostic is absolutely terrible.
5265FinishedParams:
5266 if (!Valid) {
5267 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5268 << FnDecl->getDeclName();
5269 return true;
5270 }
5271
5272 return false;
5273}
5274
Douglas Gregor07665a62009-01-05 19:45:36 +00005275/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5276/// linkage specification, including the language and (if present)
5277/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5278/// the location of the language string literal, which is provided
5279/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5280/// the '{' brace. Otherwise, this linkage specification does not
5281/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005282Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5283 SourceLocation ExternLoc,
5284 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005285 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005286 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005287 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005288 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005289 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005290 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005291 Language = LinkageSpecDecl::lang_cxx;
5292 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005293 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005294 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005295 }
Mike Stump11289f42009-09-09 15:08:12 +00005296
Chris Lattner438e5012008-12-17 07:13:27 +00005297 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005298
Douglas Gregor07665a62009-01-05 19:45:36 +00005299 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005300 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005301 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005302 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005303 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005304 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005305}
5306
Douglas Gregor07665a62009-01-05 19:45:36 +00005307/// ActOnFinishLinkageSpecification - Completely the definition of
5308/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5309/// valid, it's the position of the closing '}' brace in a linkage
5310/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005311Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5312 DeclPtrTy LinkageSpec,
5313 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005314 if (LinkageSpec)
5315 PopDeclContext();
5316 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005317}
5318
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005319/// \brief Perform semantic analysis for the variable declaration that
5320/// occurs within a C++ catch clause, returning the newly-created
5321/// variable.
5322VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005323 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005324 IdentifierInfo *Name,
5325 SourceLocation Loc,
5326 SourceRange Range) {
5327 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005328
5329 // Arrays and functions decay.
5330 if (ExDeclType->isArrayType())
5331 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5332 else if (ExDeclType->isFunctionType())
5333 ExDeclType = Context.getPointerType(ExDeclType);
5334
5335 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5336 // The exception-declaration shall not denote a pointer or reference to an
5337 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005338 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005339 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005340 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005341 Invalid = true;
5342 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005343
Douglas Gregor104ee002010-03-08 01:47:36 +00005344 // GCC allows catching pointers and references to incomplete types
5345 // as an extension; so do we, but we warn by default.
5346
Sebastian Redl54c04d42008-12-22 19:15:10 +00005347 QualType BaseType = ExDeclType;
5348 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005349 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005350 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005351 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005352 BaseType = Ptr->getPointeeType();
5353 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005354 DK = diag::ext_catch_incomplete_ptr;
5355 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005356 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005357 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005358 BaseType = Ref->getPointeeType();
5359 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005360 DK = diag::ext_catch_incomplete_ref;
5361 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005362 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005363 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005364 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5365 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005366 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005367
Mike Stump11289f42009-09-09 15:08:12 +00005368 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005369 RequireNonAbstractType(Loc, ExDeclType,
5370 diag::err_abstract_type_in_decl,
5371 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005372 Invalid = true;
5373
Mike Stump11289f42009-09-09 15:08:12 +00005374 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005375 Name, ExDeclType, TInfo, VarDecl::None,
5376 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00005377 ExDecl->setExceptionVariable(true);
5378
Douglas Gregor6de584c2010-03-05 23:38:39 +00005379 if (!Invalid) {
5380 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5381 // C++ [except.handle]p16:
5382 // The object declared in an exception-declaration or, if the
5383 // exception-declaration does not specify a name, a temporary (12.2) is
5384 // copy-initialized (8.5) from the exception object. [...]
5385 // The object is destroyed when the handler exits, after the destruction
5386 // of any automatic objects initialized within the handler.
5387 //
5388 // We just pretend to initialize the object with itself, then make sure
5389 // it can be destroyed later.
5390 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5391 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5392 Loc, ExDeclType, 0);
5393 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5394 SourceLocation());
5395 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5396 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5397 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5398 if (Result.isInvalid())
5399 Invalid = true;
5400 else
5401 FinalizeVarWithDestructor(ExDecl, RecordTy);
5402 }
5403 }
5404
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005405 if (Invalid)
5406 ExDecl->setInvalidDecl();
5407
5408 return ExDecl;
5409}
5410
5411/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5412/// handler.
5413Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005414 TypeSourceInfo *TInfo = 0;
5415 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005416
5417 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005418 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005419 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00005420 LookupOrdinaryName,
5421 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005422 // The scope should be freshly made just for us. There is just no way
5423 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005424 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005425 if (PrevDecl->isTemplateParameter()) {
5426 // Maybe we will complain about the shadowed template parameter.
5427 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005428 }
5429 }
5430
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005431 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005432 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5433 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005434 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005435 }
5436
John McCallbcd03502009-12-07 02:54:59 +00005437 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005438 D.getIdentifier(),
5439 D.getIdentifierLoc(),
5440 D.getDeclSpec().getSourceRange());
5441
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005442 if (Invalid)
5443 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005444
Sebastian Redl54c04d42008-12-22 19:15:10 +00005445 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005446 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005447 PushOnScopeChains(ExDecl, S);
5448 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005449 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005450
Douglas Gregor758a8692009-06-17 21:51:59 +00005451 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005452 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005453}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005454
Mike Stump11289f42009-09-09 15:08:12 +00005455Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005456 ExprArg assertexpr,
5457 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005458 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005459 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005460 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5461
Anders Carlsson54b26982009-03-14 00:33:21 +00005462 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5463 llvm::APSInt Value(32);
5464 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5465 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5466 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005467 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005468 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005469
Anders Carlsson54b26982009-03-14 00:33:21 +00005470 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005471 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005472 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005473 }
5474 }
Mike Stump11289f42009-09-09 15:08:12 +00005475
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005476 assertexpr.release();
5477 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005478 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005479 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005480
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005481 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005482 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005483}
Sebastian Redlf769df52009-03-24 22:27:57 +00005484
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005485/// \brief Perform semantic analysis of the given friend type declaration.
5486///
5487/// \returns A friend declaration that.
5488FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5489 TypeSourceInfo *TSInfo) {
5490 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5491
5492 QualType T = TSInfo->getType();
5493 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5494
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005495 if (!getLangOptions().CPlusPlus0x) {
5496 // C++03 [class.friend]p2:
5497 // An elaborated-type-specifier shall be used in a friend declaration
5498 // for a class.*
5499 //
5500 // * The class-key of the elaborated-type-specifier is required.
5501 if (!ActiveTemplateInstantiations.empty()) {
5502 // Do not complain about the form of friend template types during
5503 // template instantiation; we will already have complained when the
5504 // template was declared.
5505 } else if (!T->isElaboratedTypeSpecifier()) {
5506 // If we evaluated the type to a record type, suggest putting
5507 // a tag in front.
5508 if (const RecordType *RT = T->getAs<RecordType>()) {
5509 RecordDecl *RD = RT->getDecl();
5510
5511 std::string InsertionText = std::string(" ") + RD->getKindName();
5512
5513 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5514 << (unsigned) RD->getTagKind()
5515 << T
5516 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5517 InsertionText);
5518 } else {
5519 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5520 << T
5521 << SourceRange(FriendLoc, TypeRange.getEnd());
5522 }
5523 } else if (T->getAs<EnumType>()) {
5524 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005525 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005526 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005527 }
5528 }
5529
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005530 // C++0x [class.friend]p3:
5531 // If the type specifier in a friend declaration designates a (possibly
5532 // cv-qualified) class type, that class is declared as a friend; otherwise,
5533 // the friend declaration is ignored.
5534
5535 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5536 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005537
5538 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5539}
5540
John McCall11083da2009-09-16 22:47:08 +00005541/// Handle a friend type declaration. This works in tandem with
5542/// ActOnTag.
5543///
5544/// Notes on friend class templates:
5545///
5546/// We generally treat friend class declarations as if they were
5547/// declaring a class. So, for example, the elaborated type specifier
5548/// in a friend declaration is required to obey the restrictions of a
5549/// class-head (i.e. no typedefs in the scope chain), template
5550/// parameters are required to match up with simple template-ids, &c.
5551/// However, unlike when declaring a template specialization, it's
5552/// okay to refer to a template specialization without an empty
5553/// template parameter declaration, e.g.
5554/// friend class A<T>::B<unsigned>;
5555/// We permit this as a special case; if there are any template
5556/// parameters present at all, require proper matching, i.e.
5557/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005558Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005559 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005560 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005561
5562 assert(DS.isFriendSpecified());
5563 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5564
John McCall11083da2009-09-16 22:47:08 +00005565 // Try to convert the decl specifier to a type. This works for
5566 // friend templates because ActOnTag never produces a ClassTemplateDecl
5567 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005568 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall15ad0962010-03-25 18:04:51 +00005569 TypeSourceInfo *TSI;
5570 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005571 if (TheDeclarator.isInvalidType())
5572 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005573
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005574 if (!TSI)
5575 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5576
John McCall11083da2009-09-16 22:47:08 +00005577 // This is definitely an error in C++98. It's probably meant to
5578 // be forbidden in C++0x, too, but the specification is just
5579 // poorly written.
5580 //
5581 // The problem is with declarations like the following:
5582 // template <T> friend A<T>::foo;
5583 // where deciding whether a class C is a friend or not now hinges
5584 // on whether there exists an instantiation of A that causes
5585 // 'foo' to equal C. There are restrictions on class-heads
5586 // (which we declare (by fiat) elaborated friend declarations to
5587 // be) that makes this tractable.
5588 //
5589 // FIXME: handle "template <> friend class A<T>;", which
5590 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00005591 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00005592 Diag(Loc, diag::err_tagless_friend_type_template)
5593 << DS.getSourceRange();
5594 return DeclPtrTy();
5595 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005596
John McCallaa74a0c2009-08-28 07:59:38 +00005597 // C++98 [class.friend]p1: A friend of a class is a function
5598 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005599 // This is fixed in DR77, which just barely didn't make the C++03
5600 // deadline. It's also a very silly restriction that seriously
5601 // affects inner classes and which nobody else seems to implement;
5602 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00005603 //
5604 // But note that we could warn about it: it's always useless to
5605 // friend one of your own members (it's not, however, worthless to
5606 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00005607
John McCall11083da2009-09-16 22:47:08 +00005608 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005609 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00005610 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005611 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00005612 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00005613 TSI,
John McCall11083da2009-09-16 22:47:08 +00005614 DS.getFriendSpecLoc());
5615 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005616 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5617
5618 if (!D)
5619 return DeclPtrTy();
5620
John McCall11083da2009-09-16 22:47:08 +00005621 D->setAccess(AS_public);
5622 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005623
John McCall11083da2009-09-16 22:47:08 +00005624 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005625}
5626
John McCall2f212b32009-09-11 21:02:39 +00005627Sema::DeclPtrTy
5628Sema::ActOnFriendFunctionDecl(Scope *S,
5629 Declarator &D,
5630 bool IsDefinition,
5631 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005632 const DeclSpec &DS = D.getDeclSpec();
5633
5634 assert(DS.isFriendSpecified());
5635 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5636
5637 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005638 TypeSourceInfo *TInfo = 0;
5639 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005640
5641 // C++ [class.friend]p1
5642 // A friend of a class is a function or class....
5643 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005644 // It *doesn't* see through dependent types, which is correct
5645 // according to [temp.arg.type]p3:
5646 // If a declaration acquires a function type through a
5647 // type dependent on a template-parameter and this causes
5648 // a declaration that does not use the syntactic form of a
5649 // function declarator to have a function type, the program
5650 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005651 if (!T->isFunctionType()) {
5652 Diag(Loc, diag::err_unexpected_friend);
5653
5654 // It might be worthwhile to try to recover by creating an
5655 // appropriate declaration.
5656 return DeclPtrTy();
5657 }
5658
5659 // C++ [namespace.memdef]p3
5660 // - If a friend declaration in a non-local class first declares a
5661 // class or function, the friend class or function is a member
5662 // of the innermost enclosing namespace.
5663 // - The name of the friend is not found by simple name lookup
5664 // until a matching declaration is provided in that namespace
5665 // scope (either before or after the class declaration granting
5666 // friendship).
5667 // - If a friend function is called, its name may be found by the
5668 // name lookup that considers functions from namespaces and
5669 // classes associated with the types of the function arguments.
5670 // - When looking for a prior declaration of a class or a function
5671 // declared as a friend, scopes outside the innermost enclosing
5672 // namespace scope are not considered.
5673
John McCallaa74a0c2009-08-28 07:59:38 +00005674 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5675 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005676 assert(Name);
5677
John McCall07e91c02009-08-06 02:15:43 +00005678 // The context we found the declaration in, or in which we should
5679 // create the declaration.
5680 DeclContext *DC;
5681
5682 // FIXME: handle local classes
5683
5684 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005685 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5686 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005687 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5688 DC = computeDeclContext(ScopeQual);
5689
5690 // FIXME: handle dependent contexts
5691 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00005692 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005693
John McCall1f82f242009-11-18 22:49:29 +00005694 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005695
5696 // If searching in that context implicitly found a declaration in
5697 // a different context, treat it like it wasn't found at all.
5698 // TODO: better diagnostics for this case. Suggesting the right
5699 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005700 // FIXME: getRepresentativeDecl() is not right here at all
5701 if (Previous.empty() ||
5702 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005703 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005704 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5705 return DeclPtrTy();
5706 }
5707
5708 // C++ [class.friend]p1: A friend of a class is a function or
5709 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005710 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005711 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5712
John McCall07e91c02009-08-06 02:15:43 +00005713 // Otherwise walk out to the nearest namespace scope looking for matches.
5714 } else {
5715 // TODO: handle local class contexts.
5716
5717 DC = CurContext;
5718 while (true) {
5719 // Skip class contexts. If someone can cite chapter and verse
5720 // for this behavior, that would be nice --- it's what GCC and
5721 // EDG do, and it seems like a reasonable intent, but the spec
5722 // really only says that checks for unqualified existing
5723 // declarations should stop at the nearest enclosing namespace,
5724 // not that they should only consider the nearest enclosing
5725 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005726 while (DC->isRecord())
5727 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005728
John McCall1f82f242009-11-18 22:49:29 +00005729 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005730
5731 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005732 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005733 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005734
John McCall07e91c02009-08-06 02:15:43 +00005735 if (DC->isFileContext()) break;
5736 DC = DC->getParent();
5737 }
5738
5739 // C++ [class.friend]p1: A friend of a class is a function or
5740 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005741 // C++0x changes this for both friend types and functions.
5742 // Most C++ 98 compilers do seem to give an error here, so
5743 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005744 if (!Previous.empty() && DC->Equals(CurContext)
5745 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005746 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5747 }
5748
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005749 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005750 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005751 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5752 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5753 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005754 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005755 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5756 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005757 return DeclPtrTy();
5758 }
John McCall07e91c02009-08-06 02:15:43 +00005759 }
5760
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005761 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005762 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005763 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005764 IsDefinition,
5765 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005766 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005767
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005768 assert(ND->getDeclContext() == DC);
5769 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005770
John McCall759e32b2009-08-31 22:39:49 +00005771 // Add the function declaration to the appropriate lookup tables,
5772 // adjusting the redeclarations list as necessary. We don't
5773 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005774 //
John McCall759e32b2009-08-31 22:39:49 +00005775 // Also update the scope-based lookup if the target context's
5776 // lookup context is in lexical scope.
5777 if (!CurContext->isDependentContext()) {
5778 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005779 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005780 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005781 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005782 }
John McCallaa74a0c2009-08-28 07:59:38 +00005783
5784 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005785 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005786 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005787 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005788 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005789
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005790 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005791}
5792
Chris Lattner83f095c2009-03-28 19:18:32 +00005793void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005794 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005795
Chris Lattner83f095c2009-03-28 19:18:32 +00005796 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005797 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5798 if (!Fn) {
5799 Diag(DelLoc, diag::err_deleted_non_function);
5800 return;
5801 }
5802 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5803 Diag(DelLoc, diag::err_deleted_decl_not_first);
5804 Diag(Prev->getLocation(), diag::note_previous_declaration);
5805 // If the declaration wasn't the first, we delete the function anyway for
5806 // recovery.
5807 }
5808 Fn->setDeleted();
5809}
Sebastian Redl4c018662009-04-27 21:33:24 +00005810
5811static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5812 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5813 ++CI) {
5814 Stmt *SubStmt = *CI;
5815 if (!SubStmt)
5816 continue;
5817 if (isa<ReturnStmt>(SubStmt))
5818 Self.Diag(SubStmt->getSourceRange().getBegin(),
5819 diag::err_return_in_constructor_handler);
5820 if (!isa<Expr>(SubStmt))
5821 SearchForReturnInStmt(Self, SubStmt);
5822 }
5823}
5824
5825void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5826 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5827 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5828 SearchForReturnInStmt(*this, Handler);
5829 }
5830}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005831
Mike Stump11289f42009-09-09 15:08:12 +00005832bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005833 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005834 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5835 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005836
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005837 if (Context.hasSameType(NewTy, OldTy) ||
5838 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005840
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005841 // Check if the return types are covariant
5842 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005843
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005844 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005845 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5846 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005847 NewClassTy = NewPT->getPointeeType();
5848 OldClassTy = OldPT->getPointeeType();
5849 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005850 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5851 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5852 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5853 NewClassTy = NewRT->getPointeeType();
5854 OldClassTy = OldRT->getPointeeType();
5855 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005856 }
5857 }
Mike Stump11289f42009-09-09 15:08:12 +00005858
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005859 // The return types aren't either both pointers or references to a class type.
5860 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005861 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005862 diag::err_different_return_type_for_overriding_virtual_function)
5863 << New->getDeclName() << NewTy << OldTy;
5864 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005865
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005866 return true;
5867 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005868
Anders Carlssone60365b2009-12-31 18:34:24 +00005869 // C++ [class.virtual]p6:
5870 // If the return type of D::f differs from the return type of B::f, the
5871 // class type in the return type of D::f shall be complete at the point of
5872 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005873 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5874 if (!RT->isBeingDefined() &&
5875 RequireCompleteType(New->getLocation(), NewClassTy,
5876 PDiag(diag::err_covariant_return_incomplete)
5877 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005878 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005879 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005880
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005881 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005882 // Check if the new class derives from the old class.
5883 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5884 Diag(New->getLocation(),
5885 diag::err_covariant_return_not_derived)
5886 << New->getDeclName() << NewTy << OldTy;
5887 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5888 return true;
5889 }
Mike Stump11289f42009-09-09 15:08:12 +00005890
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005891 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00005892 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00005893 diag::err_covariant_return_inaccessible_base,
5894 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5895 // FIXME: Should this point to the return type?
5896 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005897 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5898 return true;
5899 }
5900 }
Mike Stump11289f42009-09-09 15:08:12 +00005901
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005902 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005903 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005904 Diag(New->getLocation(),
5905 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005906 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005907 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5908 return true;
5909 };
Mike Stump11289f42009-09-09 15:08:12 +00005910
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005911
5912 // The new class type must have the same or less qualifiers as the old type.
5913 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5914 Diag(New->getLocation(),
5915 diag::err_covariant_return_type_class_type_more_qualified)
5916 << New->getDeclName() << NewTy << OldTy;
5917 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5918 return true;
5919 };
Mike Stump11289f42009-09-09 15:08:12 +00005920
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005921 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005922}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005923
Alexis Hunt96d5c762009-11-21 08:43:09 +00005924bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5925 const CXXMethodDecl *Old)
5926{
5927 if (Old->hasAttr<FinalAttr>()) {
5928 Diag(New->getLocation(), diag::err_final_function_overridden)
5929 << New->getDeclName();
5930 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5931 return true;
5932 }
5933
5934 return false;
5935}
5936
Douglas Gregor21920e372009-12-01 17:24:26 +00005937/// \brief Mark the given method pure.
5938///
5939/// \param Method the method to be marked pure.
5940///
5941/// \param InitRange the source range that covers the "0" initializer.
5942bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5943 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5944 Method->setPure();
5945
5946 // A class is abstract if at least one function is pure virtual.
5947 Method->getParent()->setAbstract(true);
5948 return false;
5949 }
5950
5951 if (!Method->isInvalidDecl())
5952 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5953 << Method->getDeclName() << InitRange;
5954 return true;
5955}
5956
John McCall1f4ee7b2009-12-19 09:28:58 +00005957/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5958/// an initializer for the out-of-line declaration 'Dcl'. The scope
5959/// is a fresh scope pushed for just this purpose.
5960///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005961/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5962/// static data member of class X, names should be looked up in the scope of
5963/// class X.
5964void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005965 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005966 Decl *D = Dcl.getAs<Decl>();
5967 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005968
John McCall1f4ee7b2009-12-19 09:28:58 +00005969 // We should only get called for declarations with scope specifiers, like:
5970 // int foo::bar;
5971 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005972 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005973}
5974
5975/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005976/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005977void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005978 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005979 Decl *D = Dcl.getAs<Decl>();
5980 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005981
John McCall1f4ee7b2009-12-19 09:28:58 +00005982 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005983 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005984}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005985
5986/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5987/// C++ if/switch/while/for statement.
5988/// e.g: "if (int x = f()) {...}"
5989Action::DeclResult
5990Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5991 // C++ 6.4p2:
5992 // The declarator shall not specify a function or an array.
5993 // The type-specifier-seq shall not contain typedef and shall not declare a
5994 // new class or enumeration.
5995 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5996 "Parser allowed 'typedef' as storage class of condition decl.");
5997
John McCallbcd03502009-12-07 02:54:59 +00005998 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005999 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00006000 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006001
6002 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6003 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6004 // would be created and CXXConditionDeclExpr wants a VarDecl.
6005 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6006 << D.getSourceRange();
6007 return DeclResult();
6008 } else if (OwnedTag && OwnedTag->isDefinition()) {
6009 // The type-specifier-seq shall not declare a new class or enumeration.
6010 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6011 }
6012
6013 DeclPtrTy Dcl = ActOnDeclarator(S, D);
6014 if (!Dcl)
6015 return DeclResult();
6016
6017 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
6018 VD->setDeclaredInCondition(true);
6019 return Dcl;
6020}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006021
Anders Carlsson11e51402010-04-17 20:15:18 +00006022static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00006023 // Ignore dependent types.
6024 if (MD->isDependentContext())
Rafael Espindola70e040d2010-03-02 21:28:26 +00006025 return false;
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00006026
Douglas Gregorccecc1b2010-01-06 20:27:16 +00006027 // Ignore declarations that are not definitions.
6028 if (!MD->isThisDeclarationADefinition())
Rafael Espindola70e040d2010-03-02 21:28:26 +00006029 return false;
6030
6031 CXXRecordDecl *RD = MD->getParent();
6032
6033 // Ignore classes without a vtable.
6034 if (!RD->isDynamicClass())
6035 return false;
6036
6037 switch (MD->getParent()->getTemplateSpecializationKind()) {
6038 case TSK_Undeclared:
6039 case TSK_ExplicitSpecialization:
6040 // Classes that aren't instantiations of templates don't need their
6041 // virtual methods marked until we see the definition of the key
6042 // function.
6043 break;
6044
6045 case TSK_ImplicitInstantiation:
6046 // This is a constructor of a class template; mark all of the virtual
6047 // members as referenced to ensure that they get instantiatied.
6048 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
6049 return true;
6050 break;
6051
6052 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola8d04f062010-03-22 23:12:48 +00006053 return false;
Rafael Espindola70e040d2010-03-02 21:28:26 +00006054
6055 case TSK_ExplicitInstantiationDefinition:
6056 // This is method of a explicit instantiation; mark all of the virtual
6057 // members as referenced to ensure that they get instantiatied.
6058 return true;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00006059 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00006060
6061 // Consider only out-of-line definitions of member functions. When we see
6062 // an inline definition, it's too early to compute the key function.
6063 if (!MD->isOutOfLine())
6064 return false;
6065
6066 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
6067
6068 // If there is no key function, we will need a copy of the vtable.
6069 if (!KeyFunction)
6070 return true;
6071
6072 // If this is the key function, we need to mark virtual members.
6073 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
6074 return true;
6075
6076 return false;
6077}
6078
6079void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
6080 CXXMethodDecl *MD) {
6081 CXXRecordDecl *RD = MD->getParent();
6082
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00006083 // We will need to mark all of the virtual members as referenced to build the
6084 // vtable.
Anders Carlsson11e51402010-04-17 20:15:18 +00006085 if (!needsVTable(MD, Context))
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006086 return;
6087
6088 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006089 if (kind == TSK_ImplicitInstantiation)
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006090 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006091 else
6092 MarkVirtualMembersReferenced(Loc, RD);
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006093}
6094
Anders Carlsson82fccd02009-12-07 08:24:59 +00006095bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
6096 if (ClassesWithUnmarkedVirtualMembers.empty())
6097 return false;
6098
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00006099 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
6100 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
6101 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
6102 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00006103 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006104 }
6105
Anders Carlsson82fccd02009-12-07 08:24:59 +00006106 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006107}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006108
Rafael Espindola5b334082010-03-26 00:36:59 +00006109void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6110 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006111 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6112 e = RD->method_end(); i != e; ++i) {
6113 CXXMethodDecl *MD = *i;
6114
6115 // C++ [basic.def.odr]p2:
6116 // [...] A virtual member function is used if it is not pure. [...]
6117 if (MD->isVirtual() && !MD->isPure())
6118 MarkDeclarationReferenced(Loc, MD);
6119 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006120
6121 // Only classes that have virtual bases need a VTT.
6122 if (RD->getNumVBases() == 0)
6123 return;
6124
6125 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6126 e = RD->bases_end(); i != e; ++i) {
6127 const CXXRecordDecl *Base =
6128 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6129 if (i->isVirtual())
6130 continue;
6131 if (Base->getNumVBases() == 0)
6132 continue;
6133 MarkVirtualMembersReferenced(Loc, Base);
6134 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006135}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006136
6137/// SetIvarInitializers - This routine builds initialization ASTs for the
6138/// Objective-C implementation whose ivars need be initialized.
6139void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6140 if (!getLangOptions().CPlusPlus)
6141 return;
6142 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6143 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6144 CollectIvarsToConstructOrDestruct(OID, ivars);
6145 if (ivars.empty())
6146 return;
6147 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6148 for (unsigned i = 0; i < ivars.size(); i++) {
6149 FieldDecl *Field = ivars[i];
6150 CXXBaseOrMemberInitializer *Member;
6151 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6152 InitializationKind InitKind =
6153 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6154
6155 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6156 Sema::OwningExprResult MemberInit =
6157 InitSeq.Perform(*this, InitEntity, InitKind,
6158 Sema::MultiExprArg(*this, 0, 0));
6159 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6160 // Note, MemberInit could actually come back empty if no initialization
6161 // is required (e.g., because it would call a trivial default constructor)
6162 if (!MemberInit.get() || MemberInit.isInvalid())
6163 continue;
6164
6165 Member =
6166 new (Context) CXXBaseOrMemberInitializer(Context,
6167 Field, SourceLocation(),
6168 SourceLocation(),
6169 MemberInit.takeAs<Expr>(),
6170 SourceLocation());
6171 AllToInit.push_back(Member);
6172 }
6173 ObjCImplementation->setIvarInitializers(Context,
6174 AllToInit.data(), AllToInit.size());
6175 }
6176}