blob: 33b312409040232bf2308164a7e704800a7e86a4 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
Anders Carlsson6e997b22009-12-15 20:51:39 +0000140 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Anders Carlssonf1c26952009-08-25 01:02:06 +0000180 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000181 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
182 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000183 Param->setInvalidDecl();
184 return;
185 }
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCallb268a282010-08-23 23:25:46 +0000187 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000188}
189
Douglas Gregor58354032008-12-24 00:01:03 +0000190/// ActOnParamUnparsedDefaultArgument - We've seen a default
191/// argument for a function parameter, but we can't parse it yet
192/// because we're inside a class definition. Note that this default
193/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000194void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000195 SourceLocation EqualLoc,
196 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump11289f42009-09-09 15:08:12 +0000199
John McCall48871652010-08-21 09:40:31 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000201 if (Param)
202 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000205}
206
Douglas Gregor4d87df52008-12-16 21:30:33 +0000207/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
208/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000209void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000210 if (!param)
211 return;
Mike Stump11289f42009-09-09 15:08:12 +0000212
John McCall48871652010-08-21 09:40:31 +0000213 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000214
Anders Carlsson84613c42009-06-12 16:51:40 +0000215 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000216
Anders Carlsson84613c42009-06-12 16:51:40 +0000217 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000218}
219
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000220/// CheckExtraCXXDefaultArguments - Check for any extra default
221/// arguments in the declarator, which is not a function declaration
222/// or definition and therefore is not permitted to have default
223/// arguments. This routine should be invoked for every declarator
224/// that is not a function declaration or definition.
225void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
226 // C++ [dcl.fct.default]p3
227 // A default argument expression shall be specified only in the
228 // parameter-declaration-clause of a function declaration or in a
229 // template-parameter (14.1). It shall not be specified for a
230 // parameter pack. If it is specified in a
231 // parameter-declaration-clause, it shall not occur within a
232 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000234 DeclaratorChunk &chunk = D.getTypeObject(i);
235 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000236 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
237 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000238 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000239 if (Param->hasUnparsedDefaultArg()) {
240 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000241 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
242 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
243 delete Toks;
244 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000245 } else if (Param->getDefaultArg()) {
246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << Param->getDefaultArg()->getSourceRange();
248 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000249 }
250 }
251 }
252 }
253}
254
Chris Lattner199abbc2008-04-08 05:04:30 +0000255// MergeCXXFunctionDecl - Merge two declarations of the same C++
256// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000257// type. Subroutine of MergeFunctionDecl. Returns true if there was an
258// error, false otherwise.
259bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
260 bool Invalid = false;
261
Chris Lattner199abbc2008-04-08 05:04:30 +0000262 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000263 // For non-template functions, default arguments can be added in
264 // later declarations of a function in the same
265 // scope. Declarations in different scopes have completely
266 // distinct sets of default arguments. That is, declarations in
267 // inner scopes do not acquire default arguments from
268 // declarations in outer scopes, and vice versa. In a given
269 // function declaration, all parameters subsequent to a
270 // parameter with a default argument shall have default
271 // arguments supplied in this or previous declarations. A
272 // default argument shall not be redefined by a later
273 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000274 //
275 // C++ [dcl.fct.default]p6:
276 // Except for member functions of class templates, the default arguments
277 // in a member function definition that appears outside of the class
278 // definition are added to the set of default arguments provided by the
279 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000280 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
281 ParmVarDecl *OldParam = Old->getParamDecl(p);
282 ParmVarDecl *NewParam = New->getParamDecl(p);
283
Douglas Gregorc732aba2009-09-11 18:44:32 +0000284 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000285 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
286 // hint here. Alternatively, we could walk the type-source information
287 // for NewParam to find the last source location in the type... but it
288 // isn't worth the effort right now. This is the kind of test case that
289 // is hard to get right:
290
291 // int f(int);
292 // void g(int (*fp)(int) = f);
293 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000294 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000295 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000296 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000297
298 // Look for the function declaration where the default argument was
299 // actually written, which may be a declaration prior to Old.
300 for (FunctionDecl *Older = Old->getPreviousDeclaration();
301 Older; Older = Older->getPreviousDeclaration()) {
302 if (!Older->getParamDecl(p)->hasDefaultArg())
303 break;
304
305 OldParam = Older->getParamDecl(p);
306 }
307
308 Diag(OldParam->getLocation(), diag::note_previous_definition)
309 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000310 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000311 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000312 // Merge the old default argument into the new parameter.
313 // It's important to use getInit() here; getDefaultArg()
314 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000315 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000316 if (OldParam->hasUninstantiatedDefaultArg())
317 NewParam->setUninstantiatedDefaultArg(
318 OldParam->getUninstantiatedDefaultArg());
319 else
John McCalle61b02b2010-05-04 01:53:42 +0000320 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000321 } else if (NewParam->hasDefaultArg()) {
322 if (New->getDescribedFunctionTemplate()) {
323 // Paragraph 4, quoted above, only applies to non-template functions.
324 Diag(NewParam->getLocation(),
325 diag::err_param_default_argument_template_redecl)
326 << NewParam->getDefaultArgRange();
327 Diag(Old->getLocation(), diag::note_template_prev_declaration)
328 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000329 } else if (New->getTemplateSpecializationKind()
330 != TSK_ImplicitInstantiation &&
331 New->getTemplateSpecializationKind() != TSK_Undeclared) {
332 // C++ [temp.expr.spec]p21:
333 // Default function arguments shall not be specified in a declaration
334 // or a definition for one of the following explicit specializations:
335 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000336 // - the explicit specialization of a member function template;
337 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000338 // template where the class template specialization to which the
339 // member function specialization belongs is implicitly
340 // instantiated.
341 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
342 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
343 << New->getDeclName()
344 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000345 } else if (New->getDeclContext()->isDependentContext()) {
346 // C++ [dcl.fct.default]p6 (DR217):
347 // Default arguments for a member function of a class template shall
348 // be specified on the initial declaration of the member function
349 // within the class template.
350 //
351 // Reading the tea leaves a bit in DR217 and its reference to DR205
352 // leads me to the conclusion that one cannot add default function
353 // arguments for an out-of-line definition of a member function of a
354 // dependent type.
355 int WhichKind = 2;
356 if (CXXRecordDecl *Record
357 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
358 if (Record->getDescribedClassTemplate())
359 WhichKind = 0;
360 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
361 WhichKind = 1;
362 else
363 WhichKind = 2;
364 }
365
366 Diag(NewParam->getLocation(),
367 diag::err_param_default_argument_member_template_redecl)
368 << WhichKind
369 << NewParam->getDefaultArgRange();
370 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000371 }
372 }
373
Douglas Gregorf40863c2010-02-12 07:32:17 +0000374 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000375 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000376
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000377 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000378}
379
380/// CheckCXXDefaultArguments - Verify that the default arguments for a
381/// function declaration are well-formed according to C++
382/// [dcl.fct.default].
383void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
384 unsigned NumParams = FD->getNumParams();
385 unsigned p;
386
387 // Find first parameter with a default argument
388 for (p = 0; p < NumParams; ++p) {
389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000390 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000391 break;
392 }
393
394 // C++ [dcl.fct.default]p4:
395 // In a given function declaration, all parameters
396 // subsequent to a parameter with a default argument shall
397 // have default arguments supplied in this or previous
398 // declarations. A default argument shall not be redefined
399 // by a later declaration (not even to the same value).
400 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000401 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000402 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000403 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000404 if (Param->isInvalidDecl())
405 /* We already complained about this parameter. */;
406 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000407 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000408 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000409 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000410 else
Mike Stump11289f42009-09-09 15:08:12 +0000411 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000412 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner199abbc2008-04-08 05:04:30 +0000414 LastMissingDefaultArg = p;
415 }
416 }
417
418 if (LastMissingDefaultArg > 0) {
419 // Some default arguments were missing. Clear out all of the
420 // default arguments up to (and including) the last missing
421 // default argument, so that we leave the function parameters
422 // in a semantically valid state.
423 for (p = 0; p <= LastMissingDefaultArg; ++p) {
424 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000425 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000426 Param->setDefaultArg(0);
427 }
428 }
429 }
430}
Douglas Gregor556877c2008-04-13 21:30:24 +0000431
Douglas Gregor61956c42008-10-31 09:07:45 +0000432/// isCurrentClassName - Determine whether the identifier II is the
433/// name of the class type currently being defined. In the case of
434/// nested classes, this will only return true if II is the name of
435/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000436bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
437 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000438 assert(getLangOptions().CPlusPlus && "No class names in C!");
439
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000440 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000441 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000442 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000443 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
444 } else
445 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
446
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000447 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000448 return &II == CurDecl->getIdentifier();
449 else
450 return false;
451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000454///
455/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
456/// and returns NULL otherwise.
457CXXBaseSpecifier *
458Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
459 SourceRange SpecifierRange,
460 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000461 TypeSourceInfo *TInfo) {
462 QualType BaseType = TInfo->getType();
463
Douglas Gregor463421d2009-03-03 04:44:36 +0000464 // C++ [class.union]p1:
465 // A union shall not have base classes.
466 if (Class->isUnion()) {
467 Diag(Class->getLocation(), diag::err_base_clause_on_union)
468 << SpecifierRange;
469 return 0;
470 }
471
472 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000473 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000474 Class->getTagKind() == TTK_Class,
475 Access, TInfo);
476
477 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000478
479 // Base specifiers must be record types.
480 if (!BaseType->isRecordType()) {
481 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
482 return 0;
483 }
484
485 // C++ [class.union]p1:
486 // A union shall not be used as a base class.
487 if (BaseType->isUnionType()) {
488 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
489 return 0;
490 }
491
492 // C++ [class.derived]p2:
493 // The class-name in a base-specifier shall not be an incompletely
494 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000495 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000496 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000497 << SpecifierRange)) {
498 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000499 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000500 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000501
Eli Friedmanc96d4962009-08-15 21:55:26 +0000502 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000503 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000504 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000505 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000506 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000507 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
508 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000509
Alexis Hunt96d5c762009-11-21 08:43:09 +0000510 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
511 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
512 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000513 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
514 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000515 return 0;
516 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000517
John McCall3696dcb2010-08-17 07:23:57 +0000518 if (BaseDecl->isInvalidDecl())
519 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000520
521 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000522 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000523 Class->getTagKind() == TTK_Class,
524 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000525}
526
Douglas Gregor556877c2008-04-13 21:30:24 +0000527/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
528/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000529/// example:
530/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000531/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000532BaseResult
John McCall48871652010-08-21 09:40:31 +0000533Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000534 bool Virtual, AccessSpecifier Access,
John McCallba7bf592010-08-24 05:47:05 +0000535 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000536 if (!classdecl)
537 return true;
538
Douglas Gregorc40290e2009-03-09 23:48:35 +0000539 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000541 if (!Class)
542 return true;
543
Nick Lewycky19b9f952010-07-26 16:56:01 +0000544 TypeSourceInfo *TInfo = 0;
545 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor463421d2009-03-03 04:44:36 +0000546 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000547 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000548 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Douglas Gregor463421d2009-03-03 04:44:36 +0000550 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000551}
Douglas Gregor556877c2008-04-13 21:30:24 +0000552
Douglas Gregor463421d2009-03-03 04:44:36 +0000553/// \brief Performs the actual work of attaching the given base class
554/// specifiers to a C++ class.
555bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
556 unsigned NumBases) {
557 if (NumBases == 0)
558 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000559
560 // Used to keep track of which base types we have already seen, so
561 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000562 // that the key is always the unqualified canonical type of the base
563 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000564 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
565
566 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000567 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000569 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000570 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000572 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000573 if (!Class->hasObjectMember()) {
574 if (const RecordType *FDTTy =
575 NewBaseType.getTypePtr()->getAs<RecordType>())
576 if (FDTTy->getDecl()->hasObjectMember())
577 Class->setHasObjectMember(true);
578 }
579
Douglas Gregor29a92472008-10-22 17:49:05 +0000580 if (KnownBaseTypes[NewBaseType]) {
581 // C++ [class.mi]p3:
582 // A class shall not be specified as a direct base class of a
583 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000584 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000585 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000586 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000587 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000588
589 // Delete the duplicate base class specifier; we're going to
590 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000591 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000592
593 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000594 } else {
595 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 KnownBaseTypes[NewBaseType] = Bases[idx];
597 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000598 }
599 }
600
601 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000602 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000603
604 // Delete the remaining (good) base class specifiers, since their
605 // data has been copied into the CXXRecordDecl.
606 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000607 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000608
609 return Invalid;
610}
611
612/// ActOnBaseSpecifiers - Attach the given base specifiers to the
613/// class, after checking whether there are any duplicate base
614/// classes.
John McCall48871652010-08-21 09:40:31 +0000615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000616 unsigned NumBases) {
617 if (!ClassDecl || !Bases || !NumBases)
618 return;
619
620 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000623}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000624
John McCalle78aac42010-03-10 03:28:59 +0000625static CXXRecordDecl *GetClassForType(QualType T) {
626 if (const RecordType *RT = T->getAs<RecordType>())
627 return cast<CXXRecordDecl>(RT->getDecl());
628 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
629 return ICT->getDecl();
630 else
631 return 0;
632}
633
Douglas Gregor36d1b142009-10-06 17:59:45 +0000634/// \brief Determine whether the type \p Derived is a C++ class that is
635/// derived from the type \p Base.
636bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
637 if (!getLangOptions().CPlusPlus)
638 return false;
John McCalle78aac42010-03-10 03:28:59 +0000639
640 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
641 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000642 return false;
643
John McCalle78aac42010-03-10 03:28:59 +0000644 CXXRecordDecl *BaseRD = GetClassForType(Base);
645 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000646 return false;
647
John McCall67da35c2010-02-04 22:26:26 +0000648 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
649 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000650}
651
652/// \brief Determine whether the type \p Derived is a C++ class that is
653/// derived from the type \p Base.
654bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
655 if (!getLangOptions().CPlusPlus)
656 return false;
657
John McCalle78aac42010-03-10 03:28:59 +0000658 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
659 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000660 return false;
661
John McCalle78aac42010-03-10 03:28:59 +0000662 CXXRecordDecl *BaseRD = GetClassForType(Base);
663 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
Douglas Gregor36d1b142009-10-06 17:59:45 +0000666 return DerivedRD->isDerivedFrom(BaseRD, Paths);
667}
668
Anders Carlssona70cff62010-04-24 19:06:50 +0000669void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000670 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000671 assert(BasePathArray.empty() && "Base path array must be empty!");
672 assert(Paths.isRecordingPaths() && "Must record paths!");
673
674 const CXXBasePath &Path = Paths.front();
675
676 // We first go backward and check if we have a virtual base.
677 // FIXME: It would be better if CXXBasePath had the base specifier for
678 // the nearest virtual base.
679 unsigned Start = 0;
680 for (unsigned I = Path.size(); I != 0; --I) {
681 if (Path[I - 1].Base->isVirtual()) {
682 Start = I - 1;
683 break;
684 }
685 }
686
687 // Now add all bases.
688 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000690}
691
Douglas Gregor88d292c2010-05-13 16:44:06 +0000692/// \brief Determine whether the given base path includes a virtual
693/// base class.
John McCallcf142162010-08-07 06:22:56 +0000694bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
695 for (CXXCastPath::const_iterator B = BasePath.begin(),
696 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000697 B != BEnd; ++B)
698 if ((*B)->isVirtual())
699 return true;
700
701 return false;
702}
703
Douglas Gregor36d1b142009-10-06 17:59:45 +0000704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
705/// conversion (where Derived and Base are class types) is
706/// well-formed, meaning that the conversion is unambiguous (and
707/// that all of the base classes are accessible). Returns true
708/// and emits a diagnostic if the code is ill-formed, returns false
709/// otherwise. Loc is the location where this routine should point to
710/// if there is an error, and Range is the source range to highlight
711/// if there is an error.
712bool
713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000714 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000715 unsigned AmbigiousBaseConvID,
716 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000717 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000718 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000719 // First, determine whether the path from Derived to Base is
720 // ambiguous. This is slightly more expensive than checking whether
721 // the Derived to Base conversion exists, because here we need to
722 // explore multiple paths to determine if there is an ambiguity.
723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
724 /*DetectVirtual=*/false);
725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
726 assert(DerivationOkay &&
727 "Can only be used with a derived-to-base conversion");
728 (void)DerivationOkay;
729
730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000731 if (InaccessibleBaseID) {
732 // Check that the base class can be accessed.
733 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
734 InaccessibleBaseID)) {
735 case AR_inaccessible:
736 return true;
737 case AR_accessible:
738 case AR_dependent:
739 case AR_delayed:
740 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000741 }
John McCall5b0829a2010-02-10 09:31:12 +0000742 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000743
744 // Build a base path if necessary.
745 if (BasePath)
746 BuildBasePathArray(Paths, *BasePath);
747 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000748 }
749
750 // We know that the derived-to-base conversion is ambiguous, and
751 // we're going to produce a diagnostic. Perform the derived-to-base
752 // search just one more time to compute all of the possible paths so
753 // that we can print them out. This is more expensive than any of
754 // the previous derived-to-base checks we've done, but at this point
755 // performance isn't as much of an issue.
756 Paths.clear();
757 Paths.setRecordingPaths(true);
758 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
759 assert(StillOkay && "Can only be used with a derived-to-base conversion");
760 (void)StillOkay;
761
762 // Build up a textual representation of the ambiguous paths, e.g.,
763 // D -> B -> A, that will be used to illustrate the ambiguous
764 // conversions in the diagnostic. We only print one of the paths
765 // to each base class subobject.
766 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
767
768 Diag(Loc, AmbigiousBaseConvID)
769 << Derived << Base << PathDisplayStr << Range << Name;
770 return true;
771}
772
773bool
774Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000775 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000776 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000777 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000778 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000779 IgnoreAccess ? 0
780 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000781 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000782 Loc, Range, DeclarationName(),
783 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000784}
785
786
787/// @brief Builds a string representing ambiguous paths from a
788/// specific derived class to different subobjects of the same base
789/// class.
790///
791/// This function builds a string that can be used in error messages
792/// to show the different paths that one can take through the
793/// inheritance hierarchy to go from the derived class to different
794/// subobjects of a base class. The result looks something like this:
795/// @code
796/// struct D -> struct B -> struct A
797/// struct D -> struct C -> struct A
798/// @endcode
799std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
800 std::string PathDisplayStr;
801 std::set<unsigned> DisplayedPaths;
802 for (CXXBasePaths::paths_iterator Path = Paths.begin();
803 Path != Paths.end(); ++Path) {
804 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
805 // We haven't displayed a path to this particular base
806 // class subobject yet.
807 PathDisplayStr += "\n ";
808 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
809 for (CXXBasePath::const_iterator Element = Path->begin();
810 Element != Path->end(); ++Element)
811 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
812 }
813 }
814
815 return PathDisplayStr;
816}
817
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000818//===----------------------------------------------------------------------===//
819// C++ class member Handling
820//===----------------------------------------------------------------------===//
821
Abramo Bagnarad7340582010-06-05 05:09:32 +0000822/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000823Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
824 SourceLocation ASLoc,
825 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000826 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000827 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000828 ASLoc, ColonLoc);
829 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000830 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000831}
832
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000833/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
834/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
835/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000836/// any.
John McCall48871652010-08-21 09:40:31 +0000837Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000838Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000839 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000840 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
841 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000842 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000843 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
844 DeclarationName Name = NameInfo.getName();
845 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000846
847 // For anonymous bitfields, the location should point to the type.
848 if (Loc.isInvalid())
849 Loc = D.getSourceRange().getBegin();
850
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000851 Expr *BitWidth = static_cast<Expr*>(BW);
852 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853
John McCallb1cd7da2010-06-04 08:34:12 +0000854 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000855 assert(!DS.isFriendSpecified());
856
John McCallb1cd7da2010-06-04 08:34:12 +0000857 bool isFunc = false;
858 if (D.isFunctionDeclarator())
859 isFunc = true;
860 else if (D.getNumTypeObjects() == 0 &&
861 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000862 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000863 isFunc = TDType->isFunctionType();
864 }
865
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000866 // C++ 9.2p6: A member shall not be declared to have automatic storage
867 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000868 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
869 // data members and cannot be applied to names declared const or static,
870 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000871 switch (DS.getStorageClassSpec()) {
872 case DeclSpec::SCS_unspecified:
873 case DeclSpec::SCS_typedef:
874 case DeclSpec::SCS_static:
875 // FALL THROUGH.
876 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000877 case DeclSpec::SCS_mutable:
878 if (isFunc) {
879 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000880 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000881 else
Chris Lattner3b054132008-11-19 05:08:23 +0000882 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000883
Sebastian Redl8071edb2008-11-17 23:24:37 +0000884 // FIXME: It would be nicer if the keyword was ignored only for this
885 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000886 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000887 }
888 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000889 default:
890 if (DS.getStorageClassSpecLoc().isValid())
891 Diag(DS.getStorageClassSpecLoc(),
892 diag::err_storageclass_invalid_for_member);
893 else
894 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
895 D.getMutableDeclSpec().ClearStorageClassSpecs();
896 }
897
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000898 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
899 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000900 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000901
902 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000903 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000904 CXXScopeSpec &SS = D.getCXXScopeSpec();
905
906
907 if (SS.isSet() && !SS.isInvalid()) {
908 // The user provided a superfluous scope specifier inside a class
909 // definition:
910 //
911 // class X {
912 // int X::member;
913 // };
914 DeclContext *DC = 0;
915 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
916 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
917 << Name << FixItHint::CreateRemoval(SS.getRange());
918 else
919 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
920 << Name << SS.getRange();
921
922 SS.clear();
923 }
924
Douglas Gregor3447e762009-08-20 22:52:58 +0000925 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000926 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
927 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000928 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000929 } else {
John McCall48871652010-08-21 09:40:31 +0000930 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000931 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000932 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000933 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000934
935 // Non-instance-fields can't have a bitfield.
936 if (BitWidth) {
937 if (Member->isInvalidDecl()) {
938 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000939 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000940 // C++ 9.6p3: A bit-field shall not be a static member.
941 // "static member 'A' cannot be a bit-field"
942 Diag(Loc, diag::err_static_not_bitfield)
943 << Name << BitWidth->getSourceRange();
944 } else if (isa<TypedefDecl>(Member)) {
945 // "typedef member 'x' cannot be a bit-field"
946 Diag(Loc, diag::err_typedef_not_bitfield)
947 << Name << BitWidth->getSourceRange();
948 } else {
949 // A function typedef ("typedef int f(); f a;").
950 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
951 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000952 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000953 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000954 }
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattnerd26760a2009-03-05 23:01:03 +0000956 BitWidth = 0;
957 Member->setInvalidDecl();
958 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000959
960 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregor3447e762009-08-20 22:52:58 +0000962 // If we have declared a member function template, set the access of the
963 // templated declaration as well.
964 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
965 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000966 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000967
Douglas Gregor92751d42008-11-17 22:58:34 +0000968 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000969
Douglas Gregor0c880302009-03-11 23:00:04 +0000970 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000971 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000972 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000973 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000974
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000975 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000976 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +0000977 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000978 }
John McCall48871652010-08-21 09:40:31 +0000979 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000980}
981
Douglas Gregor15e77a22009-12-31 09:10:24 +0000982/// \brief Find the direct and/or virtual base specifiers that
983/// correspond to the given base type, for use in base initialization
984/// within a constructor.
985static bool FindBaseInitializer(Sema &SemaRef,
986 CXXRecordDecl *ClassDecl,
987 QualType BaseType,
988 const CXXBaseSpecifier *&DirectBaseSpec,
989 const CXXBaseSpecifier *&VirtualBaseSpec) {
990 // First, check for a direct base class.
991 DirectBaseSpec = 0;
992 for (CXXRecordDecl::base_class_const_iterator Base
993 = ClassDecl->bases_begin();
994 Base != ClassDecl->bases_end(); ++Base) {
995 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
996 // We found a direct base of this type. That's what we're
997 // initializing.
998 DirectBaseSpec = &*Base;
999 break;
1000 }
1001 }
1002
1003 // Check for a virtual base class.
1004 // FIXME: We might be able to short-circuit this if we know in advance that
1005 // there are no virtual bases.
1006 VirtualBaseSpec = 0;
1007 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1008 // We haven't found a base yet; search the class hierarchy for a
1009 // virtual base class.
1010 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1011 /*DetectVirtual=*/false);
1012 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1013 BaseType, Paths)) {
1014 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1015 Path != Paths.end(); ++Path) {
1016 if (Path->back().Base->isVirtual()) {
1017 VirtualBaseSpec = Path->back().Base;
1018 break;
1019 }
1020 }
1021 }
1022 }
1023
1024 return DirectBaseSpec || VirtualBaseSpec;
1025}
1026
Douglas Gregore8381c02008-11-05 04:29:56 +00001027/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001028MemInitResult
John McCall48871652010-08-21 09:40:31 +00001029Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001030 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001031 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001032 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001033 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001034 SourceLocation IdLoc,
1035 SourceLocation LParenLoc,
1036 ExprTy **Args, unsigned NumArgs,
Douglas Gregore8381c02008-11-05 04:29:56 +00001037 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001038 if (!ConstructorD)
1039 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001041 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001042
1043 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001044 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001045 if (!Constructor) {
1046 // The user wrote a constructor initializer on a function that is
1047 // not a C++ constructor. Ignore the error for now, because we may
1048 // have more member initializers coming; we'll diagnose it just
1049 // once in ActOnMemInitializers.
1050 return true;
1051 }
1052
1053 CXXRecordDecl *ClassDecl = Constructor->getParent();
1054
1055 // C++ [class.base.init]p2:
1056 // Names in a mem-initializer-id are looked up in the scope of the
1057 // constructor’s class and, if not found in that scope, are looked
1058 // up in the scope containing the constructor’s
1059 // definition. [Note: if the constructor’s class contains a member
1060 // with the same name as a direct or virtual base class of the
1061 // class, a mem-initializer-id naming the member or base class and
1062 // composed of a single identifier refers to the class member. A
1063 // mem-initializer-id for the hidden base class may be specified
1064 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001065 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001066 // Look for a member, first.
1067 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001068 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001069 = ClassDecl->lookup(MemberOrBase);
1070 if (Result.first != Result.second)
1071 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001072
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001073 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001074
Eli Friedman8e1433b2009-07-29 19:44:27 +00001075 if (Member)
1076 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001077 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001078 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001079 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001080 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001081 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001082
1083 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001084 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001085 } else {
1086 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1087 LookupParsedName(R, S, &SS);
1088
1089 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1090 if (!TyD) {
1091 if (R.isAmbiguous()) return true;
1092
John McCallda6841b2010-04-09 19:01:14 +00001093 // We don't want access-control diagnostics here.
1094 R.suppressDiagnostics();
1095
Douglas Gregora3b624a2010-01-19 06:46:48 +00001096 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1097 bool NotUnknownSpecialization = false;
1098 DeclContext *DC = computeDeclContext(SS, false);
1099 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1100 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1101
1102 if (!NotUnknownSpecialization) {
1103 // When the scope specifier can refer to a member of an unknown
1104 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001105 BaseType = CheckTypenameType(ETK_None,
1106 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001107 *MemberOrBase, SourceLocation(),
1108 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001109 if (BaseType.isNull())
1110 return true;
1111
Douglas Gregora3b624a2010-01-19 06:46:48 +00001112 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001113 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001114 }
1115 }
1116
Douglas Gregor15e77a22009-12-31 09:10:24 +00001117 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001118 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001119 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1120 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001121 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001122 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001123 // We have found a non-static data member with a similar
1124 // name to what was typed; complain and initialize that
1125 // member.
1126 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1127 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001128 << FixItHint::CreateReplacement(R.getNameLoc(),
1129 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001130 Diag(Member->getLocation(), diag::note_previous_decl)
1131 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001132
1133 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1134 LParenLoc, RParenLoc);
1135 }
1136 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1137 const CXXBaseSpecifier *DirectBaseSpec;
1138 const CXXBaseSpecifier *VirtualBaseSpec;
1139 if (FindBaseInitializer(*this, ClassDecl,
1140 Context.getTypeDeclType(Type),
1141 DirectBaseSpec, VirtualBaseSpec)) {
1142 // We have found a direct or virtual base class with a
1143 // similar name to what was typed; complain and initialize
1144 // that base class.
1145 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1146 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001147 << FixItHint::CreateReplacement(R.getNameLoc(),
1148 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001149
1150 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1151 : VirtualBaseSpec;
1152 Diag(BaseSpec->getSourceRange().getBegin(),
1153 diag::note_base_class_specified_here)
1154 << BaseSpec->getType()
1155 << BaseSpec->getSourceRange();
1156
Douglas Gregor15e77a22009-12-31 09:10:24 +00001157 TyD = Type;
1158 }
1159 }
1160 }
1161
Douglas Gregora3b624a2010-01-19 06:46:48 +00001162 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001163 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1164 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1165 return true;
1166 }
John McCallb5a0d312009-12-21 10:41:20 +00001167 }
1168
Douglas Gregora3b624a2010-01-19 06:46:48 +00001169 if (BaseType.isNull()) {
1170 BaseType = Context.getTypeDeclType(TyD);
1171 if (SS.isSet()) {
1172 NestedNameSpecifier *Qualifier =
1173 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001174
Douglas Gregora3b624a2010-01-19 06:46:48 +00001175 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001176 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001177 }
John McCallb5a0d312009-12-21 10:41:20 +00001178 }
1179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
John McCallbcd03502009-12-07 02:54:59 +00001181 if (!TInfo)
1182 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001183
John McCallbcd03502009-12-07 02:54:59 +00001184 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001185 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001186}
1187
John McCalle22a04a2009-11-04 23:02:40 +00001188/// Checks an initializer expression for use of uninitialized fields, such as
1189/// containing the field that is being initialized. Returns true if there is an
1190/// uninitialized field was used an updates the SourceLocation parameter; false
1191/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001192static bool InitExprContainsUninitializedFields(const Stmt *S,
1193 const FieldDecl *LhsField,
1194 SourceLocation *L) {
1195 if (isa<CallExpr>(S)) {
1196 // Do not descend into function calls or constructors, as the use
1197 // of an uninitialized field may be valid. One would have to inspect
1198 // the contents of the function/ctor to determine if it is safe or not.
1199 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1200 // may be safe, depending on what the function/ctor does.
1201 return false;
1202 }
1203 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1204 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001205
1206 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1207 // The member expression points to a static data member.
1208 assert(VD->isStaticDataMember() &&
1209 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001210 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001211 return false;
1212 }
1213
1214 if (isa<EnumConstantDecl>(RhsField)) {
1215 // The member expression points to an enum.
1216 return false;
1217 }
1218
John McCalle22a04a2009-11-04 23:02:40 +00001219 if (RhsField == LhsField) {
1220 // Initializing a field with itself. Throw a warning.
1221 // But wait; there are exceptions!
1222 // Exception #1: The field may not belong to this record.
1223 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001224 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001225 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1226 // Even though the field matches, it does not belong to this record.
1227 return false;
1228 }
1229 // None of the exceptions triggered; return true to indicate an
1230 // uninitialized field was used.
1231 *L = ME->getMemberLoc();
1232 return true;
1233 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001234 } else if (isa<SizeOfAlignOfExpr>(S)) {
1235 // sizeof/alignof doesn't reference contents, do not warn.
1236 return false;
1237 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1238 // address-of doesn't reference contents (the pointer may be dereferenced
1239 // in the same expression but it would be rare; and weird).
1240 if (UOE->getOpcode() == UO_AddrOf)
1241 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001242 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001243 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1244 it != e; ++it) {
1245 if (!*it) {
1246 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001247 continue;
1248 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001249 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1250 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001251 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001252 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001253}
1254
John McCallfaf5fb42010-08-26 23:41:50 +00001255MemInitResult
Eli Friedman8e1433b2009-07-29 19:44:27 +00001256Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1257 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001258 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001259 SourceLocation RParenLoc) {
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001260 if (Member->isInvalidDecl())
1261 return true;
1262
John McCalle22a04a2009-11-04 23:02:40 +00001263 // Diagnose value-uses of fields to initialize themselves, e.g.
1264 // foo(foo)
1265 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001266 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001267 for (unsigned i = 0; i < NumArgs; ++i) {
1268 SourceLocation L;
1269 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1270 // FIXME: Return true in the case when other fields are used before being
1271 // uninitialized. For example, let this field be the i'th field. When
1272 // initializing the i'th field, throw a warning if any of the >= i'th
1273 // fields are used, as they are not yet initialized.
1274 // Right now we are only handling the case where the i'th field uses
1275 // itself in its initializer.
1276 Diag(L, diag::warn_field_is_uninit);
1277 }
1278 }
1279
Eli Friedman8e1433b2009-07-29 19:44:27 +00001280 bool HasDependentArg = false;
1281 for (unsigned i = 0; i < NumArgs; i++)
1282 HasDependentArg |= Args[i]->isTypeDependent();
1283
Eli Friedman9255adf2010-07-24 21:19:15 +00001284 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001285 // Can't check initialization for a member of dependent type or when
1286 // any of the arguments are type-dependent expressions.
John McCallb268a282010-08-23 23:25:46 +00001287 Expr *Init
1288 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1289 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001290
1291 // Erase any temporaries within this evaluation context; we're not
1292 // going to track them in the AST, since we'll be rebuilding the
1293 // ASTs during template instantiation.
1294 ExprTemporaries.erase(
1295 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1296 ExprTemporaries.end());
1297
1298 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1299 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001300 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001301 RParenLoc);
1302
Douglas Gregore8381c02008-11-05 04:29:56 +00001303 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001304
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001305 // Initialize the member.
1306 InitializedEntity MemberEntity =
1307 InitializedEntity::InitializeMember(Member, 0);
1308 InitializationKind Kind =
1309 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1310
1311 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1312
John McCalldadc5752010-08-24 06:29:42 +00001313 ExprResult MemberInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001314 InitSeq.Perform(*this, MemberEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001315 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001316 if (MemberInit.isInvalid())
1317 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001318
1319 CheckImplicitConversions(MemberInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001320
1321 // C++0x [class.base.init]p7:
1322 // The initialization of each base and member constitutes a
1323 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001324 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001325 if (MemberInit.isInvalid())
1326 return true;
1327
1328 // If we are in a dependent context, template instantiation will
1329 // perform this type-checking again. Just save the arguments that we
1330 // received in a ParenListExpr.
1331 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1332 // of the information that we have about the member
1333 // initializer. However, deconstructing the ASTs is a dicey process,
1334 // and this approach is far more likely to get the corner cases right.
1335 if (CurContext->isDependentContext()) {
John McCallb268a282010-08-23 23:25:46 +00001336 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1337 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001338 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1339 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001340 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001341 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,
John McCallb268a282010-08-23 23:25:46 +00001346 MemberInit.get(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001347 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001348}
1349
John McCallfaf5fb42010-08-26 23:41:50 +00001350MemInitResult
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
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001359 SourceLocation BaseLoc
1360 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1361
1362 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1363 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1364 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1365
1366 // C++ [class.base.init]p2:
1367 // [...] Unless the mem-initializer-id names a nonstatic data
1368 // member of the constructor’s class or a direct or virtual base
1369 // of that class, the mem-initializer is ill-formed. A
1370 // mem-initializer-list can initialize a base class using any
1371 // name that denotes that base class type.
1372 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1373
1374 // Check for direct and virtual base classes.
1375 const CXXBaseSpecifier *DirectBaseSpec = 0;
1376 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1377 if (!Dependent) {
1378 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1379 VirtualBaseSpec);
1380
1381 // C++ [base.class.init]p2:
1382 // Unless the mem-initializer-id names a nonstatic data member of the
1383 // constructor's class or a direct or virtual base of that class, the
1384 // mem-initializer is ill-formed.
1385 if (!DirectBaseSpec && !VirtualBaseSpec) {
1386 // If the class has any dependent bases, then it's possible that
1387 // one of those types will resolve to the same type as
1388 // BaseType. Therefore, just treat this as a dependent base
1389 // class initialization. FIXME: Should we try to check the
1390 // initialization anyway? It seems odd.
1391 if (ClassDecl->hasAnyDependentBases())
1392 Dependent = true;
1393 else
1394 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1395 << BaseType << Context.getTypeDeclType(ClassDecl)
1396 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1397 }
1398 }
1399
1400 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001401 // Can't check initialization for a base of dependent type or when
1402 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001403 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001404 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1405 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001406
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001407 // Erase any temporaries within this evaluation context; we're not
1408 // going to track them in the AST, since we'll be rebuilding the
1409 // ASTs during template instantiation.
1410 ExprTemporaries.erase(
1411 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1412 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001413
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001414 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001415 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001416 LParenLoc,
1417 BaseInit.takeAs<Expr>(),
1418 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001419 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001420
1421 // C++ [base.class.init]p2:
1422 // If a mem-initializer-id is ambiguous because it designates both
1423 // a direct non-virtual base class and an inherited virtual base
1424 // class, the mem-initializer is ill-formed.
1425 if (DirectBaseSpec && VirtualBaseSpec)
1426 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001427 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001428
1429 CXXBaseSpecifier *BaseSpec
1430 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1431 if (!BaseSpec)
1432 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1433
1434 // Initialize the base.
1435 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001436 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001437 InitializationKind Kind =
1438 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1439
1440 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1441
John McCalldadc5752010-08-24 06:29:42 +00001442 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001443 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001444 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001445 if (BaseInit.isInvalid())
1446 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001447
1448 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001449
1450 // C++0x [class.base.init]p7:
1451 // The initialization of each base and member constitutes a
1452 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001453 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001454 if (BaseInit.isInvalid())
1455 return true;
1456
1457 // If we are in a dependent context, template instantiation will
1458 // perform this type-checking again. Just save the arguments that we
1459 // received in a ParenListExpr.
1460 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1461 // of the information that we have about the base
1462 // initializer. However, deconstructing the ASTs is a dicey process,
1463 // and this approach is far more likely to get the corner cases right.
1464 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001465 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001466 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1467 RParenLoc));
1468 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001469 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001470 LParenLoc,
1471 Init.takeAs<Expr>(),
1472 RParenLoc);
1473 }
1474
1475 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001476 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001477 LParenLoc,
1478 BaseInit.takeAs<Expr>(),
1479 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001480}
1481
Anders Carlsson1b00e242010-04-23 03:10:23 +00001482/// ImplicitInitializerKind - How an implicit base or member initializer should
1483/// initialize its base or member.
1484enum ImplicitInitializerKind {
1485 IIK_Default,
1486 IIK_Copy,
1487 IIK_Move
1488};
1489
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001490static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001491BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001492 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001493 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001494 bool IsInheritedVirtualBase,
1495 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001496 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001497 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1498 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001499
John McCalldadc5752010-08-24 06:29:42 +00001500 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001501
1502 switch (ImplicitInitKind) {
1503 case IIK_Default: {
1504 InitializationKind InitKind
1505 = InitializationKind::CreateDefault(Constructor->getLocation());
1506 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1507 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001508 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001509 break;
1510 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001511
Anders Carlsson1b00e242010-04-23 03:10:23 +00001512 case IIK_Copy: {
1513 ParmVarDecl *Param = Constructor->getParamDecl(0);
1514 QualType ParamType = Param->getType().getNonReferenceType();
1515
1516 Expr *CopyCtorArg =
1517 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001518 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001519
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001520 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001521 QualType ArgTy =
1522 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1523 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001524
1525 CXXCastPath BasePath;
1526 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001527 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001528 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001529 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001530
Anders Carlsson1b00e242010-04-23 03:10:23 +00001531 InitializationKind InitKind
1532 = InitializationKind::CreateDirect(Constructor->getLocation(),
1533 SourceLocation(), SourceLocation());
1534 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1535 &CopyCtorArg, 1);
1536 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001537 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001538 break;
1539 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001540
Anders Carlsson1b00e242010-04-23 03:10:23 +00001541 case IIK_Move:
1542 assert(false && "Unhandled initializer kind!");
1543 }
John McCallb268a282010-08-23 23:25:46 +00001544
1545 if (BaseInit.isInvalid())
1546 return true;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001547
John McCallb268a282010-08-23 23:25:46 +00001548 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001549 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001550 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001551
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001552 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001553 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1554 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1555 SourceLocation()),
1556 BaseSpec->isVirtual(),
1557 SourceLocation(),
1558 BaseInit.takeAs<Expr>(),
1559 SourceLocation());
1560
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001561 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001562}
1563
Anders Carlsson3c1db572010-04-23 02:15:47 +00001564static bool
1565BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001566 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001567 FieldDecl *Field,
1568 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001569 if (Field->isInvalidDecl())
1570 return true;
1571
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001572 SourceLocation Loc = Constructor->getLocation();
1573
Anders Carlsson423f5d82010-04-23 16:04:08 +00001574 if (ImplicitInitKind == IIK_Copy) {
1575 ParmVarDecl *Param = Constructor->getParamDecl(0);
1576 QualType ParamType = Param->getType().getNonReferenceType();
1577
1578 Expr *MemberExprBase =
1579 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001580 Loc, ParamType, 0);
1581
1582 // Build a reference to this field within the parameter.
1583 CXXScopeSpec SS;
1584 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1585 Sema::LookupMemberName);
1586 MemberLookup.addDecl(Field, AS_public);
1587 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001588 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001589 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001590 ParamType, Loc,
1591 /*IsArrow=*/false,
1592 SS,
1593 /*FirstQualifierInScope=*/0,
1594 MemberLookup,
1595 /*TemplateArgs=*/0);
1596 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001597 return true;
1598
Douglas Gregor94f9a482010-05-05 05:51:00 +00001599 // When the field we are copying is an array, create index variables for
1600 // each dimension of the array. We use these index variables to subscript
1601 // the source array, and other clients (e.g., CodeGen) will perform the
1602 // necessary iteration with these index variables.
1603 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1604 QualType BaseType = Field->getType();
1605 QualType SizeType = SemaRef.Context.getSizeType();
1606 while (const ConstantArrayType *Array
1607 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1608 // Create the iteration variable for this array index.
1609 IdentifierInfo *IterationVarName = 0;
1610 {
1611 llvm::SmallString<8> Str;
1612 llvm::raw_svector_ostream OS(Str);
1613 OS << "__i" << IndexVariables.size();
1614 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1615 }
1616 VarDecl *IterationVar
1617 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1618 IterationVarName, SizeType,
1619 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001620 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001621 IndexVariables.push_back(IterationVar);
1622
1623 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001624 ExprResult IterationVarRef
Douglas Gregor94f9a482010-05-05 05:51:00 +00001625 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1626 assert(!IterationVarRef.isInvalid() &&
1627 "Reference to invented variable cannot fail!");
1628
1629 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001630 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001631 Loc,
John McCallb268a282010-08-23 23:25:46 +00001632 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001633 Loc);
1634 if (CopyCtorArg.isInvalid())
1635 return true;
1636
1637 BaseType = Array->getElementType();
1638 }
1639
1640 // Construct the entity that we will be initializing. For an array, this
1641 // will be first element in the array, which may require several levels
1642 // of array-subscript entities.
1643 llvm::SmallVector<InitializedEntity, 4> Entities;
1644 Entities.reserve(1 + IndexVariables.size());
1645 Entities.push_back(InitializedEntity::InitializeMember(Field));
1646 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1647 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1648 0,
1649 Entities.back()));
1650
1651 // Direct-initialize to use the copy constructor.
1652 InitializationKind InitKind =
1653 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1654
1655 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1656 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1657 &CopyCtorArgE, 1);
1658
John McCalldadc5752010-08-24 06:29:42 +00001659 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001660 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001661 MultiExprArg(&CopyCtorArgE, 1));
John McCallb268a282010-08-23 23:25:46 +00001662 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor94f9a482010-05-05 05:51:00 +00001663 if (MemberInit.isInvalid())
1664 return true;
1665
1666 CXXMemberInit
1667 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1668 MemberInit.takeAs<Expr>(), Loc,
1669 IndexVariables.data(),
1670 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001671 return false;
1672 }
1673
Anders Carlsson423f5d82010-04-23 16:04:08 +00001674 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1675
Anders Carlsson3c1db572010-04-23 02:15:47 +00001676 QualType FieldBaseElementType =
1677 SemaRef.Context.getBaseElementType(Field->getType());
1678
Anders Carlsson3c1db572010-04-23 02:15:47 +00001679 if (FieldBaseElementType->isRecordType()) {
1680 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001681 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001682 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001683
1684 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001685 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001686 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001687 if (MemberInit.isInvalid())
1688 return true;
1689
1690 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001691 if (MemberInit.isInvalid())
1692 return true;
1693
1694 CXXMemberInit =
1695 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001696 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001697 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001698 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001699 return false;
1700 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001701
1702 if (FieldBaseElementType->isReferenceType()) {
1703 SemaRef.Diag(Constructor->getLocation(),
1704 diag::err_uninitialized_member_in_ctor)
1705 << (int)Constructor->isImplicit()
1706 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1707 << 0 << Field->getDeclName();
1708 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1709 return true;
1710 }
1711
1712 if (FieldBaseElementType.isConstQualified()) {
1713 SemaRef.Diag(Constructor->getLocation(),
1714 diag::err_uninitialized_member_in_ctor)
1715 << (int)Constructor->isImplicit()
1716 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1717 << 1 << Field->getDeclName();
1718 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1719 return true;
1720 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001721
1722 // Nothing to initialize.
1723 CXXMemberInit = 0;
1724 return false;
1725}
John McCallbc83b3f2010-05-20 23:23:51 +00001726
1727namespace {
1728struct BaseAndFieldInfo {
1729 Sema &S;
1730 CXXConstructorDecl *Ctor;
1731 bool AnyErrorsInInits;
1732 ImplicitInitializerKind IIK;
1733 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1734 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1735
1736 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1737 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1738 // FIXME: Handle implicit move constructors.
1739 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1740 IIK = IIK_Copy;
1741 else
1742 IIK = IIK_Default;
1743 }
1744};
1745}
1746
Chandler Carruth139e9622010-06-30 02:59:29 +00001747static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1748 FieldDecl *Top, FieldDecl *Field,
1749 CXXBaseOrMemberInitializer *Init) {
1750 // If the member doesn't need to be initialized, Init will still be null.
1751 if (!Init)
1752 return;
1753
1754 Info.AllToInit.push_back(Init);
1755 if (Field != Top) {
1756 Init->setMember(Top);
1757 Init->setAnonUnionMember(Field);
1758 }
1759}
1760
John McCallbc83b3f2010-05-20 23:23:51 +00001761static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1762 FieldDecl *Top, FieldDecl *Field) {
1763
Chandler Carruth139e9622010-06-30 02:59:29 +00001764 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001765 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001766 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001767 return false;
1768 }
1769
1770 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1771 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1772 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001773 CXXRecordDecl *FieldClassDecl
1774 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001775
1776 // Even though union members never have non-trivial default
1777 // constructions in C++03, we still build member initializers for aggregate
1778 // record types which can be union members, and C++0x allows non-trivial
1779 // default constructors for union members, so we ensure that only one
1780 // member is initialized for these.
1781 if (FieldClassDecl->isUnion()) {
1782 // First check for an explicit initializer for one field.
1783 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1784 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1785 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1786 RecordFieldInitializer(Info, Top, *FA, Init);
1787
1788 // Once we've initialized a field of an anonymous union, the union
1789 // field in the class is also initialized, so exit immediately.
1790 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001791 } else if ((*FA)->isAnonymousStructOrUnion()) {
1792 if (CollectFieldInitializer(Info, Top, *FA))
1793 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001794 }
1795 }
1796
1797 // Fallthrough and construct a default initializer for the union as
1798 // a whole, which can call its default constructor if such a thing exists
1799 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1800 // behavior going forward with C++0x, when anonymous unions there are
1801 // finalized, we should revisit this.
1802 } else {
1803 // For structs, we simply descend through to initialize all members where
1804 // necessary.
1805 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1806 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1807 if (CollectFieldInitializer(Info, Top, *FA))
1808 return true;
1809 }
1810 }
John McCallbc83b3f2010-05-20 23:23:51 +00001811 }
1812
1813 // Don't try to build an implicit initializer if there were semantic
1814 // errors in any of the initializers (and therefore we might be
1815 // missing some that the user actually wrote).
1816 if (Info.AnyErrorsInInits)
1817 return false;
1818
1819 CXXBaseOrMemberInitializer *Init = 0;
1820 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1821 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001822
Chandler Carruth139e9622010-06-30 02:59:29 +00001823 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001824 return false;
1825}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001826
Eli Friedman9cf6b592009-11-09 19:20:36 +00001827bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001828Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001829 CXXBaseOrMemberInitializer **Initializers,
1830 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001831 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001832 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001833 // Just store the initializers as written, they will be checked during
1834 // instantiation.
1835 if (NumInitializers > 0) {
1836 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1837 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1838 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1839 memcpy(baseOrMemberInitializers, Initializers,
1840 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1841 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1842 }
1843
1844 return false;
1845 }
1846
John McCallbc83b3f2010-05-20 23:23:51 +00001847 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001848
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001849 // We need to build the initializer AST according to order of construction
1850 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001851 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001852 if (!ClassDecl)
1853 return true;
1854
Eli Friedman9cf6b592009-11-09 19:20:36 +00001855 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001856
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001857 for (unsigned i = 0; i < NumInitializers; i++) {
1858 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001859
1860 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001861 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001862 else
John McCallbc83b3f2010-05-20 23:23:51 +00001863 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001864 }
1865
Anders Carlsson43c64af2010-04-21 19:52:01 +00001866 // Keep track of the direct virtual bases.
1867 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1868 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1869 E = ClassDecl->bases_end(); I != E; ++I) {
1870 if (I->isVirtual())
1871 DirectVBases.insert(I);
1872 }
1873
Anders Carlssondb0a9652010-04-02 06:26:44 +00001874 // Push virtual bases before others.
1875 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1876 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1877
1878 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001879 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1880 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001881 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001882 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001883 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001884 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001885 VBase, IsInheritedVirtualBase,
1886 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001887 HadError = true;
1888 continue;
1889 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001890
John McCallbc83b3f2010-05-20 23:23:51 +00001891 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001892 }
1893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCallbc83b3f2010-05-20 23:23:51 +00001895 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001896 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1897 E = ClassDecl->bases_end(); Base != E; ++Base) {
1898 // Virtuals are in the virtual base list and already constructed.
1899 if (Base->isVirtual())
1900 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001901
Anders Carlssondb0a9652010-04-02 06:26:44 +00001902 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001903 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1904 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001905 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001906 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001907 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001908 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001909 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001910 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001911 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001912 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001913
John McCallbc83b3f2010-05-20 23:23:51 +00001914 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001915 }
1916 }
Mike Stump11289f42009-09-09 15:08:12 +00001917
John McCallbc83b3f2010-05-20 23:23:51 +00001918 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001919 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001920 E = ClassDecl->field_end(); Field != E; ++Field) {
1921 if ((*Field)->getType()->isIncompleteArrayType()) {
1922 assert(ClassDecl->hasFlexibleArrayMember() &&
1923 "Incomplete array type is not valid");
1924 continue;
1925 }
John McCallbc83b3f2010-05-20 23:23:51 +00001926 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001927 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001928 }
Mike Stump11289f42009-09-09 15:08:12 +00001929
John McCallbc83b3f2010-05-20 23:23:51 +00001930 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001931 if (NumInitializers > 0) {
1932 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1933 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1934 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001935 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001936 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001937 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001938
John McCalla6309952010-03-16 21:39:52 +00001939 // Constructors implicitly reference the base and member
1940 // destructors.
1941 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1942 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001943 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001944
1945 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001946}
1947
Eli Friedman952c15d2009-07-21 19:28:10 +00001948static void *GetKeyForTopLevelField(FieldDecl *Field) {
1949 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001950 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001951 if (RT->getDecl()->isAnonymousStructOrUnion())
1952 return static_cast<void *>(RT->getDecl());
1953 }
1954 return static_cast<void *>(Field);
1955}
1956
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001957static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1958 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001959}
1960
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001961static void *GetKeyForMember(ASTContext &Context,
1962 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001963 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001964 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001965 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001966
Eli Friedman952c15d2009-07-21 19:28:10 +00001967 // For fields injected into the class via declaration of an anonymous union,
1968 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001969 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001970
Anders Carlssona942dcd2010-03-30 15:39:27 +00001971 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1972 // data member of the class. Data member used in the initializer list is
1973 // in AnonUnionMember field.
1974 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1975 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001976
John McCall23eebd92010-04-10 09:28:51 +00001977 // If the field is a member of an anonymous struct or union, our key
1978 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001979 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001980 if (RD->isAnonymousStructOrUnion()) {
1981 while (true) {
1982 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1983 if (Parent->isAnonymousStructOrUnion())
1984 RD = Parent;
1985 else
1986 break;
1987 }
1988
Anders Carlsson83ac3122010-03-30 16:19:37 +00001989 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
Anders Carlssona942dcd2010-03-30 15:39:27 +00001992 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001993}
1994
Anders Carlssone857b292010-04-02 03:37:03 +00001995static void
1996DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001997 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001998 CXXBaseOrMemberInitializer **Inits,
1999 unsigned NumInits) {
2000 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002001 return;
Mike Stump11289f42009-09-09 15:08:12 +00002002
John McCallbb7b6582010-04-10 07:37:23 +00002003 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2004 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002005 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002006
John McCallbb7b6582010-04-10 07:37:23 +00002007 // Build the list of bases and members in the order that they'll
2008 // actually be initialized. The explicit initializers should be in
2009 // this same order but may be missing things.
2010 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002011
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002012 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2013
John McCallbb7b6582010-04-10 07:37:23 +00002014 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002015 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002016 ClassDecl->vbases_begin(),
2017 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002018 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002019
John McCallbb7b6582010-04-10 07:37:23 +00002020 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002021 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002022 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002023 if (Base->isVirtual())
2024 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002025 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002026 }
Mike Stump11289f42009-09-09 15:08:12 +00002027
John McCallbb7b6582010-04-10 07:37:23 +00002028 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002029 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2030 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002031 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002032
John McCallbb7b6582010-04-10 07:37:23 +00002033 unsigned NumIdealInits = IdealInitKeys.size();
2034 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002035
John McCallbb7b6582010-04-10 07:37:23 +00002036 CXXBaseOrMemberInitializer *PrevInit = 0;
2037 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2038 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2039 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2040
2041 // Scan forward to try to find this initializer in the idealized
2042 // initializers list.
2043 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2044 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002045 break;
John McCallbb7b6582010-04-10 07:37:23 +00002046
2047 // If we didn't find this initializer, it must be because we
2048 // scanned past it on a previous iteration. That can only
2049 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002050 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002051 Sema::SemaDiagnosticBuilder D =
2052 SemaRef.Diag(PrevInit->getSourceLocation(),
2053 diag::warn_initializer_out_of_order);
2054
2055 if (PrevInit->isMemberInitializer())
2056 D << 0 << PrevInit->getMember()->getDeclName();
2057 else
2058 D << 1 << PrevInit->getBaseClassInfo()->getType();
2059
2060 if (Init->isMemberInitializer())
2061 D << 0 << Init->getMember()->getDeclName();
2062 else
2063 D << 1 << Init->getBaseClassInfo()->getType();
2064
2065 // Move back to the initializer's location in the ideal list.
2066 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2067 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002068 break;
John McCallbb7b6582010-04-10 07:37:23 +00002069
2070 assert(IdealIndex != NumIdealInits &&
2071 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002072 }
John McCallbb7b6582010-04-10 07:37:23 +00002073
2074 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002075 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002076}
2077
John McCall23eebd92010-04-10 09:28:51 +00002078namespace {
2079bool CheckRedundantInit(Sema &S,
2080 CXXBaseOrMemberInitializer *Init,
2081 CXXBaseOrMemberInitializer *&PrevInit) {
2082 if (!PrevInit) {
2083 PrevInit = Init;
2084 return false;
2085 }
2086
2087 if (FieldDecl *Field = Init->getMember())
2088 S.Diag(Init->getSourceLocation(),
2089 diag::err_multiple_mem_initialization)
2090 << Field->getDeclName()
2091 << Init->getSourceRange();
2092 else {
2093 Type *BaseClass = Init->getBaseClass();
2094 assert(BaseClass && "neither field nor base");
2095 S.Diag(Init->getSourceLocation(),
2096 diag::err_multiple_base_initialization)
2097 << QualType(BaseClass, 0)
2098 << Init->getSourceRange();
2099 }
2100 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2101 << 0 << PrevInit->getSourceRange();
2102
2103 return true;
2104}
2105
2106typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2107typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2108
2109bool CheckRedundantUnionInit(Sema &S,
2110 CXXBaseOrMemberInitializer *Init,
2111 RedundantUnionMap &Unions) {
2112 FieldDecl *Field = Init->getMember();
2113 RecordDecl *Parent = Field->getParent();
2114 if (!Parent->isAnonymousStructOrUnion())
2115 return false;
2116
2117 NamedDecl *Child = Field;
2118 do {
2119 if (Parent->isUnion()) {
2120 UnionEntry &En = Unions[Parent];
2121 if (En.first && En.first != Child) {
2122 S.Diag(Init->getSourceLocation(),
2123 diag::err_multiple_mem_union_initialization)
2124 << Field->getDeclName()
2125 << Init->getSourceRange();
2126 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2127 << 0 << En.second->getSourceRange();
2128 return true;
2129 } else if (!En.first) {
2130 En.first = Child;
2131 En.second = Init;
2132 }
2133 }
2134
2135 Child = Parent;
2136 Parent = cast<RecordDecl>(Parent->getDeclContext());
2137 } while (Parent->isAnonymousStructOrUnion());
2138
2139 return false;
2140}
2141}
2142
Anders Carlssone857b292010-04-02 03:37:03 +00002143/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002144void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002145 SourceLocation ColonLoc,
2146 MemInitTy **meminits, unsigned NumMemInits,
2147 bool AnyErrors) {
2148 if (!ConstructorDecl)
2149 return;
2150
2151 AdjustDeclIfTemplate(ConstructorDecl);
2152
2153 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002154 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002155
2156 if (!Constructor) {
2157 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2158 return;
2159 }
2160
2161 CXXBaseOrMemberInitializer **MemInits =
2162 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002163
2164 // Mapping for the duplicate initializers check.
2165 // For member initializers, this is keyed with a FieldDecl*.
2166 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002167 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002168
2169 // Mapping for the inconsistent anonymous-union initializers check.
2170 RedundantUnionMap MemberUnions;
2171
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002172 bool HadError = false;
2173 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002174 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002175
Abramo Bagnara341d7832010-05-26 18:09:23 +00002176 // Set the source order index.
2177 Init->setSourceOrder(i);
2178
John McCall23eebd92010-04-10 09:28:51 +00002179 if (Init->isMemberInitializer()) {
2180 FieldDecl *Field = Init->getMember();
2181 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2182 CheckRedundantUnionInit(*this, Init, MemberUnions))
2183 HadError = true;
2184 } else {
2185 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2186 if (CheckRedundantInit(*this, Init, Members[Key]))
2187 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002188 }
Anders Carlssone857b292010-04-02 03:37:03 +00002189 }
2190
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002191 if (HadError)
2192 return;
2193
Anders Carlssone857b292010-04-02 03:37:03 +00002194 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002195
2196 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002197}
2198
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002199void
John McCalla6309952010-03-16 21:39:52 +00002200Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2201 CXXRecordDecl *ClassDecl) {
2202 // Ignore dependent contexts.
2203 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002204 return;
John McCall1064d7e2010-03-16 05:22:47 +00002205
2206 // FIXME: all the access-control diagnostics are positioned on the
2207 // field/base declaration. That's probably good; that said, the
2208 // user might reasonably want to know why the destructor is being
2209 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002210
Anders Carlssondee9a302009-11-17 04:44:12 +00002211 // Non-static data members.
2212 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2213 E = ClassDecl->field_end(); I != E; ++I) {
2214 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002215 if (Field->isInvalidDecl())
2216 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002217 QualType FieldType = Context.getBaseElementType(Field->getType());
2218
2219 const RecordType* RT = FieldType->getAs<RecordType>();
2220 if (!RT)
2221 continue;
2222
2223 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2224 if (FieldClassDecl->hasTrivialDestructor())
2225 continue;
2226
Douglas Gregore71edda2010-07-01 22:47:18 +00002227 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002228 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002229 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002230 << Field->getDeclName()
2231 << FieldType);
2232
John McCalla6309952010-03-16 21:39:52 +00002233 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002234 }
2235
John McCall1064d7e2010-03-16 05:22:47 +00002236 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2237
Anders Carlssondee9a302009-11-17 04:44:12 +00002238 // Bases.
2239 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2240 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002241 // Bases are always records in a well-formed non-dependent class.
2242 const RecordType *RT = Base->getType()->getAs<RecordType>();
2243
2244 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002245 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002246 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002247
2248 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002249 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002250 if (BaseClassDecl->hasTrivialDestructor())
2251 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002252
Douglas Gregore71edda2010-07-01 22:47:18 +00002253 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002254
2255 // FIXME: caret should be on the start of the class name
2256 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002257 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002258 << Base->getType()
2259 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002260
John McCalla6309952010-03-16 21:39:52 +00002261 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002262 }
2263
2264 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002265 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2266 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002267
2268 // Bases are always records in a well-formed non-dependent class.
2269 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2270
2271 // Ignore direct virtual bases.
2272 if (DirectVirtualBases.count(RT))
2273 continue;
2274
Anders Carlssondee9a302009-11-17 04:44:12 +00002275 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002276 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002277 if (BaseClassDecl->hasTrivialDestructor())
2278 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002279
Douglas Gregore71edda2010-07-01 22:47:18 +00002280 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002281 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002282 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002283 << VBase->getType());
2284
John McCalla6309952010-03-16 21:39:52 +00002285 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002286 }
2287}
2288
John McCall48871652010-08-21 09:40:31 +00002289void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002290 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002291 return;
Mike Stump11289f42009-09-09 15:08:12 +00002292
Mike Stump11289f42009-09-09 15:08:12 +00002293 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002294 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002295 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002296}
2297
Mike Stump11289f42009-09-09 15:08:12 +00002298bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002299 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002300 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002301 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002302 else
John McCall02db245d2010-08-18 09:41:07 +00002303 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002304}
2305
Anders Carlssoneabf7702009-08-27 00:13:57 +00002306bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002307 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002308 if (!getLangOptions().CPlusPlus)
2309 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002310
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002311 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002312 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002313
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002314 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002315 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002316 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002317 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002318
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002319 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002320 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002321 }
Mike Stump11289f42009-09-09 15:08:12 +00002322
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002323 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002324 if (!RT)
2325 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002326
John McCall67da35c2010-02-04 22:26:26 +00002327 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002328
John McCall02db245d2010-08-18 09:41:07 +00002329 // We can't answer whether something is abstract until it has a
2330 // definition. If it's currently being defined, we'll walk back
2331 // over all the declarations when we have a full definition.
2332 const CXXRecordDecl *Def = RD->getDefinition();
2333 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002334 return false;
2335
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002336 if (!RD->isAbstract())
2337 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002338
Anders Carlssoneabf7702009-08-27 00:13:57 +00002339 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002340 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002341
John McCall02db245d2010-08-18 09:41:07 +00002342 return true;
2343}
2344
2345void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2346 // Check if we've already emitted the list of pure virtual functions
2347 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002348 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002349 return;
Mike Stump11289f42009-09-09 15:08:12 +00002350
Douglas Gregor4165bd62010-03-23 23:47:56 +00002351 CXXFinalOverriderMap FinalOverriders;
2352 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002353
Anders Carlssona2f74f32010-06-03 01:00:02 +00002354 // Keep a set of seen pure methods so we won't diagnose the same method
2355 // more than once.
2356 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2357
Douglas Gregor4165bd62010-03-23 23:47:56 +00002358 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2359 MEnd = FinalOverriders.end();
2360 M != MEnd;
2361 ++M) {
2362 for (OverridingMethods::iterator SO = M->second.begin(),
2363 SOEnd = M->second.end();
2364 SO != SOEnd; ++SO) {
2365 // C++ [class.abstract]p4:
2366 // A class is abstract if it contains or inherits at least one
2367 // pure virtual function for which the final overrider is pure
2368 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002369
Douglas Gregor4165bd62010-03-23 23:47:56 +00002370 //
2371 if (SO->second.size() != 1)
2372 continue;
2373
2374 if (!SO->second.front().Method->isPure())
2375 continue;
2376
Anders Carlssona2f74f32010-06-03 01:00:02 +00002377 if (!SeenPureMethods.insert(SO->second.front().Method))
2378 continue;
2379
Douglas Gregor4165bd62010-03-23 23:47:56 +00002380 Diag(SO->second.front().Method->getLocation(),
2381 diag::note_pure_virtual_function)
2382 << SO->second.front().Method->getDeclName();
2383 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002384 }
2385
2386 if (!PureVirtualClassDiagSet)
2387 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2388 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002389}
2390
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002391namespace {
John McCall02db245d2010-08-18 09:41:07 +00002392struct AbstractUsageInfo {
2393 Sema &S;
2394 CXXRecordDecl *Record;
2395 CanQualType AbstractType;
2396 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002397
John McCall02db245d2010-08-18 09:41:07 +00002398 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2399 : S(S), Record(Record),
2400 AbstractType(S.Context.getCanonicalType(
2401 S.Context.getTypeDeclType(Record))),
2402 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002403
John McCall02db245d2010-08-18 09:41:07 +00002404 void DiagnoseAbstractType() {
2405 if (Invalid) return;
2406 S.DiagnoseAbstractType(Record);
2407 Invalid = true;
2408 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002409
John McCall02db245d2010-08-18 09:41:07 +00002410 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2411};
2412
2413struct CheckAbstractUsage {
2414 AbstractUsageInfo &Info;
2415 const NamedDecl *Ctx;
2416
2417 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2418 : Info(Info), Ctx(Ctx) {}
2419
2420 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2421 switch (TL.getTypeLocClass()) {
2422#define ABSTRACT_TYPELOC(CLASS, PARENT)
2423#define TYPELOC(CLASS, PARENT) \
2424 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2425#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002426 }
John McCall02db245d2010-08-18 09:41:07 +00002427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
John McCall02db245d2010-08-18 09:41:07 +00002429 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2430 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2431 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2432 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2433 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002434 }
John McCall02db245d2010-08-18 09:41:07 +00002435 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002436
John McCall02db245d2010-08-18 09:41:07 +00002437 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2438 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2439 }
Mike Stump11289f42009-09-09 15:08:12 +00002440
John McCall02db245d2010-08-18 09:41:07 +00002441 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2442 // Visit the type parameters from a permissive context.
2443 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2444 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2445 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2446 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2447 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2448 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002449 }
John McCall02db245d2010-08-18 09:41:07 +00002450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
John McCall02db245d2010-08-18 09:41:07 +00002452 // Visit pointee types from a permissive context.
2453#define CheckPolymorphic(Type) \
2454 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2455 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2456 }
2457 CheckPolymorphic(PointerTypeLoc)
2458 CheckPolymorphic(ReferenceTypeLoc)
2459 CheckPolymorphic(MemberPointerTypeLoc)
2460 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002461
John McCall02db245d2010-08-18 09:41:07 +00002462 /// Handle all the types we haven't given a more specific
2463 /// implementation for above.
2464 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2465 // Every other kind of type that we haven't called out already
2466 // that has an inner type is either (1) sugar or (2) contains that
2467 // inner type in some way as a subobject.
2468 if (TypeLoc Next = TL.getNextTypeLoc())
2469 return Visit(Next, Sel);
2470
2471 // If there's no inner type and we're in a permissive context,
2472 // don't diagnose.
2473 if (Sel == Sema::AbstractNone) return;
2474
2475 // Check whether the type matches the abstract type.
2476 QualType T = TL.getType();
2477 if (T->isArrayType()) {
2478 Sel = Sema::AbstractArrayType;
2479 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002480 }
John McCall02db245d2010-08-18 09:41:07 +00002481 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2482 if (CT != Info.AbstractType) return;
2483
2484 // It matched; do some magic.
2485 if (Sel == Sema::AbstractArrayType) {
2486 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2487 << T << TL.getSourceRange();
2488 } else {
2489 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2490 << Sel << T << TL.getSourceRange();
2491 }
2492 Info.DiagnoseAbstractType();
2493 }
2494};
2495
2496void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2497 Sema::AbstractDiagSelID Sel) {
2498 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2499}
2500
2501}
2502
2503/// Check for invalid uses of an abstract type in a method declaration.
2504static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2505 CXXMethodDecl *MD) {
2506 // No need to do the check on definitions, which require that
2507 // the return/param types be complete.
2508 if (MD->isThisDeclarationADefinition())
2509 return;
2510
2511 // For safety's sake, just ignore it if we don't have type source
2512 // information. This should never happen for non-implicit methods,
2513 // but...
2514 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2515 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2516}
2517
2518/// Check for invalid uses of an abstract type within a class definition.
2519static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2520 CXXRecordDecl *RD) {
2521 for (CXXRecordDecl::decl_iterator
2522 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2523 Decl *D = *I;
2524 if (D->isImplicit()) continue;
2525
2526 // Methods and method templates.
2527 if (isa<CXXMethodDecl>(D)) {
2528 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2529 } else if (isa<FunctionTemplateDecl>(D)) {
2530 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2531 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2532
2533 // Fields and static variables.
2534 } else if (isa<FieldDecl>(D)) {
2535 FieldDecl *FD = cast<FieldDecl>(D);
2536 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2537 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2538 } else if (isa<VarDecl>(D)) {
2539 VarDecl *VD = cast<VarDecl>(D);
2540 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2541 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2542
2543 // Nested classes and class templates.
2544 } else if (isa<CXXRecordDecl>(D)) {
2545 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2546 } else if (isa<ClassTemplateDecl>(D)) {
2547 CheckAbstractClassUsage(Info,
2548 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2549 }
2550 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002551}
2552
Douglas Gregorc99f1552009-12-03 18:33:45 +00002553/// \brief Perform semantic checks on a class definition that has been
2554/// completing, introducing implicitly-declared members, checking for
2555/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002556void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002557 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002558 return;
2559
John McCall02db245d2010-08-18 09:41:07 +00002560 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2561 AbstractUsageInfo Info(*this, Record);
2562 CheckAbstractClassUsage(Info, Record);
2563 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002564
2565 // If this is not an aggregate type and has no user-declared constructor,
2566 // complain about any non-static data members of reference or const scalar
2567 // type, since they will never get initializers.
2568 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2569 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2570 bool Complained = false;
2571 for (RecordDecl::field_iterator F = Record->field_begin(),
2572 FEnd = Record->field_end();
2573 F != FEnd; ++F) {
2574 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002575 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002576 if (!Complained) {
2577 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2578 << Record->getTagKind() << Record;
2579 Complained = true;
2580 }
2581
2582 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2583 << F->getType()->isReferenceType()
2584 << F->getDeclName();
2585 }
2586 }
2587 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002588
2589 if (Record->isDynamicClass())
2590 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002591
2592 if (Record->getIdentifier()) {
2593 // C++ [class.mem]p13:
2594 // If T is the name of a class, then each of the following shall have a
2595 // name different from T:
2596 // - every member of every anonymous union that is a member of class T.
2597 //
2598 // C++ [class.mem]p14:
2599 // In addition, if class T has a user-declared constructor (12.1), every
2600 // non-static data member of class T shall have a name different from T.
2601 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
2602 R.first != R.second; ++R.first)
2603 if (FieldDecl *Field = dyn_cast<FieldDecl>(*R.first)) {
2604 if (Record->hasUserDeclaredConstructor() ||
2605 !Field->getDeclContext()->Equals(Record)) {
2606 Diag(Field->getLocation(), diag::err_member_name_of_class)
2607 << Field->getDeclName();
2608 break;
2609 }
2610 }
2611 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002612}
2613
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002614void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002615 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002616 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002617 SourceLocation RBrac,
2618 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002619 if (!TagDecl)
2620 return;
Mike Stump11289f42009-09-09 15:08:12 +00002621
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002622 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002623
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002624 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002625 // strict aliasing violation!
2626 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002627 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002628
Douglas Gregor0be31a22010-07-02 17:43:08 +00002629 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002630 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002631}
2632
Douglas Gregor95755162010-07-01 05:10:53 +00002633namespace {
2634 /// \brief Helper class that collects exception specifications for
2635 /// implicitly-declared special member functions.
2636 class ImplicitExceptionSpecification {
2637 ASTContext &Context;
2638 bool AllowsAllExceptions;
2639 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2640 llvm::SmallVector<QualType, 4> Exceptions;
2641
2642 public:
2643 explicit ImplicitExceptionSpecification(ASTContext &Context)
2644 : Context(Context), AllowsAllExceptions(false) { }
2645
2646 /// \brief Whether the special member function should have any
2647 /// exception specification at all.
2648 bool hasExceptionSpecification() const {
2649 return !AllowsAllExceptions;
2650 }
2651
2652 /// \brief Whether the special member function should have a
2653 /// throw(...) exception specification (a Microsoft extension).
2654 bool hasAnyExceptionSpecification() const {
2655 return false;
2656 }
2657
2658 /// \brief The number of exceptions in the exception specification.
2659 unsigned size() const { return Exceptions.size(); }
2660
2661 /// \brief The set of exceptions in the exception specification.
2662 const QualType *data() const { return Exceptions.data(); }
2663
2664 /// \brief Note that
2665 void CalledDecl(CXXMethodDecl *Method) {
2666 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002667 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002668 return;
2669
2670 const FunctionProtoType *Proto
2671 = Method->getType()->getAs<FunctionProtoType>();
2672
2673 // If this function can throw any exceptions, make a note of that.
2674 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2675 AllowsAllExceptions = true;
2676 ExceptionsSeen.clear();
2677 Exceptions.clear();
2678 return;
2679 }
2680
2681 // Record the exceptions in this function's exception specification.
2682 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2683 EEnd = Proto->exception_end();
2684 E != EEnd; ++E)
2685 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2686 Exceptions.push_back(*E);
2687 }
2688 };
2689}
2690
2691
Douglas Gregor05379422008-11-03 17:51:48 +00002692/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2693/// special functions, such as the default constructor, copy
2694/// constructor, or destructor, to the given C++ class (C++
2695/// [special]p1). This routine can only be executed just before the
2696/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002697void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002698 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002699 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002700
Douglas Gregor54be3392010-07-01 17:57:27 +00002701 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002702 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002703
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002704 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2705 ++ASTContext::NumImplicitCopyAssignmentOperators;
2706
2707 // If we have a dynamic class, then the copy assignment operator may be
2708 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2709 // it shows up in the right place in the vtable and that we diagnose
2710 // problems with the implicit exception specification.
2711 if (ClassDecl->isDynamicClass())
2712 DeclareImplicitCopyAssignment(ClassDecl);
2713 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002714
Douglas Gregor7454c562010-07-02 20:37:36 +00002715 if (!ClassDecl->hasUserDeclaredDestructor()) {
2716 ++ASTContext::NumImplicitDestructors;
2717
2718 // If we have a dynamic class, then the destructor may be virtual, so we
2719 // have to declare the destructor immediately. This ensures that, e.g., it
2720 // shows up in the right place in the vtable and that we diagnose problems
2721 // with the implicit exception specification.
2722 if (ClassDecl->isDynamicClass())
2723 DeclareImplicitDestructor(ClassDecl);
2724 }
Douglas Gregor05379422008-11-03 17:51:48 +00002725}
2726
John McCall48871652010-08-21 09:40:31 +00002727void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002728 if (!D)
2729 return;
2730
2731 TemplateParameterList *Params = 0;
2732 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2733 Params = Template->getTemplateParameters();
2734 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2735 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2736 Params = PartialSpec->getTemplateParameters();
2737 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002738 return;
2739
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002740 for (TemplateParameterList::iterator Param = Params->begin(),
2741 ParamEnd = Params->end();
2742 Param != ParamEnd; ++Param) {
2743 NamedDecl *Named = cast<NamedDecl>(*Param);
2744 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002745 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002746 IdResolver.AddDecl(Named);
2747 }
2748 }
2749}
2750
John McCall48871652010-08-21 09:40:31 +00002751void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002752 if (!RecordD) return;
2753 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002754 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002755 PushDeclContext(S, Record);
2756}
2757
John McCall48871652010-08-21 09:40:31 +00002758void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002759 if (!RecordD) return;
2760 PopDeclContext();
2761}
2762
Douglas Gregor4d87df52008-12-16 21:30:33 +00002763/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2764/// parsing a top-level (non-nested) C++ class, and we are now
2765/// parsing those parts of the given Method declaration that could
2766/// not be parsed earlier (C++ [class.mem]p2), such as default
2767/// arguments. This action should enter the scope of the given
2768/// Method declaration as if we had just parsed the qualified method
2769/// name. However, it should not bring the parameters into scope;
2770/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002771void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002772}
2773
2774/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2775/// C++ method declaration. We're (re-)introducing the given
2776/// function parameter into scope for use in parsing later parts of
2777/// the method declaration. For example, we could see an
2778/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002779void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002780 if (!ParamD)
2781 return;
Mike Stump11289f42009-09-09 15:08:12 +00002782
John McCall48871652010-08-21 09:40:31 +00002783 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002784
2785 // If this parameter has an unparsed default argument, clear it out
2786 // to make way for the parsed default argument.
2787 if (Param->hasUnparsedDefaultArg())
2788 Param->setDefaultArg(0);
2789
John McCall48871652010-08-21 09:40:31 +00002790 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002791 if (Param->getDeclName())
2792 IdResolver.AddDecl(Param);
2793}
2794
2795/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2796/// processing the delayed method declaration for Method. The method
2797/// declaration is now considered finished. There may be a separate
2798/// ActOnStartOfFunctionDef action later (not necessarily
2799/// immediately!) for this method, if it was also defined inside the
2800/// class body.
John McCall48871652010-08-21 09:40:31 +00002801void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002802 if (!MethodD)
2803 return;
Mike Stump11289f42009-09-09 15:08:12 +00002804
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002805 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002806
John McCall48871652010-08-21 09:40:31 +00002807 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002808
2809 // Now that we have our default arguments, check the constructor
2810 // again. It could produce additional diagnostics or affect whether
2811 // the class has implicitly-declared destructors, among other
2812 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002813 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2814 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002815
2816 // Check the default arguments, which we may have added.
2817 if (!Method->isInvalidDecl())
2818 CheckCXXDefaultArguments(Method);
2819}
2820
Douglas Gregor831c93f2008-11-05 20:51:48 +00002821/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002822/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002823/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002824/// emit diagnostics and set the invalid bit to true. In any case, the type
2825/// will be updated to reflect a well-formed type for the constructor and
2826/// returned.
2827QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002828 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002829 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002830
2831 // C++ [class.ctor]p3:
2832 // A constructor shall not be virtual (10.3) or static (9.4). A
2833 // constructor can be invoked for a const, volatile or const
2834 // volatile object. A constructor shall not be declared const,
2835 // volatile, or const volatile (9.3.2).
2836 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002837 if (!D.isInvalidType())
2838 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2839 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2840 << SourceRange(D.getIdentifierLoc());
2841 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002842 }
John McCall8e7d6562010-08-26 03:08:43 +00002843 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002844 if (!D.isInvalidType())
2845 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2846 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2847 << SourceRange(D.getIdentifierLoc());
2848 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002849 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002850 }
Mike Stump11289f42009-09-09 15:08:12 +00002851
Chris Lattner38378bf2009-04-25 08:28:21 +00002852 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2853 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002854 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002855 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2856 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002857 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002858 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2859 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002860 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002861 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2862 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002863 }
Mike Stump11289f42009-09-09 15:08:12 +00002864
Douglas Gregor831c93f2008-11-05 20:51:48 +00002865 // Rebuild the function type "R" without any type qualifiers (in
2866 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002867 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002868 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002869 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2870 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002871 Proto->isVariadic(), 0,
2872 Proto->hasExceptionSpec(),
2873 Proto->hasAnyExceptionSpec(),
2874 Proto->getNumExceptions(),
2875 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002876 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002877}
2878
Douglas Gregor4d87df52008-12-16 21:30:33 +00002879/// CheckConstructor - Checks a fully-formed constructor for
2880/// well-formedness, issuing any diagnostics required. Returns true if
2881/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002882void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002883 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002884 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2885 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002886 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002887
2888 // C++ [class.copy]p3:
2889 // A declaration of a constructor for a class X is ill-formed if
2890 // its first parameter is of type (optionally cv-qualified) X and
2891 // either there are no other parameters or else all other
2892 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002893 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002894 ((Constructor->getNumParams() == 1) ||
2895 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002896 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2897 Constructor->getTemplateSpecializationKind()
2898 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002899 QualType ParamType = Constructor->getParamDecl(0)->getType();
2900 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2901 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002902 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002903 const char *ConstRef
2904 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2905 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002906 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002907 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002908
2909 // FIXME: Rather that making the constructor invalid, we should endeavor
2910 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002911 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002912 }
2913 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002914}
2915
John McCalldeb646e2010-08-04 01:04:25 +00002916/// CheckDestructor - Checks a fully-formed destructor definition for
2917/// well-formedness, issuing any diagnostics required. Returns true
2918/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002919bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002920 CXXRecordDecl *RD = Destructor->getParent();
2921
2922 if (Destructor->isVirtual()) {
2923 SourceLocation Loc;
2924
2925 if (!Destructor->isImplicit())
2926 Loc = Destructor->getLocation();
2927 else
2928 Loc = RD->getLocation();
2929
2930 // If we have a virtual destructor, look up the deallocation function
2931 FunctionDecl *OperatorDelete = 0;
2932 DeclarationName Name =
2933 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002934 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002935 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002936
2937 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002938
2939 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002940 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002941
2942 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002943}
2944
Mike Stump11289f42009-09-09 15:08:12 +00002945static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002946FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2947 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2948 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002949 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002950}
2951
Douglas Gregor831c93f2008-11-05 20:51:48 +00002952/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2953/// the well-formednes of the destructor declarator @p D with type @p
2954/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002955/// emit diagnostics and set the declarator to invalid. Even if this happens,
2956/// will be updated to reflect a well-formed type for the destructor and
2957/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002958QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002959 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002960 // C++ [class.dtor]p1:
2961 // [...] A typedef-name that names a class is a class-name
2962 // (7.1.3); however, a typedef-name that names a class shall not
2963 // be used as the identifier in the declarator for a destructor
2964 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002965 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002966 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002967 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002968 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002969
2970 // C++ [class.dtor]p2:
2971 // A destructor is used to destroy objects of its class type. A
2972 // destructor takes no parameters, and no return type can be
2973 // specified for it (not even void). The address of a destructor
2974 // shall not be taken. A destructor shall not be static. A
2975 // destructor can be invoked for a const, volatile or const
2976 // volatile object. A destructor shall not be declared const,
2977 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002978 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002979 if (!D.isInvalidType())
2980 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2981 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002982 << SourceRange(D.getIdentifierLoc())
2983 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2984
John McCall8e7d6562010-08-26 03:08:43 +00002985 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002986 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002987 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002988 // Destructors don't have return types, but the parser will
2989 // happily parse something like:
2990 //
2991 // class X {
2992 // float ~X();
2993 // };
2994 //
2995 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002996 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2997 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2998 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002999 }
Mike Stump11289f42009-09-09 15:08:12 +00003000
Chris Lattner38378bf2009-04-25 08:28:21 +00003001 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3002 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003003 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003004 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3005 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003006 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003007 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3008 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003009 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003010 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3011 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003012 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003013 }
3014
3015 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003016 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003017 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3018
3019 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003020 FTI.freeArgs();
3021 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003022 }
3023
Mike Stump11289f42009-09-09 15:08:12 +00003024 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003025 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003026 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003027 D.setInvalidType();
3028 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003029
3030 // Rebuild the function type "R" without any type qualifiers or
3031 // parameters (in case any of the errors above fired) and with
3032 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003033 // types.
3034 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3035 if (!Proto)
3036 return QualType();
3037
Douglas Gregor36c569f2010-02-21 22:15:06 +00003038 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00003039 Proto->hasExceptionSpec(),
3040 Proto->hasAnyExceptionSpec(),
3041 Proto->getNumExceptions(),
3042 Proto->exception_begin(),
3043 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003044}
3045
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003046/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3047/// well-formednes of the conversion function declarator @p D with
3048/// type @p R. If there are any errors in the declarator, this routine
3049/// will emit diagnostics and return true. Otherwise, it will return
3050/// false. Either way, the type @p R will be updated to reflect a
3051/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003052void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003053 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003054 // C++ [class.conv.fct]p1:
3055 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003056 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003057 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003058 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003059 if (!D.isInvalidType())
3060 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3061 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3062 << SourceRange(D.getIdentifierLoc());
3063 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003064 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003065 }
John McCall212fa2e2010-04-13 00:04:31 +00003066
3067 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3068
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003069 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003070 // Conversion functions don't have return types, but the parser will
3071 // happily parse something like:
3072 //
3073 // class X {
3074 // float operator bool();
3075 // };
3076 //
3077 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003078 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3079 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3080 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003081 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003082 }
3083
John McCall212fa2e2010-04-13 00:04:31 +00003084 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3085
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003086 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003087 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003088 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3089
3090 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003091 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003092 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003093 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003094 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003095 D.setInvalidType();
3096 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003097
John McCall212fa2e2010-04-13 00:04:31 +00003098 // Diagnose "&operator bool()" and other such nonsense. This
3099 // is actually a gcc extension which we don't support.
3100 if (Proto->getResultType() != ConvType) {
3101 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3102 << Proto->getResultType();
3103 D.setInvalidType();
3104 ConvType = Proto->getResultType();
3105 }
3106
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003107 // C++ [class.conv.fct]p4:
3108 // The conversion-type-id shall not represent a function type nor
3109 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003110 if (ConvType->isArrayType()) {
3111 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3112 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003113 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003114 } else if (ConvType->isFunctionType()) {
3115 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3116 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003117 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003118 }
3119
3120 // Rebuild the function type "R" without any parameters (in case any
3121 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003122 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003123 if (D.isInvalidType()) {
3124 R = Context.getFunctionType(ConvType, 0, 0, false,
3125 Proto->getTypeQuals(),
3126 Proto->hasExceptionSpec(),
3127 Proto->hasAnyExceptionSpec(),
3128 Proto->getNumExceptions(),
3129 Proto->exception_begin(),
3130 Proto->getExtInfo());
3131 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003132
Douglas Gregor5fb53972009-01-14 15:45:31 +00003133 // C++0x explicit conversion operators.
3134 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003135 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003136 diag::warn_explicit_conversion_functions)
3137 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003138}
3139
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003140/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3141/// the declaration of the given C++ conversion function. This routine
3142/// is responsible for recording the conversion function in the C++
3143/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003144Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003145 assert(Conversion && "Expected to receive a conversion function declaration");
3146
Douglas Gregor4287b372008-12-12 08:25:50 +00003147 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003148
3149 // Make sure we aren't redeclaring the conversion function.
3150 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003151
3152 // C++ [class.conv.fct]p1:
3153 // [...] A conversion function is never used to convert a
3154 // (possibly cv-qualified) object to the (possibly cv-qualified)
3155 // same object type (or a reference to it), to a (possibly
3156 // cv-qualified) base class of that type (or a reference to it),
3157 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003158 // FIXME: Suppress this warning if the conversion function ends up being a
3159 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003160 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003161 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003162 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003163 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003164 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3165 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003166 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003167 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003168 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3169 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003170 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003171 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003172 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003173 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003174 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003175 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003176 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003177 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003178 }
3179
Douglas Gregor457104e2010-09-29 04:25:11 +00003180 if (FunctionTemplateDecl *ConversionTemplate
3181 = Conversion->getDescribedFunctionTemplate())
3182 return ConversionTemplate;
3183
John McCall48871652010-08-21 09:40:31 +00003184 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003185}
3186
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003187//===----------------------------------------------------------------------===//
3188// Namespace Handling
3189//===----------------------------------------------------------------------===//
3190
John McCallb1be5232010-08-26 09:15:37 +00003191
3192
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003193/// ActOnStartNamespaceDef - This is called at the start of a namespace
3194/// definition.
John McCall48871652010-08-21 09:40:31 +00003195Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003196 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003197 SourceLocation IdentLoc,
3198 IdentifierInfo *II,
3199 SourceLocation LBrace,
3200 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003201 // anonymous namespace starts at its left brace
3202 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3203 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003204 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003205 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003206
3207 Scope *DeclRegionScope = NamespcScope->getParent();
3208
Anders Carlssona7bcade2010-02-07 01:09:23 +00003209 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3210
Eli Friedman570024a2010-08-05 06:57:20 +00003211 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallb1be5232010-08-26 09:15:37 +00003212 PushVisibilityAttr(attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003213
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003214 if (II) {
3215 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003216 // The identifier in an original-namespace-definition shall not
3217 // have been previously defined in the declarative region in
3218 // which the original-namespace-definition appears. The
3219 // identifier in an original-namespace-definition is the name of
3220 // the namespace. Subsequently in that declarative region, it is
3221 // treated as an original-namespace-name.
3222 //
3223 // Since namespace names are unique in their scope, and we don't
3224 // look through using directives, just
3225 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3226 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003227
Douglas Gregor91f84212008-12-11 16:49:14 +00003228 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3229 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003230 if (Namespc->isInline() != OrigNS->isInline()) {
3231 // inline-ness must match
3232 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3233 << Namespc->isInline();
3234 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3235 Namespc->setInvalidDecl();
3236 // Recover by ignoring the new namespace's inline status.
3237 Namespc->setInline(OrigNS->isInline());
3238 }
3239
Douglas Gregor91f84212008-12-11 16:49:14 +00003240 // Attach this namespace decl to the chain of extended namespace
3241 // definitions.
3242 OrigNS->setNextNamespace(Namespc);
3243 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003244
Mike Stump11289f42009-09-09 15:08:12 +00003245 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003246 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003247 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003248 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003249 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003250 } else if (PrevDecl) {
3251 // This is an invalid name redefinition.
3252 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3253 << Namespc->getDeclName();
3254 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3255 Namespc->setInvalidDecl();
3256 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003257 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003258 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003259 // This is the first "real" definition of the namespace "std", so update
3260 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003261 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003262 // We had already defined a dummy namespace "std". Link this new
3263 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003264 StdNS->setNextNamespace(Namespc);
3265 StdNS->setLocation(IdentLoc);
3266 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003267 }
3268
3269 // Make our StdNamespace cache point at the first real definition of the
3270 // "std" namespace.
3271 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003272 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003273
3274 PushOnScopeChains(Namespc, DeclRegionScope);
3275 } else {
John McCall4fa53422009-10-01 00:25:31 +00003276 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003277 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003278
3279 // Link the anonymous namespace into its parent.
3280 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003281 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003282 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3283 PrevDecl = TU->getAnonymousNamespace();
3284 TU->setAnonymousNamespace(Namespc);
3285 } else {
3286 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3287 PrevDecl = ND->getAnonymousNamespace();
3288 ND->setAnonymousNamespace(Namespc);
3289 }
3290
3291 // Link the anonymous namespace with its previous declaration.
3292 if (PrevDecl) {
3293 assert(PrevDecl->isAnonymousNamespace());
3294 assert(!PrevDecl->getNextNamespace());
3295 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3296 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003297
3298 if (Namespc->isInline() != PrevDecl->isInline()) {
3299 // inline-ness must match
3300 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3301 << Namespc->isInline();
3302 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3303 Namespc->setInvalidDecl();
3304 // Recover by ignoring the new namespace's inline status.
3305 Namespc->setInline(PrevDecl->isInline());
3306 }
John McCall0db42252009-12-16 02:06:49 +00003307 }
John McCall4fa53422009-10-01 00:25:31 +00003308
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003309 CurContext->addDecl(Namespc);
3310
John McCall4fa53422009-10-01 00:25:31 +00003311 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3312 // behaves as if it were replaced by
3313 // namespace unique { /* empty body */ }
3314 // using namespace unique;
3315 // namespace unique { namespace-body }
3316 // where all occurrences of 'unique' in a translation unit are
3317 // replaced by the same identifier and this identifier differs
3318 // from all other identifiers in the entire program.
3319
3320 // We just create the namespace with an empty name and then add an
3321 // implicit using declaration, just like the standard suggests.
3322 //
3323 // CodeGen enforces the "universally unique" aspect by giving all
3324 // declarations semantically contained within an anonymous
3325 // namespace internal linkage.
3326
John McCall0db42252009-12-16 02:06:49 +00003327 if (!PrevDecl) {
3328 UsingDirectiveDecl* UD
3329 = UsingDirectiveDecl::Create(Context, CurContext,
3330 /* 'using' */ LBrace,
3331 /* 'namespace' */ SourceLocation(),
3332 /* qualifier */ SourceRange(),
3333 /* NNS */ NULL,
3334 /* identifier */ SourceLocation(),
3335 Namespc,
3336 /* Ancestor */ CurContext);
3337 UD->setImplicit();
3338 CurContext->addDecl(UD);
3339 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003340 }
3341
3342 // Although we could have an invalid decl (i.e. the namespace name is a
3343 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003344 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3345 // for the namespace has the declarations that showed up in that particular
3346 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003347 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003348 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003349}
3350
Sebastian Redla6602e92009-11-23 15:34:23 +00003351/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3352/// is a namespace alias, returns the namespace it points to.
3353static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3354 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3355 return AD->getNamespace();
3356 return dyn_cast_or_null<NamespaceDecl>(D);
3357}
3358
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003359/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3360/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003361void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003362 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3363 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3364 Namespc->setRBracLoc(RBrace);
3365 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003366 if (Namespc->hasAttr<VisibilityAttr>())
3367 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003368}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003369
John McCall28a0cf72010-08-25 07:42:41 +00003370CXXRecordDecl *Sema::getStdBadAlloc() const {
3371 return cast_or_null<CXXRecordDecl>(
3372 StdBadAlloc.get(Context.getExternalSource()));
3373}
3374
3375NamespaceDecl *Sema::getStdNamespace() const {
3376 return cast_or_null<NamespaceDecl>(
3377 StdNamespace.get(Context.getExternalSource()));
3378}
3379
Douglas Gregorcdf87022010-06-29 17:53:46 +00003380/// \brief Retrieve the special "std" namespace, which may require us to
3381/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003382NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003383 if (!StdNamespace) {
3384 // The "std" namespace has not yet been defined, so build one implicitly.
3385 StdNamespace = NamespaceDecl::Create(Context,
3386 Context.getTranslationUnitDecl(),
3387 SourceLocation(),
3388 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003389 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003390 }
3391
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003392 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003393}
3394
John McCall48871652010-08-21 09:40:31 +00003395Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003396 SourceLocation UsingLoc,
3397 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003398 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003399 SourceLocation IdentLoc,
3400 IdentifierInfo *NamespcName,
3401 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003402 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3403 assert(NamespcName && "Invalid NamespcName.");
3404 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003405
3406 // This can only happen along a recovery path.
3407 while (S->getFlags() & Scope::TemplateParamScope)
3408 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003409 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003410
Douglas Gregor889ceb72009-02-03 19:21:40 +00003411 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003412 NestedNameSpecifier *Qualifier = 0;
3413 if (SS.isSet())
3414 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3415
Douglas Gregor34074322009-01-14 22:20:51 +00003416 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003417 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3418 LookupParsedName(R, S, &SS);
3419 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003420 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003421
Douglas Gregorcdf87022010-06-29 17:53:46 +00003422 if (R.empty()) {
3423 // Allow "using namespace std;" or "using namespace ::std;" even if
3424 // "std" hasn't been defined yet, for GCC compatibility.
3425 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3426 NamespcName->isStr("std")) {
3427 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003428 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003429 R.resolveKind();
3430 }
3431 // Otherwise, attempt typo correction.
3432 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3433 CTC_NoKeywords, 0)) {
3434 if (R.getAsSingle<NamespaceDecl>() ||
3435 R.getAsSingle<NamespaceAliasDecl>()) {
3436 if (DeclContext *DC = computeDeclContext(SS, false))
3437 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3438 << NamespcName << DC << Corrected << SS.getRange()
3439 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3440 else
3441 Diag(IdentLoc, diag::err_using_directive_suggest)
3442 << NamespcName << Corrected
3443 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3444 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3445 << Corrected;
3446
3447 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003448 } else {
3449 R.clear();
3450 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003451 }
3452 }
3453 }
3454
John McCall9f3059a2009-10-09 21:13:30 +00003455 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003456 NamedDecl *Named = R.getFoundDecl();
3457 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3458 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003459 // C++ [namespace.udir]p1:
3460 // A using-directive specifies that the names in the nominated
3461 // namespace can be used in the scope in which the
3462 // using-directive appears after the using-directive. During
3463 // unqualified name lookup (3.4.1), the names appear as if they
3464 // were declared in the nearest enclosing namespace which
3465 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003466 // namespace. [Note: in this context, "contains" means "contains
3467 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003468
3469 // Find enclosing context containing both using-directive and
3470 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003471 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003472 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3473 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3474 CommonAncestor = CommonAncestor->getParent();
3475
Sebastian Redla6602e92009-11-23 15:34:23 +00003476 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003477 SS.getRange(),
3478 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003479 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003480 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003481 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003482 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003483 }
3484
Douglas Gregor889ceb72009-02-03 19:21:40 +00003485 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003486 delete AttrList;
John McCall48871652010-08-21 09:40:31 +00003487 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003488}
3489
3490void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3491 // If scope has associated entity, then using directive is at namespace
3492 // or translation unit scope. We add UsingDirectiveDecls, into
3493 // it's lookup structure.
3494 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003495 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003496 else
3497 // Otherwise it is block-sope. using-directives will affect lookup
3498 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003499 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003500}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003501
Douglas Gregorfec52632009-06-20 00:51:54 +00003502
John McCall48871652010-08-21 09:40:31 +00003503Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003504 AccessSpecifier AS,
3505 bool HasUsingKeyword,
3506 SourceLocation UsingLoc,
3507 CXXScopeSpec &SS,
3508 UnqualifiedId &Name,
3509 AttributeList *AttrList,
3510 bool IsTypeName,
3511 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003512 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003513
Douglas Gregor220f4272009-11-04 16:30:06 +00003514 switch (Name.getKind()) {
3515 case UnqualifiedId::IK_Identifier:
3516 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003517 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003518 case UnqualifiedId::IK_ConversionFunctionId:
3519 break;
3520
3521 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003522 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003523 // C++0x inherited constructors.
3524 if (getLangOptions().CPlusPlus0x) break;
3525
Douglas Gregor220f4272009-11-04 16:30:06 +00003526 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3527 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003528 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003529
3530 case UnqualifiedId::IK_DestructorName:
3531 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3532 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003533 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003534
3535 case UnqualifiedId::IK_TemplateId:
3536 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3537 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003538 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003539 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003540
3541 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3542 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003543 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003544 return 0;
John McCall3969e302009-12-08 07:46:18 +00003545
John McCalla0097262009-12-11 02:10:03 +00003546 // Warn about using declarations.
3547 // TODO: store that the declaration was written without 'using' and
3548 // talk about access decls instead of using decls in the
3549 // diagnostics.
3550 if (!HasUsingKeyword) {
3551 UsingLoc = Name.getSourceRange().getBegin();
3552
3553 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003554 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003555 }
3556
John McCall3f746822009-11-17 05:59:44 +00003557 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003558 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003559 /* IsInstantiation */ false,
3560 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003561 if (UD)
3562 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003563
John McCall48871652010-08-21 09:40:31 +00003564 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003565}
3566
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003567/// \brief Determine whether a using declaration considers the given
3568/// declarations as "equivalent", e.g., if they are redeclarations of
3569/// the same entity or are both typedefs of the same type.
3570static bool
3571IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3572 bool &SuppressRedeclaration) {
3573 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3574 SuppressRedeclaration = false;
3575 return true;
3576 }
3577
3578 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3579 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3580 SuppressRedeclaration = true;
3581 return Context.hasSameType(TD1->getUnderlyingType(),
3582 TD2->getUnderlyingType());
3583 }
3584
3585 return false;
3586}
3587
3588
John McCall84d87672009-12-10 09:41:52 +00003589/// Determines whether to create a using shadow decl for a particular
3590/// decl, given the set of decls existing prior to this using lookup.
3591bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3592 const LookupResult &Previous) {
3593 // Diagnose finding a decl which is not from a base class of the
3594 // current class. We do this now because there are cases where this
3595 // function will silently decide not to build a shadow decl, which
3596 // will pre-empt further diagnostics.
3597 //
3598 // We don't need to do this in C++0x because we do the check once on
3599 // the qualifier.
3600 //
3601 // FIXME: diagnose the following if we care enough:
3602 // struct A { int foo; };
3603 // struct B : A { using A::foo; };
3604 // template <class T> struct C : A {};
3605 // template <class T> struct D : C<T> { using B::foo; } // <---
3606 // This is invalid (during instantiation) in C++03 because B::foo
3607 // resolves to the using decl in B, which is not a base class of D<T>.
3608 // We can't diagnose it immediately because C<T> is an unknown
3609 // specialization. The UsingShadowDecl in D<T> then points directly
3610 // to A::foo, which will look well-formed when we instantiate.
3611 // The right solution is to not collapse the shadow-decl chain.
3612 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3613 DeclContext *OrigDC = Orig->getDeclContext();
3614
3615 // Handle enums and anonymous structs.
3616 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3617 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3618 while (OrigRec->isAnonymousStructOrUnion())
3619 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3620
3621 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3622 if (OrigDC == CurContext) {
3623 Diag(Using->getLocation(),
3624 diag::err_using_decl_nested_name_specifier_is_current_class)
3625 << Using->getNestedNameRange();
3626 Diag(Orig->getLocation(), diag::note_using_decl_target);
3627 return true;
3628 }
3629
3630 Diag(Using->getNestedNameRange().getBegin(),
3631 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3632 << Using->getTargetNestedNameDecl()
3633 << cast<CXXRecordDecl>(CurContext)
3634 << Using->getNestedNameRange();
3635 Diag(Orig->getLocation(), diag::note_using_decl_target);
3636 return true;
3637 }
3638 }
3639
3640 if (Previous.empty()) return false;
3641
3642 NamedDecl *Target = Orig;
3643 if (isa<UsingShadowDecl>(Target))
3644 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3645
John McCalla17e83e2009-12-11 02:33:26 +00003646 // If the target happens to be one of the previous declarations, we
3647 // don't have a conflict.
3648 //
3649 // FIXME: but we might be increasing its access, in which case we
3650 // should redeclare it.
3651 NamedDecl *NonTag = 0, *Tag = 0;
3652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3653 I != E; ++I) {
3654 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003655 bool Result;
3656 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3657 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003658
3659 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3660 }
3661
John McCall84d87672009-12-10 09:41:52 +00003662 if (Target->isFunctionOrFunctionTemplate()) {
3663 FunctionDecl *FD;
3664 if (isa<FunctionTemplateDecl>(Target))
3665 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3666 else
3667 FD = cast<FunctionDecl>(Target);
3668
3669 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003670 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003671 case Ovl_Overload:
3672 return false;
3673
3674 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003675 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003676 break;
3677
3678 // We found a decl with the exact signature.
3679 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003680 // If we're in a record, we want to hide the target, so we
3681 // return true (without a diagnostic) to tell the caller not to
3682 // build a shadow decl.
3683 if (CurContext->isRecord())
3684 return true;
3685
3686 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003687 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003688 break;
3689 }
3690
3691 Diag(Target->getLocation(), diag::note_using_decl_target);
3692 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3693 return true;
3694 }
3695
3696 // Target is not a function.
3697
John McCall84d87672009-12-10 09:41:52 +00003698 if (isa<TagDecl>(Target)) {
3699 // No conflict between a tag and a non-tag.
3700 if (!Tag) return false;
3701
John McCalle29c5cd2009-12-10 19:51:03 +00003702 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003703 Diag(Target->getLocation(), diag::note_using_decl_target);
3704 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3705 return true;
3706 }
3707
3708 // No conflict between a tag and a non-tag.
3709 if (!NonTag) return false;
3710
John McCalle29c5cd2009-12-10 19:51:03 +00003711 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003712 Diag(Target->getLocation(), diag::note_using_decl_target);
3713 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3714 return true;
3715}
3716
John McCall3f746822009-11-17 05:59:44 +00003717/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003718UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003719 UsingDecl *UD,
3720 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003721
3722 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003723 NamedDecl *Target = Orig;
3724 if (isa<UsingShadowDecl>(Target)) {
3725 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3726 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003727 }
3728
3729 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003730 = UsingShadowDecl::Create(Context, CurContext,
3731 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003732 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003733
3734 Shadow->setAccess(UD->getAccess());
3735 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3736 Shadow->setInvalidDecl();
3737
John McCall3f746822009-11-17 05:59:44 +00003738 if (S)
John McCall3969e302009-12-08 07:46:18 +00003739 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003740 else
John McCall3969e302009-12-08 07:46:18 +00003741 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003742
John McCall3969e302009-12-08 07:46:18 +00003743
John McCall84d87672009-12-10 09:41:52 +00003744 return Shadow;
3745}
John McCall3969e302009-12-08 07:46:18 +00003746
John McCall84d87672009-12-10 09:41:52 +00003747/// Hides a using shadow declaration. This is required by the current
3748/// using-decl implementation when a resolvable using declaration in a
3749/// class is followed by a declaration which would hide or override
3750/// one or more of the using decl's targets; for example:
3751///
3752/// struct Base { void foo(int); };
3753/// struct Derived : Base {
3754/// using Base::foo;
3755/// void foo(int);
3756/// };
3757///
3758/// The governing language is C++03 [namespace.udecl]p12:
3759///
3760/// When a using-declaration brings names from a base class into a
3761/// derived class scope, member functions in the derived class
3762/// override and/or hide member functions with the same name and
3763/// parameter types in a base class (rather than conflicting).
3764///
3765/// There are two ways to implement this:
3766/// (1) optimistically create shadow decls when they're not hidden
3767/// by existing declarations, or
3768/// (2) don't create any shadow decls (or at least don't make them
3769/// visible) until we've fully parsed/instantiated the class.
3770/// The problem with (1) is that we might have to retroactively remove
3771/// a shadow decl, which requires several O(n) operations because the
3772/// decl structures are (very reasonably) not designed for removal.
3773/// (2) avoids this but is very fiddly and phase-dependent.
3774void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003775 if (Shadow->getDeclName().getNameKind() ==
3776 DeclarationName::CXXConversionFunctionName)
3777 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3778
John McCall84d87672009-12-10 09:41:52 +00003779 // Remove it from the DeclContext...
3780 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003781
John McCall84d87672009-12-10 09:41:52 +00003782 // ...and the scope, if applicable...
3783 if (S) {
John McCall48871652010-08-21 09:40:31 +00003784 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003785 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003786 }
3787
John McCall84d87672009-12-10 09:41:52 +00003788 // ...and the using decl.
3789 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3790
3791 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003792 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003793}
3794
John McCalle61f2ba2009-11-18 02:36:19 +00003795/// Builds a using declaration.
3796///
3797/// \param IsInstantiation - Whether this call arises from an
3798/// instantiation of an unresolved using declaration. We treat
3799/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003800NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3801 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003802 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003803 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003804 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003805 bool IsInstantiation,
3806 bool IsTypeName,
3807 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003808 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003809 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003810 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003811
Anders Carlssonf038fc22009-08-28 05:49:21 +00003812 // FIXME: We ignore attributes for now.
3813 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003814
Anders Carlsson59140b32009-08-28 03:16:11 +00003815 if (SS.isEmpty()) {
3816 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003817 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003818 }
Mike Stump11289f42009-09-09 15:08:12 +00003819
John McCall84d87672009-12-10 09:41:52 +00003820 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003821 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003822 ForRedeclaration);
3823 Previous.setHideTags(false);
3824 if (S) {
3825 LookupName(Previous, S);
3826
3827 // It is really dumb that we have to do this.
3828 LookupResult::Filter F = Previous.makeFilter();
3829 while (F.hasNext()) {
3830 NamedDecl *D = F.next();
3831 if (!isDeclInScope(D, CurContext, S))
3832 F.erase();
3833 }
3834 F.done();
3835 } else {
3836 assert(IsInstantiation && "no scope in non-instantiation");
3837 assert(CurContext->isRecord() && "scope not record in instantiation");
3838 LookupQualifiedName(Previous, CurContext);
3839 }
3840
Mike Stump11289f42009-09-09 15:08:12 +00003841 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003842 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3843
John McCall84d87672009-12-10 09:41:52 +00003844 // Check for invalid redeclarations.
3845 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3846 return 0;
3847
3848 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003849 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3850 return 0;
3851
John McCall84c16cf2009-11-12 03:15:40 +00003852 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003853 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003854 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003855 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003856 // FIXME: not all declaration name kinds are legal here
3857 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3858 UsingLoc, TypenameLoc,
3859 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003860 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003861 } else {
3862 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003863 UsingLoc, SS.getRange(),
3864 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003865 }
John McCallb96ec562009-12-04 22:46:56 +00003866 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003867 D = UsingDecl::Create(Context, CurContext,
3868 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003869 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003870 }
John McCallb96ec562009-12-04 22:46:56 +00003871 D->setAccess(AS);
3872 CurContext->addDecl(D);
3873
3874 if (!LookupContext) return D;
3875 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003876
John McCall0b66eb32010-05-01 00:40:08 +00003877 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003878 UD->setInvalidDecl();
3879 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003880 }
3881
John McCall3969e302009-12-08 07:46:18 +00003882 // Look up the target name.
3883
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003884 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003885
John McCall3969e302009-12-08 07:46:18 +00003886 // Unlike most lookups, we don't always want to hide tag
3887 // declarations: tag names are visible through the using declaration
3888 // even if hidden by ordinary names, *except* in a dependent context
3889 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003890 if (!IsInstantiation)
3891 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003892
John McCall27b18f82009-11-17 02:14:36 +00003893 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003894
John McCall9f3059a2009-10-09 21:13:30 +00003895 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003896 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003897 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003898 UD->setInvalidDecl();
3899 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003900 }
3901
John McCallb96ec562009-12-04 22:46:56 +00003902 if (R.isAmbiguous()) {
3903 UD->setInvalidDecl();
3904 return UD;
3905 }
Mike Stump11289f42009-09-09 15:08:12 +00003906
John McCalle61f2ba2009-11-18 02:36:19 +00003907 if (IsTypeName) {
3908 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003909 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003910 Diag(IdentLoc, diag::err_using_typename_non_type);
3911 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3912 Diag((*I)->getUnderlyingDecl()->getLocation(),
3913 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003914 UD->setInvalidDecl();
3915 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003916 }
3917 } else {
3918 // If we asked for a non-typename and we got a type, error out,
3919 // but only if this is an instantiation of an unresolved using
3920 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003921 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003922 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3923 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003924 UD->setInvalidDecl();
3925 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003926 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003927 }
3928
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003929 // C++0x N2914 [namespace.udecl]p6:
3930 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003931 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003932 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3933 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003934 UD->setInvalidDecl();
3935 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003936 }
Mike Stump11289f42009-09-09 15:08:12 +00003937
John McCall84d87672009-12-10 09:41:52 +00003938 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3939 if (!CheckUsingShadowDecl(UD, *I, Previous))
3940 BuildUsingShadowDecl(S, UD, *I);
3941 }
John McCall3f746822009-11-17 05:59:44 +00003942
3943 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003944}
3945
John McCall84d87672009-12-10 09:41:52 +00003946/// Checks that the given using declaration is not an invalid
3947/// redeclaration. Note that this is checking only for the using decl
3948/// itself, not for any ill-formedness among the UsingShadowDecls.
3949bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3950 bool isTypeName,
3951 const CXXScopeSpec &SS,
3952 SourceLocation NameLoc,
3953 const LookupResult &Prev) {
3954 // C++03 [namespace.udecl]p8:
3955 // C++0x [namespace.udecl]p10:
3956 // A using-declaration is a declaration and can therefore be used
3957 // repeatedly where (and only where) multiple declarations are
3958 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003959 //
3960 // That's in non-member contexts.
Sebastian Redl50c68252010-08-31 00:36:30 +00003961 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003962 return false;
3963
3964 NestedNameSpecifier *Qual
3965 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3966
3967 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3968 NamedDecl *D = *I;
3969
3970 bool DTypename;
3971 NestedNameSpecifier *DQual;
3972 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3973 DTypename = UD->isTypeName();
3974 DQual = UD->getTargetNestedNameDecl();
3975 } else if (UnresolvedUsingValueDecl *UD
3976 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3977 DTypename = false;
3978 DQual = UD->getTargetNestedNameSpecifier();
3979 } else if (UnresolvedUsingTypenameDecl *UD
3980 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3981 DTypename = true;
3982 DQual = UD->getTargetNestedNameSpecifier();
3983 } else continue;
3984
3985 // using decls differ if one says 'typename' and the other doesn't.
3986 // FIXME: non-dependent using decls?
3987 if (isTypeName != DTypename) continue;
3988
3989 // using decls differ if they name different scopes (but note that
3990 // template instantiation can cause this check to trigger when it
3991 // didn't before instantiation).
3992 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3993 Context.getCanonicalNestedNameSpecifier(DQual))
3994 continue;
3995
3996 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003997 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003998 return true;
3999 }
4000
4001 return false;
4002}
4003
John McCall3969e302009-12-08 07:46:18 +00004004
John McCallb96ec562009-12-04 22:46:56 +00004005/// Checks that the given nested-name qualifier used in a using decl
4006/// in the current context is appropriately related to the current
4007/// scope. If an error is found, diagnoses it and returns true.
4008bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4009 const CXXScopeSpec &SS,
4010 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004011 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004012
John McCall3969e302009-12-08 07:46:18 +00004013 if (!CurContext->isRecord()) {
4014 // C++03 [namespace.udecl]p3:
4015 // C++0x [namespace.udecl]p8:
4016 // A using-declaration for a class member shall be a member-declaration.
4017
4018 // If we weren't able to compute a valid scope, it must be a
4019 // dependent class scope.
4020 if (!NamedContext || NamedContext->isRecord()) {
4021 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4022 << SS.getRange();
4023 return true;
4024 }
4025
4026 // Otherwise, everything is known to be fine.
4027 return false;
4028 }
4029
4030 // The current scope is a record.
4031
4032 // If the named context is dependent, we can't decide much.
4033 if (!NamedContext) {
4034 // FIXME: in C++0x, we can diagnose if we can prove that the
4035 // nested-name-specifier does not refer to a base class, which is
4036 // still possible in some cases.
4037
4038 // Otherwise we have to conservatively report that things might be
4039 // okay.
4040 return false;
4041 }
4042
4043 if (!NamedContext->isRecord()) {
4044 // Ideally this would point at the last name in the specifier,
4045 // but we don't have that level of source info.
4046 Diag(SS.getRange().getBegin(),
4047 diag::err_using_decl_nested_name_specifier_is_not_class)
4048 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4049 return true;
4050 }
4051
4052 if (getLangOptions().CPlusPlus0x) {
4053 // C++0x [namespace.udecl]p3:
4054 // In a using-declaration used as a member-declaration, the
4055 // nested-name-specifier shall name a base class of the class
4056 // being defined.
4057
4058 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4059 cast<CXXRecordDecl>(NamedContext))) {
4060 if (CurContext == NamedContext) {
4061 Diag(NameLoc,
4062 diag::err_using_decl_nested_name_specifier_is_current_class)
4063 << SS.getRange();
4064 return true;
4065 }
4066
4067 Diag(SS.getRange().getBegin(),
4068 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4069 << (NestedNameSpecifier*) SS.getScopeRep()
4070 << cast<CXXRecordDecl>(CurContext)
4071 << SS.getRange();
4072 return true;
4073 }
4074
4075 return false;
4076 }
4077
4078 // C++03 [namespace.udecl]p4:
4079 // A using-declaration used as a member-declaration shall refer
4080 // to a member of a base class of the class being defined [etc.].
4081
4082 // Salient point: SS doesn't have to name a base class as long as
4083 // lookup only finds members from base classes. Therefore we can
4084 // diagnose here only if we can prove that that can't happen,
4085 // i.e. if the class hierarchies provably don't intersect.
4086
4087 // TODO: it would be nice if "definitely valid" results were cached
4088 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4089 // need to be repeated.
4090
4091 struct UserData {
4092 llvm::DenseSet<const CXXRecordDecl*> Bases;
4093
4094 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4095 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4096 Data->Bases.insert(Base);
4097 return true;
4098 }
4099
4100 bool hasDependentBases(const CXXRecordDecl *Class) {
4101 return !Class->forallBases(collect, this);
4102 }
4103
4104 /// Returns true if the base is dependent or is one of the
4105 /// accumulated base classes.
4106 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4107 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4108 return !Data->Bases.count(Base);
4109 }
4110
4111 bool mightShareBases(const CXXRecordDecl *Class) {
4112 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4113 }
4114 };
4115
4116 UserData Data;
4117
4118 // Returns false if we find a dependent base.
4119 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4120 return false;
4121
4122 // Returns false if the class has a dependent base or if it or one
4123 // of its bases is present in the base set of the current context.
4124 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4125 return false;
4126
4127 Diag(SS.getRange().getBegin(),
4128 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4129 << (NestedNameSpecifier*) SS.getScopeRep()
4130 << cast<CXXRecordDecl>(CurContext)
4131 << SS.getRange();
4132
4133 return true;
John McCallb96ec562009-12-04 22:46:56 +00004134}
4135
John McCall48871652010-08-21 09:40:31 +00004136Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004137 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004138 SourceLocation AliasLoc,
4139 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004140 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004141 SourceLocation IdentLoc,
4142 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004143
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004144 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004145 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4146 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004147
Anders Carlssondca83c42009-03-28 06:23:46 +00004148 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004149 NamedDecl *PrevDecl
4150 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4151 ForRedeclaration);
4152 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4153 PrevDecl = 0;
4154
4155 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004156 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004157 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004158 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004159 // FIXME: At some point, we'll want to create the (redundant)
4160 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004161 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004162 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004163 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004164 }
Mike Stump11289f42009-09-09 15:08:12 +00004165
Anders Carlssondca83c42009-03-28 06:23:46 +00004166 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4167 diag::err_redefinition_different_kind;
4168 Diag(AliasLoc, DiagID) << Alias;
4169 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004170 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004171 }
4172
John McCall27b18f82009-11-17 02:14:36 +00004173 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004174 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004175
John McCall9f3059a2009-10-09 21:13:30 +00004176 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004177 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4178 CTC_NoKeywords, 0)) {
4179 if (R.getAsSingle<NamespaceDecl>() ||
4180 R.getAsSingle<NamespaceAliasDecl>()) {
4181 if (DeclContext *DC = computeDeclContext(SS, false))
4182 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4183 << Ident << DC << Corrected << SS.getRange()
4184 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4185 else
4186 Diag(IdentLoc, diag::err_using_directive_suggest)
4187 << Ident << Corrected
4188 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4189
4190 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4191 << Corrected;
4192
4193 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004194 } else {
4195 R.clear();
4196 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004197 }
4198 }
4199
4200 if (R.empty()) {
4201 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004202 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004203 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004206 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004207 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4208 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004209 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004210 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004211
John McCalld8d0d432010-02-16 06:53:13 +00004212 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004213 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004214}
4215
Douglas Gregora57478e2010-05-01 15:04:51 +00004216namespace {
4217 /// \brief Scoped object used to handle the state changes required in Sema
4218 /// to implicitly define the body of a C++ member function;
4219 class ImplicitlyDefinedFunctionScope {
4220 Sema &S;
4221 DeclContext *PreviousContext;
4222
4223 public:
4224 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4225 : S(S), PreviousContext(S.CurContext)
4226 {
4227 S.CurContext = Method;
4228 S.PushFunctionScope();
4229 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4230 }
4231
4232 ~ImplicitlyDefinedFunctionScope() {
4233 S.PopExpressionEvaluationContext();
4234 S.PopFunctionOrBlockScope();
4235 S.CurContext = PreviousContext;
4236 }
4237 };
4238}
4239
Sebastian Redlc15c3262010-09-13 22:02:47 +00004240static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4241 CXXRecordDecl *D) {
4242 ASTContext &Context = Self.Context;
4243 QualType ClassType = Context.getTypeDeclType(D);
4244 DeclarationName ConstructorName
4245 = Context.DeclarationNames.getCXXConstructorName(
4246 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4247
4248 DeclContext::lookup_const_iterator Con, ConEnd;
4249 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4250 Con != ConEnd; ++Con) {
4251 // FIXME: In C++0x, a constructor template can be a default constructor.
4252 if (isa<FunctionTemplateDecl>(*Con))
4253 continue;
4254
4255 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4256 if (Constructor->isDefaultConstructor())
4257 return Constructor;
4258 }
4259 return 0;
4260}
4261
Douglas Gregor0be31a22010-07-02 17:43:08 +00004262CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4263 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004264 // C++ [class.ctor]p5:
4265 // A default constructor for a class X is a constructor of class X
4266 // that can be called without an argument. If there is no
4267 // user-declared constructor for class X, a default constructor is
4268 // implicitly declared. An implicitly-declared default constructor
4269 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004270 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4271 "Should not build implicit default constructor!");
4272
Douglas Gregor6d880b12010-07-01 22:31:05 +00004273 // C++ [except.spec]p14:
4274 // An implicitly declared special member function (Clause 12) shall have an
4275 // exception-specification. [...]
4276 ImplicitExceptionSpecification ExceptSpec(Context);
4277
4278 // Direct base-class destructors.
4279 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4280 BEnd = ClassDecl->bases_end();
4281 B != BEnd; ++B) {
4282 if (B->isVirtual()) // Handled below.
4283 continue;
4284
Douglas Gregor9672f922010-07-03 00:47:00 +00004285 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4286 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4287 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4288 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004289 else if (CXXConstructorDecl *Constructor
4290 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004291 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004292 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004293 }
4294
4295 // Virtual base-class destructors.
4296 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4297 BEnd = ClassDecl->vbases_end();
4298 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004299 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4300 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4301 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4302 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4303 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004304 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004305 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004306 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004307 }
4308
4309 // Field destructors.
4310 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4311 FEnd = ClassDecl->field_end();
4312 F != FEnd; ++F) {
4313 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004314 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4315 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4316 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4317 ExceptSpec.CalledDecl(
4318 DeclareImplicitDefaultConstructor(FieldClassDecl));
4319 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004320 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004321 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004322 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004323 }
4324
4325
4326 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004327 CanQualType ClassType
4328 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4329 DeclarationName Name
4330 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004331 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004332 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004333 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004334 Context.getFunctionType(Context.VoidTy,
4335 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004336 ExceptSpec.hasExceptionSpecification(),
4337 ExceptSpec.hasAnyExceptionSpecification(),
4338 ExceptSpec.size(),
4339 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004340 FunctionType::ExtInfo()),
4341 /*TInfo=*/0,
4342 /*isExplicit=*/false,
4343 /*isInline=*/true,
4344 /*isImplicitlyDeclared=*/true);
4345 DefaultCon->setAccess(AS_public);
4346 DefaultCon->setImplicit();
4347 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004348
4349 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004350 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4351
Douglas Gregor0be31a22010-07-02 17:43:08 +00004352 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004353 PushOnScopeChains(DefaultCon, S, false);
4354 ClassDecl->addDecl(DefaultCon);
4355
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004356 return DefaultCon;
4357}
4358
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004359void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4360 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004361 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004362 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004363 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004364
Anders Carlsson423f5d82010-04-23 16:04:08 +00004365 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004366 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004367
Douglas Gregora57478e2010-05-01 15:04:51 +00004368 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004369 ErrorTrap Trap(*this);
4370 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4371 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004372 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004373 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004374 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004375 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004376 }
Douglas Gregor73193272010-09-20 16:48:21 +00004377
4378 SourceLocation Loc = Constructor->getLocation();
4379 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4380
4381 Constructor->setUsed();
4382 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004383}
4384
Douglas Gregor0be31a22010-07-02 17:43:08 +00004385CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004386 // C++ [class.dtor]p2:
4387 // If a class has no user-declared destructor, a destructor is
4388 // declared implicitly. An implicitly-declared destructor is an
4389 // inline public member of its class.
4390
4391 // C++ [except.spec]p14:
4392 // An implicitly declared special member function (Clause 12) shall have
4393 // an exception-specification.
4394 ImplicitExceptionSpecification ExceptSpec(Context);
4395
4396 // Direct base-class destructors.
4397 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4398 BEnd = ClassDecl->bases_end();
4399 B != BEnd; ++B) {
4400 if (B->isVirtual()) // Handled below.
4401 continue;
4402
4403 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4404 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004405 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004406 }
4407
4408 // Virtual base-class destructors.
4409 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4410 BEnd = ClassDecl->vbases_end();
4411 B != BEnd; ++B) {
4412 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4413 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004414 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004415 }
4416
4417 // Field destructors.
4418 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4419 FEnd = ClassDecl->field_end();
4420 F != FEnd; ++F) {
4421 if (const RecordType *RecordTy
4422 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4423 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004424 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004425 }
4426
Douglas Gregor7454c562010-07-02 20:37:36 +00004427 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004428 QualType Ty = Context.getFunctionType(Context.VoidTy,
4429 0, 0, false, 0,
4430 ExceptSpec.hasExceptionSpecification(),
4431 ExceptSpec.hasAnyExceptionSpecification(),
4432 ExceptSpec.size(),
4433 ExceptSpec.data(),
4434 FunctionType::ExtInfo());
4435
4436 CanQualType ClassType
4437 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4438 DeclarationName Name
4439 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004440 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004441 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004442 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004443 /*isInline=*/true,
4444 /*isImplicitlyDeclared=*/true);
4445 Destructor->setAccess(AS_public);
4446 Destructor->setImplicit();
4447 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004448
4449 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004450 ++ASTContext::NumImplicitDestructorsDeclared;
4451
4452 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004453 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004454 PushOnScopeChains(Destructor, S, false);
4455 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004456
4457 // This could be uniqued if it ever proves significant.
4458 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4459
4460 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004461
Douglas Gregorf1203042010-07-01 19:09:28 +00004462 return Destructor;
4463}
4464
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004465void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004466 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004467 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004468 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004469 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004470 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004471
Douglas Gregor54818f02010-05-12 16:39:35 +00004472 if (Destructor->isInvalidDecl())
4473 return;
4474
Douglas Gregora57478e2010-05-01 15:04:51 +00004475 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004476
Douglas Gregor54818f02010-05-12 16:39:35 +00004477 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004478 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4479 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregor54818f02010-05-12 16:39:35 +00004481 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004482 Diag(CurrentLocation, diag::note_member_synthesized_at)
4483 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4484
4485 Destructor->setInvalidDecl();
4486 return;
4487 }
4488
Douglas Gregor73193272010-09-20 16:48:21 +00004489 SourceLocation Loc = Destructor->getLocation();
4490 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4491
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004492 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004493 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004494}
4495
Douglas Gregorb139cd52010-05-01 20:49:11 +00004496/// \brief Builds a statement that copies the given entity from \p From to
4497/// \c To.
4498///
4499/// This routine is used to copy the members of a class with an
4500/// implicitly-declared copy assignment operator. When the entities being
4501/// copied are arrays, this routine builds for loops to copy them.
4502///
4503/// \param S The Sema object used for type-checking.
4504///
4505/// \param Loc The location where the implicit copy is being generated.
4506///
4507/// \param T The type of the expressions being copied. Both expressions must
4508/// have this type.
4509///
4510/// \param To The expression we are copying to.
4511///
4512/// \param From The expression we are copying from.
4513///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004514/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4515/// Otherwise, it's a non-static member subobject.
4516///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004517/// \param Depth Internal parameter recording the depth of the recursion.
4518///
4519/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004520static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004521BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004522 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004523 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004524 // C++0x [class.copy]p30:
4525 // Each subobject is assigned in the manner appropriate to its type:
4526 //
4527 // - if the subobject is of class type, the copy assignment operator
4528 // for the class is used (as if by explicit qualification; that is,
4529 // ignoring any possible virtual overriding functions in more derived
4530 // classes);
4531 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4532 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4533
4534 // Look for operator=.
4535 DeclarationName Name
4536 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4537 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4538 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4539
4540 // Filter out any result that isn't a copy-assignment operator.
4541 LookupResult::Filter F = OpLookup.makeFilter();
4542 while (F.hasNext()) {
4543 NamedDecl *D = F.next();
4544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4545 if (Method->isCopyAssignmentOperator())
4546 continue;
4547
4548 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004549 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004550 F.done();
4551
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004552 // Suppress the protected check (C++ [class.protected]) for each of the
4553 // assignment operators we found. This strange dance is required when
4554 // we're assigning via a base classes's copy-assignment operator. To
4555 // ensure that we're getting the right base class subobject (without
4556 // ambiguities), we need to cast "this" to that subobject type; to
4557 // ensure that we don't go through the virtual call mechanism, we need
4558 // to qualify the operator= name with the base class (see below). However,
4559 // this means that if the base class has a protected copy assignment
4560 // operator, the protected member access check will fail. So, we
4561 // rewrite "protected" access to "public" access in this case, since we
4562 // know by construction that we're calling from a derived class.
4563 if (CopyingBaseSubobject) {
4564 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4565 L != LEnd; ++L) {
4566 if (L.getAccess() == AS_protected)
4567 L.setAccess(AS_public);
4568 }
4569 }
4570
Douglas Gregorb139cd52010-05-01 20:49:11 +00004571 // Create the nested-name-specifier that will be used to qualify the
4572 // reference to operator=; this is required to suppress the virtual
4573 // call mechanism.
4574 CXXScopeSpec SS;
4575 SS.setRange(Loc);
4576 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4577 T.getTypePtr()));
4578
4579 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004580 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004581 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004582 /*FirstQualifierInScope=*/0, OpLookup,
4583 /*TemplateArgs=*/0,
4584 /*SuppressQualifierCheck=*/true);
4585 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004586 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004587
4588 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004589
John McCalldadc5752010-08-24 06:29:42 +00004590 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004591 OpEqualRef.takeAs<Expr>(),
4592 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004593 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004594 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004595
4596 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004597 }
John McCallab8c2732010-03-16 06:11:48 +00004598
Douglas Gregorb139cd52010-05-01 20:49:11 +00004599 // - if the subobject is of scalar type, the built-in assignment
4600 // operator is used.
4601 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4602 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004603 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004604 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004605 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004606
4607 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004608 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004609
4610 // - if the subobject is an array, each element is assigned, in the
4611 // manner appropriate to the element type;
4612
4613 // Construct a loop over the array bounds, e.g.,
4614 //
4615 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4616 //
4617 // that will copy each of the array elements.
4618 QualType SizeType = S.Context.getSizeType();
4619
4620 // Create the iteration variable.
4621 IdentifierInfo *IterationVarName = 0;
4622 {
4623 llvm::SmallString<8> Str;
4624 llvm::raw_svector_ostream OS(Str);
4625 OS << "__i" << Depth;
4626 IterationVarName = &S.Context.Idents.get(OS.str());
4627 }
4628 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4629 IterationVarName, SizeType,
4630 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004631 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004632
4633 // Initialize the iteration variable to zero.
4634 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004635 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004636
4637 // Create a reference to the iteration variable; we'll use this several
4638 // times throughout.
4639 Expr *IterationVarRef
4640 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4641 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4642
4643 // Create the DeclStmt that holds the iteration variable.
4644 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4645
4646 // Create the comparison against the array bound.
4647 llvm::APInt Upper = ArrayTy->getSize();
4648 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004649 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004650 = new (S.Context) BinaryOperator(IterationVarRef,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004651 IntegerLiteral::Create(S.Context,
4652 Upper, SizeType, Loc),
4653 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004654
4655 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004656 Expr *Increment
John McCallc3007a22010-10-26 07:05:15 +00004657 = new (S.Context) UnaryOperator(IterationVarRef,
John McCalle3027922010-08-25 11:45:40 +00004658 UO_PreInc,
John McCallb268a282010-08-23 23:25:46 +00004659 SizeType, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004660
4661 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004662 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4663 IterationVarRef, Loc));
4664 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4665 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004666
4667 // Build the copy for an individual element of the array.
John McCalldadc5752010-08-24 06:29:42 +00004668 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004669 ArrayTy->getElementType(),
John McCallb268a282010-08-23 23:25:46 +00004670 To, From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004671 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004672 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004673 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004674
4675 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004676 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004677 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004678 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004679 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004680}
4681
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004682/// \brief Determine whether the given class has a copy assignment operator
4683/// that accepts a const-qualified argument.
4684static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4685 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4686
4687 if (!Class->hasDeclaredCopyAssignment())
4688 S.DeclareImplicitCopyAssignment(Class);
4689
4690 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4691 DeclarationName OpName
4692 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4693
4694 DeclContext::lookup_const_iterator Op, OpEnd;
4695 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4696 // C++ [class.copy]p9:
4697 // A user-declared copy assignment operator is a non-static non-template
4698 // member function of class X with exactly one parameter of type X, X&,
4699 // const X&, volatile X& or const volatile X&.
4700 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4701 if (!Method)
4702 continue;
4703
4704 if (Method->isStatic())
4705 continue;
4706 if (Method->getPrimaryTemplate())
4707 continue;
4708 const FunctionProtoType *FnType =
4709 Method->getType()->getAs<FunctionProtoType>();
4710 assert(FnType && "Overloaded operator has no prototype.");
4711 // Don't assert on this; an invalid decl might have been left in the AST.
4712 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4713 continue;
4714 bool AcceptsConst = true;
4715 QualType ArgType = FnType->getArgType(0);
4716 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4717 ArgType = Ref->getPointeeType();
4718 // Is it a non-const lvalue reference?
4719 if (!ArgType.isConstQualified())
4720 AcceptsConst = false;
4721 }
4722 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4723 continue;
4724
4725 // We have a single argument of type cv X or cv X&, i.e. we've found the
4726 // copy assignment operator. Return whether it accepts const arguments.
4727 return AcceptsConst;
4728 }
4729 assert(Class->isInvalidDecl() &&
4730 "No copy assignment operator declared in valid code.");
4731 return false;
4732}
4733
Douglas Gregor0be31a22010-07-02 17:43:08 +00004734CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004735 // Note: The following rules are largely analoguous to the copy
4736 // constructor rules. Note that virtual bases are not taken into account
4737 // for determining the argument type of the operator. Note also that
4738 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004739
4740
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004741 // C++ [class.copy]p10:
4742 // If the class definition does not explicitly declare a copy
4743 // assignment operator, one is declared implicitly.
4744 // The implicitly-defined copy assignment operator for a class X
4745 // will have the form
4746 //
4747 // X& X::operator=(const X&)
4748 //
4749 // if
4750 bool HasConstCopyAssignment = true;
4751
4752 // -- each direct base class B of X has a copy assignment operator
4753 // whose parameter is of type const B&, const volatile B& or B,
4754 // and
4755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4756 BaseEnd = ClassDecl->bases_end();
4757 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4758 assert(!Base->getType()->isDependentType() &&
4759 "Cannot generate implicit members for class with dependent bases.");
4760 const CXXRecordDecl *BaseClassDecl
4761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004762 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004763 }
4764
4765 // -- for all the nonstatic data members of X that are of a class
4766 // type M (or array thereof), each such class type has a copy
4767 // assignment operator whose parameter is of type const M&,
4768 // const volatile M& or M.
4769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4770 FieldEnd = ClassDecl->field_end();
4771 HasConstCopyAssignment && Field != FieldEnd;
4772 ++Field) {
4773 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4774 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4775 const CXXRecordDecl *FieldClassDecl
4776 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004777 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004778 }
4779 }
4780
4781 // Otherwise, the implicitly declared copy assignment operator will
4782 // have the form
4783 //
4784 // X& X::operator=(X&)
4785 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4786 QualType RetType = Context.getLValueReferenceType(ArgType);
4787 if (HasConstCopyAssignment)
4788 ArgType = ArgType.withConst();
4789 ArgType = Context.getLValueReferenceType(ArgType);
4790
Douglas Gregor68e11362010-07-01 17:48:08 +00004791 // C++ [except.spec]p14:
4792 // An implicitly declared special member function (Clause 12) shall have an
4793 // exception-specification. [...]
4794 ImplicitExceptionSpecification ExceptSpec(Context);
4795 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4796 BaseEnd = ClassDecl->bases_end();
4797 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004798 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004799 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004800
4801 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4802 DeclareImplicitCopyAssignment(BaseClassDecl);
4803
Douglas Gregor68e11362010-07-01 17:48:08 +00004804 if (CXXMethodDecl *CopyAssign
4805 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4806 ExceptSpec.CalledDecl(CopyAssign);
4807 }
4808 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4809 FieldEnd = ClassDecl->field_end();
4810 Field != FieldEnd;
4811 ++Field) {
4812 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4813 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004814 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004815 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004816
4817 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4818 DeclareImplicitCopyAssignment(FieldClassDecl);
4819
Douglas Gregor68e11362010-07-01 17:48:08 +00004820 if (CXXMethodDecl *CopyAssign
4821 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4822 ExceptSpec.CalledDecl(CopyAssign);
4823 }
4824 }
4825
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004826 // An implicitly-declared copy assignment operator is an inline public
4827 // member of its class.
4828 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004829 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004830 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004831 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004832 Context.getFunctionType(RetType, &ArgType, 1,
4833 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004834 ExceptSpec.hasExceptionSpecification(),
4835 ExceptSpec.hasAnyExceptionSpecification(),
4836 ExceptSpec.size(),
4837 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004838 FunctionType::ExtInfo()),
4839 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004840 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004841 /*isInline=*/true);
4842 CopyAssignment->setAccess(AS_public);
4843 CopyAssignment->setImplicit();
4844 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004845
4846 // Add the parameter to the operator.
4847 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4848 ClassDecl->getLocation(),
4849 /*Id=*/0,
4850 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004851 SC_None,
4852 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004853 CopyAssignment->setParams(&FromParam, 1);
4854
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004855 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004856 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4857
Douglas Gregor0be31a22010-07-02 17:43:08 +00004858 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004859 PushOnScopeChains(CopyAssignment, S, false);
4860 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004861
4862 AddOverriddenMethods(ClassDecl, CopyAssignment);
4863 return CopyAssignment;
4864}
4865
Douglas Gregorb139cd52010-05-01 20:49:11 +00004866void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4867 CXXMethodDecl *CopyAssignOperator) {
4868 assert((CopyAssignOperator->isImplicit() &&
4869 CopyAssignOperator->isOverloadedOperator() &&
4870 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004871 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004872 "DefineImplicitCopyAssignment called for wrong function");
4873
4874 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4875
4876 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4877 CopyAssignOperator->setInvalidDecl();
4878 return;
4879 }
4880
4881 CopyAssignOperator->setUsed();
4882
4883 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004884 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004885
4886 // C++0x [class.copy]p30:
4887 // The implicitly-defined or explicitly-defaulted copy assignment operator
4888 // for a non-union class X performs memberwise copy assignment of its
4889 // subobjects. The direct base classes of X are assigned first, in the
4890 // order of their declaration in the base-specifier-list, and then the
4891 // immediate non-static data members of X are assigned, in the order in
4892 // which they were declared in the class definition.
4893
4894 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004895 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004896
4897 // The parameter for the "other" object, which we are copying from.
4898 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4899 Qualifiers OtherQuals = Other->getType().getQualifiers();
4900 QualType OtherRefType = Other->getType();
4901 if (const LValueReferenceType *OtherRef
4902 = OtherRefType->getAs<LValueReferenceType>()) {
4903 OtherRefType = OtherRef->getPointeeType();
4904 OtherQuals = OtherRefType.getQualifiers();
4905 }
4906
4907 // Our location for everything implicitly-generated.
4908 SourceLocation Loc = CopyAssignOperator->getLocation();
4909
4910 // Construct a reference to the "other" object. We'll be using this
4911 // throughout the generated ASTs.
4912 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4913 assert(OtherRef && "Reference to parameter cannot fail!");
4914
4915 // Construct the "this" pointer. We'll be using this throughout the generated
4916 // ASTs.
4917 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4918 assert(This && "Reference to this cannot fail!");
4919
4920 // Assign base classes.
4921 bool Invalid = false;
4922 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4923 E = ClassDecl->bases_end(); Base != E; ++Base) {
4924 // Form the assignment:
4925 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4926 QualType BaseType = Base->getType().getUnqualifiedType();
4927 CXXRecordDecl *BaseClassDecl = 0;
4928 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4929 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4930 else {
4931 Invalid = true;
4932 continue;
4933 }
4934
John McCallcf142162010-08-07 06:22:56 +00004935 CXXCastPath BasePath;
4936 BasePath.push_back(Base);
4937
Douglas Gregorb139cd52010-05-01 20:49:11 +00004938 // Construct the "from" expression, which is an implicit cast to the
4939 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00004940 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004941 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004942 CK_UncheckedDerivedToBase,
4943 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004944
4945 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004946 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004947
4948 // Implicitly cast "this" to the appropriately-qualified base type.
4949 Expr *ToE = To.takeAs<Expr>();
4950 ImpCastExprToType(ToE,
4951 Context.getCVRQualifiedType(BaseType,
4952 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004953 CK_UncheckedDerivedToBase,
4954 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004955 To = Owned(ToE);
4956
4957 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004958 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004959 To.get(), From,
4960 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004961 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004962 Diag(CurrentLocation, diag::note_member_synthesized_at)
4963 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4964 CopyAssignOperator->setInvalidDecl();
4965 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004966 }
4967
4968 // Success! Record the copy.
4969 Statements.push_back(Copy.takeAs<Expr>());
4970 }
4971
4972 // \brief Reference to the __builtin_memcpy function.
4973 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004974 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004975 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004976
4977 // Assign non-static members.
4978 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4979 FieldEnd = ClassDecl->field_end();
4980 Field != FieldEnd; ++Field) {
4981 // Check for members of reference type; we can't copy those.
4982 if (Field->getType()->isReferenceType()) {
4983 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4984 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4985 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004986 Diag(CurrentLocation, diag::note_member_synthesized_at)
4987 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004988 Invalid = true;
4989 continue;
4990 }
4991
4992 // Check for members of const-qualified, non-class type.
4993 QualType BaseType = Context.getBaseElementType(Field->getType());
4994 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4995 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4996 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4997 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004998 Diag(CurrentLocation, diag::note_member_synthesized_at)
4999 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005000 Invalid = true;
5001 continue;
5002 }
5003
5004 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005005 if (FieldType->isIncompleteArrayType()) {
5006 assert(ClassDecl->hasFlexibleArrayMember() &&
5007 "Incomplete array type is not valid");
5008 continue;
5009 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005010
5011 // Build references to the field in the object we're copying from and to.
5012 CXXScopeSpec SS; // Intentionally empty
5013 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5014 LookupMemberName);
5015 MemberLookup.addDecl(*Field);
5016 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005017 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005018 Loc, /*IsArrow=*/false,
5019 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005020 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005021 Loc, /*IsArrow=*/true,
5022 SS, 0, MemberLookup, 0);
5023 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5024 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5025
5026 // If the field should be copied with __builtin_memcpy rather than via
5027 // explicit assignments, do so. This optimization only applies for arrays
5028 // of scalars and arrays of class type with trivial copy-assignment
5029 // operators.
5030 if (FieldType->isArrayType() &&
5031 (!BaseType->isRecordType() ||
5032 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5033 ->hasTrivialCopyAssignment())) {
5034 // Compute the size of the memory buffer to be copied.
5035 QualType SizeType = Context.getSizeType();
5036 llvm::APInt Size(Context.getTypeSize(SizeType),
5037 Context.getTypeSizeInChars(BaseType).getQuantity());
5038 for (const ConstantArrayType *Array
5039 = Context.getAsConstantArrayType(FieldType);
5040 Array;
5041 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5042 llvm::APInt ArraySize = Array->getSize();
5043 ArraySize.zextOrTrunc(Size.getBitWidth());
5044 Size *= ArraySize;
5045 }
5046
5047 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005048 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5049 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005050
5051 bool NeedsCollectableMemCpy =
5052 (BaseType->isRecordType() &&
5053 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5054
5055 if (NeedsCollectableMemCpy) {
5056 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005057 // Create a reference to the __builtin_objc_memmove_collectable function.
5058 LookupResult R(*this,
5059 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005060 Loc, LookupOrdinaryName);
5061 LookupName(R, TUScope, true);
5062
5063 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5064 if (!CollectableMemCpy) {
5065 // Something went horribly wrong earlier, and we will have
5066 // complained about it.
5067 Invalid = true;
5068 continue;
5069 }
5070
5071 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5072 CollectableMemCpy->getType(),
5073 Loc, 0).takeAs<Expr>();
5074 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5075 }
5076 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005077 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005078 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005079 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5080 LookupOrdinaryName);
5081 LookupName(R, TUScope, true);
5082
5083 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5084 if (!BuiltinMemCpy) {
5085 // Something went horribly wrong earlier, and we will have complained
5086 // about it.
5087 Invalid = true;
5088 continue;
5089 }
5090
5091 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5092 BuiltinMemCpy->getType(),
5093 Loc, 0).takeAs<Expr>();
5094 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5095 }
5096
John McCall37ad5512010-08-23 06:44:23 +00005097 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005098 CallArgs.push_back(To.takeAs<Expr>());
5099 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005100 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005101 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005102 if (NeedsCollectableMemCpy)
5103 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005104 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005105 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005106 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005107 else
5108 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005109 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005110 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005111 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005112
Douglas Gregorb139cd52010-05-01 20:49:11 +00005113 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5114 Statements.push_back(Call.takeAs<Expr>());
5115 continue;
5116 }
5117
5118 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005119 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005120 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005121 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005122 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005123 Diag(CurrentLocation, diag::note_member_synthesized_at)
5124 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5125 CopyAssignOperator->setInvalidDecl();
5126 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005127 }
5128
5129 // Success! Record the copy.
5130 Statements.push_back(Copy.takeAs<Stmt>());
5131 }
5132
5133 if (!Invalid) {
5134 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005135 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005136
John McCalldadc5752010-08-24 06:29:42 +00005137 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005138 if (Return.isInvalid())
5139 Invalid = true;
5140 else {
5141 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005142
5143 if (Trap.hasErrorOccurred()) {
5144 Diag(CurrentLocation, diag::note_member_synthesized_at)
5145 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5146 Invalid = true;
5147 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005148 }
5149 }
5150
5151 if (Invalid) {
5152 CopyAssignOperator->setInvalidDecl();
5153 return;
5154 }
5155
John McCalldadc5752010-08-24 06:29:42 +00005156 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005157 /*isStmtExpr=*/false);
5158 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5159 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005160}
5161
Douglas Gregor0be31a22010-07-02 17:43:08 +00005162CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5163 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005164 // C++ [class.copy]p4:
5165 // If the class definition does not explicitly declare a copy
5166 // constructor, one is declared implicitly.
5167
Douglas Gregor54be3392010-07-01 17:57:27 +00005168 // C++ [class.copy]p5:
5169 // The implicitly-declared copy constructor for a class X will
5170 // have the form
5171 //
5172 // X::X(const X&)
5173 //
5174 // if
5175 bool HasConstCopyConstructor = true;
5176
5177 // -- each direct or virtual base class B of X has a copy
5178 // constructor whose first parameter is of type const B& or
5179 // const volatile B&, and
5180 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5181 BaseEnd = ClassDecl->bases_end();
5182 HasConstCopyConstructor && Base != BaseEnd;
5183 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005184 // Virtual bases are handled below.
5185 if (Base->isVirtual())
5186 continue;
5187
Douglas Gregora6d69502010-07-02 23:41:54 +00005188 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005189 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005190 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5191 DeclareImplicitCopyConstructor(BaseClassDecl);
5192
Douglas Gregorcfe68222010-07-01 18:27:03 +00005193 HasConstCopyConstructor
5194 = BaseClassDecl->hasConstCopyConstructor(Context);
5195 }
5196
5197 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5198 BaseEnd = ClassDecl->vbases_end();
5199 HasConstCopyConstructor && Base != BaseEnd;
5200 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005201 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005202 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005203 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5204 DeclareImplicitCopyConstructor(BaseClassDecl);
5205
Douglas Gregor54be3392010-07-01 17:57:27 +00005206 HasConstCopyConstructor
5207 = BaseClassDecl->hasConstCopyConstructor(Context);
5208 }
5209
5210 // -- for all the nonstatic data members of X that are of a
5211 // class type M (or array thereof), each such class type
5212 // has a copy constructor whose first parameter is of type
5213 // const M& or const volatile M&.
5214 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5215 FieldEnd = ClassDecl->field_end();
5216 HasConstCopyConstructor && Field != FieldEnd;
5217 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005218 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005219 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005220 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005221 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005222 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5223 DeclareImplicitCopyConstructor(FieldClassDecl);
5224
Douglas Gregor54be3392010-07-01 17:57:27 +00005225 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005226 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005227 }
5228 }
5229
5230 // Otherwise, the implicitly declared copy constructor will have
5231 // the form
5232 //
5233 // X::X(X&)
5234 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5235 QualType ArgType = ClassType;
5236 if (HasConstCopyConstructor)
5237 ArgType = ArgType.withConst();
5238 ArgType = Context.getLValueReferenceType(ArgType);
5239
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005240 // C++ [except.spec]p14:
5241 // An implicitly declared special member function (Clause 12) shall have an
5242 // exception-specification. [...]
5243 ImplicitExceptionSpecification ExceptSpec(Context);
5244 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5245 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5246 BaseEnd = ClassDecl->bases_end();
5247 Base != BaseEnd;
5248 ++Base) {
5249 // Virtual bases are handled below.
5250 if (Base->isVirtual())
5251 continue;
5252
Douglas Gregora6d69502010-07-02 23:41:54 +00005253 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005254 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005255 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5256 DeclareImplicitCopyConstructor(BaseClassDecl);
5257
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005258 if (CXXConstructorDecl *CopyConstructor
5259 = BaseClassDecl->getCopyConstructor(Context, Quals))
5260 ExceptSpec.CalledDecl(CopyConstructor);
5261 }
5262 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5263 BaseEnd = ClassDecl->vbases_end();
5264 Base != BaseEnd;
5265 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005266 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005267 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005268 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5269 DeclareImplicitCopyConstructor(BaseClassDecl);
5270
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005271 if (CXXConstructorDecl *CopyConstructor
5272 = BaseClassDecl->getCopyConstructor(Context, Quals))
5273 ExceptSpec.CalledDecl(CopyConstructor);
5274 }
5275 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5276 FieldEnd = ClassDecl->field_end();
5277 Field != FieldEnd;
5278 ++Field) {
5279 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5280 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005281 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005282 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005283 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5284 DeclareImplicitCopyConstructor(FieldClassDecl);
5285
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005286 if (CXXConstructorDecl *CopyConstructor
5287 = FieldClassDecl->getCopyConstructor(Context, Quals))
5288 ExceptSpec.CalledDecl(CopyConstructor);
5289 }
5290 }
5291
Douglas Gregor54be3392010-07-01 17:57:27 +00005292 // An implicitly-declared copy constructor is an inline public
5293 // member of its class.
5294 DeclarationName Name
5295 = Context.DeclarationNames.getCXXConstructorName(
5296 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005297 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005298 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005299 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005300 Context.getFunctionType(Context.VoidTy,
5301 &ArgType, 1,
5302 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005303 ExceptSpec.hasExceptionSpecification(),
5304 ExceptSpec.hasAnyExceptionSpecification(),
5305 ExceptSpec.size(),
5306 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005307 FunctionType::ExtInfo()),
5308 /*TInfo=*/0,
5309 /*isExplicit=*/false,
5310 /*isInline=*/true,
5311 /*isImplicitlyDeclared=*/true);
5312 CopyConstructor->setAccess(AS_public);
5313 CopyConstructor->setImplicit();
5314 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5315
Douglas Gregora6d69502010-07-02 23:41:54 +00005316 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005317 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5318
Douglas Gregor54be3392010-07-01 17:57:27 +00005319 // Add the parameter to the constructor.
5320 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5321 ClassDecl->getLocation(),
5322 /*IdentifierInfo=*/0,
5323 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005324 SC_None,
5325 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005326 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005327 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005328 PushOnScopeChains(CopyConstructor, S, false);
5329 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005330
5331 return CopyConstructor;
5332}
5333
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005334void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5335 CXXConstructorDecl *CopyConstructor,
5336 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005337 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005338 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005339 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005340 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005341
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005342 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005343 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005344
Douglas Gregora57478e2010-05-01 15:04:51 +00005345 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005346 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005347
Douglas Gregor54818f02010-05-12 16:39:35 +00005348 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5349 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005350 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005351 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005352 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005353 } else {
5354 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5355 CopyConstructor->getLocation(),
5356 MultiStmtArg(*this, 0, 0),
5357 /*isStmtExpr=*/false)
5358 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005359 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005360
5361 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005362}
5363
John McCalldadc5752010-08-24 06:29:42 +00005364ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005365Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005366 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005367 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005368 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005369 unsigned ConstructKind,
5370 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005371 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005372
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005373 // C++0x [class.copy]p34:
5374 // When certain criteria are met, an implementation is allowed to
5375 // omit the copy/move construction of a class object, even if the
5376 // copy/move constructor and/or destructor for the object have
5377 // side effects. [...]
5378 // - when a temporary class object that has not been bound to a
5379 // reference (12.2) would be copied/moved to a class object
5380 // with the same cv-unqualified type, the copy/move operation
5381 // can be omitted by constructing the temporary object
5382 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005383 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5384 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005385 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005386 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005387 }
Mike Stump11289f42009-09-09 15:08:12 +00005388
5389 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005390 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005391 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005392}
5393
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005394/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5395/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005396ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005397Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5398 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005399 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005400 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005401 unsigned ConstructKind,
5402 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005403 unsigned NumExprs = ExprArgs.size();
5404 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005405
Douglas Gregor27381f32009-11-23 12:27:39 +00005406 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005407 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005408 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005409 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005410 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5411 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005412}
5413
Mike Stump11289f42009-09-09 15:08:12 +00005414bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005415 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005416 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005417 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005418 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005419 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005420 move(Exprs), false, CXXConstructExpr::CK_Complete,
5421 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005422 if (TempResult.isInvalid())
5423 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005424
Anders Carlsson6eb55572009-08-25 05:12:04 +00005425 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005426 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005427 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005428 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005429 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005430
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005431 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005432}
5433
John McCall03c48482010-02-02 09:10:11 +00005434void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005436 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005437 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005438 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005439 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005440 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005441 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005442 << VD->getDeclName()
5443 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005444
John McCall386dfc72010-09-18 05:25:11 +00005445 // TODO: this should be re-enabled for static locals by !CXAAtExit
5446 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005447 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005448 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005449}
5450
Mike Stump11289f42009-09-09 15:08:12 +00005451/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005452/// ActOnDeclarator, when a C++ direct initializer is present.
5453/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005454void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005455 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005456 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005457 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005458 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005459
5460 // If there is no declaration, there was an error parsing it. Just ignore
5461 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005462 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005463 return;
Mike Stump11289f42009-09-09 15:08:12 +00005464
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005465 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5466 if (!VDecl) {
5467 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5468 RealDecl->setInvalidDecl();
5469 return;
5470 }
5471
Douglas Gregor402250f2009-08-26 21:14:46 +00005472 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005473 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005474 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5475 //
5476 // Clients that want to distinguish between the two forms, can check for
5477 // direct initializer using VarDecl::hasCXXDirectInitializer().
5478 // A major benefit is that clients that don't particularly care about which
5479 // exactly form was it (like the CodeGen) can handle both cases without
5480 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005481
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005482 // C++ 8.5p11:
5483 // The form of initialization (using parentheses or '=') is generally
5484 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005485 // class type.
5486
Douglas Gregor50dc2192010-02-11 22:55:30 +00005487 if (!VDecl->getType()->isDependentType() &&
5488 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005489 diag::err_typecheck_decl_incomplete_type)) {
5490 VDecl->setInvalidDecl();
5491 return;
5492 }
5493
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005494 // The variable can not have an abstract class type.
5495 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5496 diag::err_abstract_type_in_decl,
5497 AbstractVariableType))
5498 VDecl->setInvalidDecl();
5499
Sebastian Redl5ca79842010-02-01 20:16:42 +00005500 const VarDecl *Def;
5501 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005502 Diag(VDecl->getLocation(), diag::err_redefinition)
5503 << VDecl->getDeclName();
5504 Diag(Def->getLocation(), diag::note_previous_definition);
5505 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005506 return;
5507 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005508
Douglas Gregorf0f83692010-08-24 05:27:49 +00005509 // C++ [class.static.data]p4
5510 // If a static data member is of const integral or const
5511 // enumeration type, its declaration in the class definition can
5512 // specify a constant-initializer which shall be an integral
5513 // constant expression (5.19). In that case, the member can appear
5514 // in integral constant expressions. The member shall still be
5515 // defined in a namespace scope if it is used in the program and the
5516 // namespace scope definition shall not contain an initializer.
5517 //
5518 // We already performed a redefinition check above, but for static
5519 // data members we also need to check whether there was an in-class
5520 // declaration with an initializer.
5521 const VarDecl* PrevInit = 0;
5522 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5523 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5524 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5525 return;
5526 }
5527
Douglas Gregor50dc2192010-02-11 22:55:30 +00005528 // If either the declaration has a dependent type or if any of the
5529 // expressions is type-dependent, we represent the initialization
5530 // via a ParenListExpr for later use during template instantiation.
5531 if (VDecl->getType()->isDependentType() ||
5532 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5533 // Let clients know that initialization was done with a direct initializer.
5534 VDecl->setCXXDirectInitializer(true);
5535
5536 // Store the initialization expressions as a ParenListExpr.
5537 unsigned NumExprs = Exprs.size();
5538 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5539 (Expr **)Exprs.release(),
5540 NumExprs, RParenLoc));
5541 return;
5542 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005543
5544 // Capture the variable that is being initialized and the style of
5545 // initialization.
5546 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5547
5548 // FIXME: Poor source location information.
5549 InitializationKind Kind
5550 = InitializationKind::CreateDirect(VDecl->getLocation(),
5551 LParenLoc, RParenLoc);
5552
5553 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005554 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005555 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005556 if (Result.isInvalid()) {
5557 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005558 return;
5559 }
John McCallacf0ee52010-10-08 02:01:28 +00005560
5561 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005562
John McCallb268a282010-08-23 23:25:46 +00005563 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregord5058122010-02-11 01:19:42 +00005564 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005565 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005566
John McCall8b0f4ff2010-08-02 21:13:48 +00005567 if (!VDecl->isInvalidDecl() &&
5568 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005569 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005570 !VDecl->getInit()->isConstantInitializer(Context,
5571 VDecl->getType()->isReferenceType()))
5572 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5573 << VDecl->getInit()->getSourceRange();
5574
John McCall03c48482010-02-02 09:10:11 +00005575 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5576 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005577}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005578
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005579/// \brief Given a constructor and the set of arguments provided for the
5580/// constructor, convert the arguments and add any required default arguments
5581/// to form a proper call to this constructor.
5582///
5583/// \returns true if an error occurred, false otherwise.
5584bool
5585Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5586 MultiExprArg ArgsPtr,
5587 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005588 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005589 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5590 unsigned NumArgs = ArgsPtr.size();
5591 Expr **Args = (Expr **)ArgsPtr.get();
5592
5593 const FunctionProtoType *Proto
5594 = Constructor->getType()->getAs<FunctionProtoType>();
5595 assert(Proto && "Constructor without a prototype?");
5596 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005597
5598 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005599 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005600 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005601 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005602 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005603
5604 VariadicCallType CallType =
5605 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5606 llvm::SmallVector<Expr *, 8> AllArgs;
5607 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5608 Proto, 0, Args, NumArgs, AllArgs,
5609 CallType);
5610 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5611 ConvertedArgs.push_back(AllArgs[i]);
5612 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005613}
5614
Anders Carlssone363c8e2009-12-12 00:32:00 +00005615static inline bool
5616CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5617 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005618 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005619 if (isa<NamespaceDecl>(DC)) {
5620 return SemaRef.Diag(FnDecl->getLocation(),
5621 diag::err_operator_new_delete_declared_in_namespace)
5622 << FnDecl->getDeclName();
5623 }
5624
5625 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005626 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005627 return SemaRef.Diag(FnDecl->getLocation(),
5628 diag::err_operator_new_delete_declared_static)
5629 << FnDecl->getDeclName();
5630 }
5631
Anders Carlsson60659a82009-12-12 02:43:16 +00005632 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005633}
5634
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005635static inline bool
5636CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5637 CanQualType ExpectedResultType,
5638 CanQualType ExpectedFirstParamType,
5639 unsigned DependentParamTypeDiag,
5640 unsigned InvalidParamTypeDiag) {
5641 QualType ResultType =
5642 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5643
5644 // Check that the result type is not dependent.
5645 if (ResultType->isDependentType())
5646 return SemaRef.Diag(FnDecl->getLocation(),
5647 diag::err_operator_new_delete_dependent_result_type)
5648 << FnDecl->getDeclName() << ExpectedResultType;
5649
5650 // Check that the result type is what we expect.
5651 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5652 return SemaRef.Diag(FnDecl->getLocation(),
5653 diag::err_operator_new_delete_invalid_result_type)
5654 << FnDecl->getDeclName() << ExpectedResultType;
5655
5656 // A function template must have at least 2 parameters.
5657 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5658 return SemaRef.Diag(FnDecl->getLocation(),
5659 diag::err_operator_new_delete_template_too_few_parameters)
5660 << FnDecl->getDeclName();
5661
5662 // The function decl must have at least 1 parameter.
5663 if (FnDecl->getNumParams() == 0)
5664 return SemaRef.Diag(FnDecl->getLocation(),
5665 diag::err_operator_new_delete_too_few_parameters)
5666 << FnDecl->getDeclName();
5667
5668 // Check the the first parameter type is not dependent.
5669 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5670 if (FirstParamType->isDependentType())
5671 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5672 << FnDecl->getDeclName() << ExpectedFirstParamType;
5673
5674 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005675 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005676 ExpectedFirstParamType)
5677 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5678 << FnDecl->getDeclName() << ExpectedFirstParamType;
5679
5680 return false;
5681}
5682
Anders Carlsson12308f42009-12-11 23:23:22 +00005683static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005684CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005685 // C++ [basic.stc.dynamic.allocation]p1:
5686 // A program is ill-formed if an allocation function is declared in a
5687 // namespace scope other than global scope or declared static in global
5688 // scope.
5689 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5690 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005691
5692 CanQualType SizeTy =
5693 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5694
5695 // C++ [basic.stc.dynamic.allocation]p1:
5696 // The return type shall be void*. The first parameter shall have type
5697 // std::size_t.
5698 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5699 SizeTy,
5700 diag::err_operator_new_dependent_param_type,
5701 diag::err_operator_new_param_type))
5702 return true;
5703
5704 // C++ [basic.stc.dynamic.allocation]p1:
5705 // The first parameter shall not have an associated default argument.
5706 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005707 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005708 diag::err_operator_new_default_arg)
5709 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5710
5711 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005712}
5713
5714static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005715CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5716 // C++ [basic.stc.dynamic.deallocation]p1:
5717 // A program is ill-formed if deallocation functions are declared in a
5718 // namespace scope other than global scope or declared static in global
5719 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005720 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5721 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005722
5723 // C++ [basic.stc.dynamic.deallocation]p2:
5724 // Each deallocation function shall return void and its first parameter
5725 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005726 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5727 SemaRef.Context.VoidPtrTy,
5728 diag::err_operator_delete_dependent_param_type,
5729 diag::err_operator_delete_param_type))
5730 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005731
Anders Carlsson12308f42009-12-11 23:23:22 +00005732 return false;
5733}
5734
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005735/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5736/// of this overloaded operator is well-formed. If so, returns false;
5737/// otherwise, emits appropriate diagnostics and returns true.
5738bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005739 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005740 "Expected an overloaded operator declaration");
5741
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005742 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5743
Mike Stump11289f42009-09-09 15:08:12 +00005744 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005745 // The allocation and deallocation functions, operator new,
5746 // operator new[], operator delete and operator delete[], are
5747 // described completely in 3.7.3. The attributes and restrictions
5748 // found in the rest of this subclause do not apply to them unless
5749 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005750 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005751 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005752
Anders Carlsson22f443f2009-12-12 00:26:23 +00005753 if (Op == OO_New || Op == OO_Array_New)
5754 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005755
5756 // C++ [over.oper]p6:
5757 // An operator function shall either be a non-static member
5758 // function or be a non-member function and have at least one
5759 // parameter whose type is a class, a reference to a class, an
5760 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005761 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5762 if (MethodDecl->isStatic())
5763 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005764 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005765 } else {
5766 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005767 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5768 ParamEnd = FnDecl->param_end();
5769 Param != ParamEnd; ++Param) {
5770 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005771 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5772 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005773 ClassOrEnumParam = true;
5774 break;
5775 }
5776 }
5777
Douglas Gregord69246b2008-11-17 16:14:12 +00005778 if (!ClassOrEnumParam)
5779 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005780 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005781 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005782 }
5783
5784 // C++ [over.oper]p8:
5785 // An operator function cannot have default arguments (8.3.6),
5786 // except where explicitly stated below.
5787 //
Mike Stump11289f42009-09-09 15:08:12 +00005788 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005789 // (C++ [over.call]p1).
5790 if (Op != OO_Call) {
5791 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5792 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005793 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005794 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005795 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005796 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005797 }
5798 }
5799
Douglas Gregor6cf08062008-11-10 13:38:07 +00005800 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5801 { false, false, false }
5802#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5803 , { Unary, Binary, MemberOnly }
5804#include "clang/Basic/OperatorKinds.def"
5805 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005806
Douglas Gregor6cf08062008-11-10 13:38:07 +00005807 bool CanBeUnaryOperator = OperatorUses[Op][0];
5808 bool CanBeBinaryOperator = OperatorUses[Op][1];
5809 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005810
5811 // C++ [over.oper]p8:
5812 // [...] Operator functions cannot have more or fewer parameters
5813 // than the number required for the corresponding operator, as
5814 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005815 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005816 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005817 if (Op != OO_Call &&
5818 ((NumParams == 1 && !CanBeUnaryOperator) ||
5819 (NumParams == 2 && !CanBeBinaryOperator) ||
5820 (NumParams < 1) || (NumParams > 2))) {
5821 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005822 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005823 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005824 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005825 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005826 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005827 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005828 assert(CanBeBinaryOperator &&
5829 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005830 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005831 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005832
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005833 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005834 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005835 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005836
Douglas Gregord69246b2008-11-17 16:14:12 +00005837 // Overloaded operators other than operator() cannot be variadic.
5838 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005839 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005840 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005841 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005842 }
5843
5844 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005845 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5846 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005847 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005848 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005849 }
5850
5851 // C++ [over.inc]p1:
5852 // The user-defined function called operator++ implements the
5853 // prefix and postfix ++ operator. If this function is a member
5854 // function with no parameters, or a non-member function with one
5855 // parameter of class or enumeration type, it defines the prefix
5856 // increment operator ++ for objects of that type. If the function
5857 // is a member function with one parameter (which shall be of type
5858 // int) or a non-member function with two parameters (the second
5859 // of which shall be of type int), it defines the postfix
5860 // increment operator ++ for objects of that type.
5861 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5862 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5863 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005864 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005865 ParamIsInt = BT->getKind() == BuiltinType::Int;
5866
Chris Lattner2b786902008-11-21 07:50:02 +00005867 if (!ParamIsInt)
5868 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005869 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005870 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005871 }
5872
Douglas Gregord69246b2008-11-17 16:14:12 +00005873 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005874}
Chris Lattner3b024a32008-12-17 07:09:26 +00005875
Alexis Huntc88db062010-01-13 09:01:02 +00005876/// CheckLiteralOperatorDeclaration - Check whether the declaration
5877/// of this literal operator function is well-formed. If so, returns
5878/// false; otherwise, emits appropriate diagnostics and returns true.
5879bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5880 DeclContext *DC = FnDecl->getDeclContext();
5881 Decl::Kind Kind = DC->getDeclKind();
5882 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5883 Kind != Decl::LinkageSpec) {
5884 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5885 << FnDecl->getDeclName();
5886 return true;
5887 }
5888
5889 bool Valid = false;
5890
Alexis Hunt7dd26172010-04-07 23:11:06 +00005891 // template <char...> type operator "" name() is the only valid template
5892 // signature, and the only valid signature with no parameters.
5893 if (FnDecl->param_size() == 0) {
5894 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5895 // Must have only one template parameter
5896 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5897 if (Params->size() == 1) {
5898 NonTypeTemplateParmDecl *PmDecl =
5899 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005900
Alexis Hunt7dd26172010-04-07 23:11:06 +00005901 // The template parameter must be a char parameter pack.
5902 // FIXME: This test will always fail because non-type parameter packs
5903 // have not been implemented.
5904 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5905 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5906 Valid = true;
5907 }
5908 }
5909 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005910 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005911 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5912
Alexis Huntc88db062010-01-13 09:01:02 +00005913 QualType T = (*Param)->getType();
5914
Alexis Hunt079a6f72010-04-07 22:57:35 +00005915 // unsigned long long int, long double, and any character type are allowed
5916 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005917 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5918 Context.hasSameType(T, Context.LongDoubleTy) ||
5919 Context.hasSameType(T, Context.CharTy) ||
5920 Context.hasSameType(T, Context.WCharTy) ||
5921 Context.hasSameType(T, Context.Char16Ty) ||
5922 Context.hasSameType(T, Context.Char32Ty)) {
5923 if (++Param == FnDecl->param_end())
5924 Valid = true;
5925 goto FinishedParams;
5926 }
5927
Alexis Hunt079a6f72010-04-07 22:57:35 +00005928 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005929 const PointerType *PT = T->getAs<PointerType>();
5930 if (!PT)
5931 goto FinishedParams;
5932 T = PT->getPointeeType();
5933 if (!T.isConstQualified())
5934 goto FinishedParams;
5935 T = T.getUnqualifiedType();
5936
5937 // Move on to the second parameter;
5938 ++Param;
5939
5940 // If there is no second parameter, the first must be a const char *
5941 if (Param == FnDecl->param_end()) {
5942 if (Context.hasSameType(T, Context.CharTy))
5943 Valid = true;
5944 goto FinishedParams;
5945 }
5946
5947 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5948 // are allowed as the first parameter to a two-parameter function
5949 if (!(Context.hasSameType(T, Context.CharTy) ||
5950 Context.hasSameType(T, Context.WCharTy) ||
5951 Context.hasSameType(T, Context.Char16Ty) ||
5952 Context.hasSameType(T, Context.Char32Ty)))
5953 goto FinishedParams;
5954
5955 // The second and final parameter must be an std::size_t
5956 T = (*Param)->getType().getUnqualifiedType();
5957 if (Context.hasSameType(T, Context.getSizeType()) &&
5958 ++Param == FnDecl->param_end())
5959 Valid = true;
5960 }
5961
5962 // FIXME: This diagnostic is absolutely terrible.
5963FinishedParams:
5964 if (!Valid) {
5965 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5966 << FnDecl->getDeclName();
5967 return true;
5968 }
5969
5970 return false;
5971}
5972
Douglas Gregor07665a62009-01-05 19:45:36 +00005973/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5974/// linkage specification, including the language and (if present)
5975/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5976/// the location of the language string literal, which is provided
5977/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5978/// the '{' brace. Otherwise, this linkage specification does not
5979/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00005980Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5981 SourceLocation LangLoc,
5982 llvm::StringRef Lang,
5983 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005984 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005985 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005986 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005987 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005988 Language = LinkageSpecDecl::lang_cxx;
5989 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005990 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00005991 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00005992 }
Mike Stump11289f42009-09-09 15:08:12 +00005993
Chris Lattner438e5012008-12-17 07:13:27 +00005994 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005995
Douglas Gregor07665a62009-01-05 19:45:36 +00005996 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005997 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005998 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005999 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006000 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006001 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006002}
6003
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006004/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006005/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6006/// valid, it's the position of the closing '}' brace in a linkage
6007/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006008Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6009 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006010 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006011 if (LinkageSpec)
6012 PopDeclContext();
6013 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006014}
6015
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006016/// \brief Perform semantic analysis for the variable declaration that
6017/// occurs within a C++ catch clause, returning the newly-created
6018/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006019VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006020 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006021 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006022 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006023 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006024 QualType ExDeclType = TInfo->getType();
6025
Sebastian Redl54c04d42008-12-22 19:15:10 +00006026 // Arrays and functions decay.
6027 if (ExDeclType->isArrayType())
6028 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6029 else if (ExDeclType->isFunctionType())
6030 ExDeclType = Context.getPointerType(ExDeclType);
6031
6032 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6033 // The exception-declaration shall not denote a pointer or reference to an
6034 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006035 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006036 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006037 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006038 Invalid = true;
6039 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006040
Douglas Gregor104ee002010-03-08 01:47:36 +00006041 // GCC allows catching pointers and references to incomplete types
6042 // as an extension; so do we, but we warn by default.
6043
Sebastian Redl54c04d42008-12-22 19:15:10 +00006044 QualType BaseType = ExDeclType;
6045 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006046 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006047 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006048 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006049 BaseType = Ptr->getPointeeType();
6050 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006051 DK = diag::ext_catch_incomplete_ptr;
6052 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006053 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006054 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006055 BaseType = Ref->getPointeeType();
6056 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006057 DK = diag::ext_catch_incomplete_ref;
6058 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006059 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006060 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006061 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6062 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006063 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006064
Mike Stump11289f42009-09-09 15:08:12 +00006065 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006066 RequireNonAbstractType(Loc, ExDeclType,
6067 diag::err_abstract_type_in_decl,
6068 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006069 Invalid = true;
6070
John McCall2ca705e2010-07-24 00:37:23 +00006071 // Only the non-fragile NeXT runtime currently supports C++ catches
6072 // of ObjC types, and no runtime supports catching ObjC types by value.
6073 if (!Invalid && getLangOptions().ObjC1) {
6074 QualType T = ExDeclType;
6075 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6076 T = RT->getPointeeType();
6077
6078 if (T->isObjCObjectType()) {
6079 Diag(Loc, diag::err_objc_object_catch);
6080 Invalid = true;
6081 } else if (T->isObjCObjectPointerType()) {
6082 if (!getLangOptions().NeXTRuntime) {
6083 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6084 Invalid = true;
6085 } else if (!getLangOptions().ObjCNonFragileABI) {
6086 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6087 Invalid = true;
6088 }
6089 }
6090 }
6091
Mike Stump11289f42009-09-09 15:08:12 +00006092 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006093 Name, ExDeclType, TInfo, SC_None,
6094 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006095 ExDecl->setExceptionVariable(true);
6096
Douglas Gregor6de584c2010-03-05 23:38:39 +00006097 if (!Invalid) {
6098 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6099 // C++ [except.handle]p16:
6100 // The object declared in an exception-declaration or, if the
6101 // exception-declaration does not specify a name, a temporary (12.2) is
6102 // copy-initialized (8.5) from the exception object. [...]
6103 // The object is destroyed when the handler exits, after the destruction
6104 // of any automatic objects initialized within the handler.
6105 //
6106 // We just pretend to initialize the object with itself, then make sure
6107 // it can be destroyed later.
6108 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6109 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6110 Loc, ExDeclType, 0);
6111 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6112 SourceLocation());
6113 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006114 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006115 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006116 if (Result.isInvalid())
6117 Invalid = true;
6118 else
6119 FinalizeVarWithDestructor(ExDecl, RecordTy);
6120 }
6121 }
6122
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006123 if (Invalid)
6124 ExDecl->setInvalidDecl();
6125
6126 return ExDecl;
6127}
6128
6129/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6130/// handler.
John McCall48871652010-08-21 09:40:31 +00006131Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006132 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6133 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006134
6135 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006136 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006137 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006138 LookupOrdinaryName,
6139 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006140 // The scope should be freshly made just for us. There is just no way
6141 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006142 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006143 if (PrevDecl->isTemplateParameter()) {
6144 // Maybe we will complain about the shadowed template parameter.
6145 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006146 }
6147 }
6148
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006149 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006150 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6151 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006152 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006153 }
6154
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006155 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006156 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006157 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006158
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006159 if (Invalid)
6160 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006161
Sebastian Redl54c04d42008-12-22 19:15:10 +00006162 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006163 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006164 PushOnScopeChains(ExDecl, S);
6165 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006166 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006167
Douglas Gregor758a8692009-06-17 21:51:59 +00006168 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006169 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006170}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006171
John McCall48871652010-08-21 09:40:31 +00006172Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006173 Expr *AssertExpr,
6174 Expr *AssertMessageExpr_) {
6175 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006176
Anders Carlsson54b26982009-03-14 00:33:21 +00006177 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6178 llvm::APSInt Value(32);
6179 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6180 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6181 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006182 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006183 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006184
Anders Carlsson54b26982009-03-14 00:33:21 +00006185 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006186 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006187 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006188 }
6189 }
Mike Stump11289f42009-09-09 15:08:12 +00006190
Mike Stump11289f42009-09-09 15:08:12 +00006191 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006192 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006193
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006194 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006195 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006196}
Sebastian Redlf769df52009-03-24 22:27:57 +00006197
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006198/// \brief Perform semantic analysis of the given friend type declaration.
6199///
6200/// \returns A friend declaration that.
6201FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6202 TypeSourceInfo *TSInfo) {
6203 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6204
6205 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006206 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006207
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006208 if (!getLangOptions().CPlusPlus0x) {
6209 // C++03 [class.friend]p2:
6210 // An elaborated-type-specifier shall be used in a friend declaration
6211 // for a class.*
6212 //
6213 // * The class-key of the elaborated-type-specifier is required.
6214 if (!ActiveTemplateInstantiations.empty()) {
6215 // Do not complain about the form of friend template types during
6216 // template instantiation; we will already have complained when the
6217 // template was declared.
6218 } else if (!T->isElaboratedTypeSpecifier()) {
6219 // If we evaluated the type to a record type, suggest putting
6220 // a tag in front.
6221 if (const RecordType *RT = T->getAs<RecordType>()) {
6222 RecordDecl *RD = RT->getDecl();
6223
6224 std::string InsertionText = std::string(" ") + RD->getKindName();
6225
6226 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6227 << (unsigned) RD->getTagKind()
6228 << T
6229 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6230 InsertionText);
6231 } else {
6232 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6233 << T
6234 << SourceRange(FriendLoc, TypeRange.getEnd());
6235 }
6236 } else if (T->getAs<EnumType>()) {
6237 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006238 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006239 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006240 }
6241 }
6242
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006243 // C++0x [class.friend]p3:
6244 // If the type specifier in a friend declaration designates a (possibly
6245 // cv-qualified) class type, that class is declared as a friend; otherwise,
6246 // the friend declaration is ignored.
6247
6248 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6249 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006250
6251 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6252}
6253
John McCallace48cd2010-10-19 01:40:49 +00006254/// Handle a friend tag declaration where the scope specifier was
6255/// templated.
6256Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6257 unsigned TagSpec, SourceLocation TagLoc,
6258 CXXScopeSpec &SS,
6259 IdentifierInfo *Name, SourceLocation NameLoc,
6260 AttributeList *Attr,
6261 MultiTemplateParamsArg TempParamLists) {
6262 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6263
6264 bool isExplicitSpecialization = false;
6265 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6266 bool Invalid = false;
6267
6268 if (TemplateParameterList *TemplateParams
6269 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6270 TempParamLists.get(),
6271 TempParamLists.size(),
6272 /*friend*/ true,
6273 isExplicitSpecialization,
6274 Invalid)) {
6275 --NumMatchedTemplateParamLists;
6276
6277 if (TemplateParams->size() > 0) {
6278 // This is a declaration of a class template.
6279 if (Invalid)
6280 return 0;
6281
6282 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6283 SS, Name, NameLoc, Attr,
6284 TemplateParams, AS_public).take();
6285 } else {
6286 // The "template<>" header is extraneous.
6287 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6288 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6289 isExplicitSpecialization = true;
6290 }
6291 }
6292
6293 if (Invalid) return 0;
6294
6295 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6296
6297 bool isAllExplicitSpecializations = true;
6298 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6299 if (TempParamLists.get()[I]->size()) {
6300 isAllExplicitSpecializations = false;
6301 break;
6302 }
6303 }
6304
6305 // FIXME: don't ignore attributes.
6306
6307 // If it's explicit specializations all the way down, just forget
6308 // about the template header and build an appropriate non-templated
6309 // friend. TODO: for source fidelity, remember the headers.
6310 if (isAllExplicitSpecializations) {
6311 ElaboratedTypeKeyword Keyword
6312 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6313 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6314 TagLoc, SS.getRange(), NameLoc);
6315 if (T.isNull())
6316 return 0;
6317
6318 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6319 if (isa<DependentNameType>(T)) {
6320 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6321 TL.setKeywordLoc(TagLoc);
6322 TL.setQualifierRange(SS.getRange());
6323 TL.setNameLoc(NameLoc);
6324 } else {
6325 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6326 TL.setKeywordLoc(TagLoc);
6327 TL.setQualifierRange(SS.getRange());
6328 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6329 }
6330
6331 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6332 TSI, FriendLoc);
6333 Friend->setAccess(AS_public);
6334 CurContext->addDecl(Friend);
6335 return Friend;
6336 }
6337
6338 // Handle the case of a templated-scope friend class. e.g.
6339 // template <class T> class A<T>::B;
6340 // FIXME: we don't support these right now.
6341 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6342 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6343 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6344 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6345 TL.setKeywordLoc(TagLoc);
6346 TL.setQualifierRange(SS.getRange());
6347 TL.setNameLoc(NameLoc);
6348
6349 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6350 TSI, FriendLoc);
6351 Friend->setAccess(AS_public);
6352 Friend->setUnsupportedFriend(true);
6353 CurContext->addDecl(Friend);
6354 return Friend;
6355}
6356
6357
John McCall11083da2009-09-16 22:47:08 +00006358/// Handle a friend type declaration. This works in tandem with
6359/// ActOnTag.
6360///
6361/// Notes on friend class templates:
6362///
6363/// We generally treat friend class declarations as if they were
6364/// declaring a class. So, for example, the elaborated type specifier
6365/// in a friend declaration is required to obey the restrictions of a
6366/// class-head (i.e. no typedefs in the scope chain), template
6367/// parameters are required to match up with simple template-ids, &c.
6368/// However, unlike when declaring a template specialization, it's
6369/// okay to refer to a template specialization without an empty
6370/// template parameter declaration, e.g.
6371/// friend class A<T>::B<unsigned>;
6372/// We permit this as a special case; if there are any template
6373/// parameters present at all, require proper matching, i.e.
6374/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006375Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006376 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006377 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006378
6379 assert(DS.isFriendSpecified());
6380 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6381
John McCall11083da2009-09-16 22:47:08 +00006382 // Try to convert the decl specifier to a type. This works for
6383 // friend templates because ActOnTag never produces a ClassTemplateDecl
6384 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006385 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006386 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6387 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006388 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006389 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006390
John McCall11083da2009-09-16 22:47:08 +00006391 // This is definitely an error in C++98. It's probably meant to
6392 // be forbidden in C++0x, too, but the specification is just
6393 // poorly written.
6394 //
6395 // The problem is with declarations like the following:
6396 // template <T> friend A<T>::foo;
6397 // where deciding whether a class C is a friend or not now hinges
6398 // on whether there exists an instantiation of A that causes
6399 // 'foo' to equal C. There are restrictions on class-heads
6400 // (which we declare (by fiat) elaborated friend declarations to
6401 // be) that makes this tractable.
6402 //
6403 // FIXME: handle "template <> friend class A<T>;", which
6404 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006405 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006406 Diag(Loc, diag::err_tagless_friend_type_template)
6407 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006408 return 0;
John McCall11083da2009-09-16 22:47:08 +00006409 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006410
John McCallaa74a0c2009-08-28 07:59:38 +00006411 // C++98 [class.friend]p1: A friend of a class is a function
6412 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006413 // This is fixed in DR77, which just barely didn't make the C++03
6414 // deadline. It's also a very silly restriction that seriously
6415 // affects inner classes and which nobody else seems to implement;
6416 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006417 //
6418 // But note that we could warn about it: it's always useless to
6419 // friend one of your own members (it's not, however, worthless to
6420 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006421
John McCall11083da2009-09-16 22:47:08 +00006422 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006423 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006424 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006425 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006426 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006427 TSI,
John McCall11083da2009-09-16 22:47:08 +00006428 DS.getFriendSpecLoc());
6429 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006430 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6431
6432 if (!D)
John McCall48871652010-08-21 09:40:31 +00006433 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006434
John McCall11083da2009-09-16 22:47:08 +00006435 D->setAccess(AS_public);
6436 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006437
John McCall48871652010-08-21 09:40:31 +00006438 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006439}
6440
John McCallde3fd222010-10-12 23:13:28 +00006441Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6442 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006443 const DeclSpec &DS = D.getDeclSpec();
6444
6445 assert(DS.isFriendSpecified());
6446 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6447
6448 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006449 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6450 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006451
6452 // C++ [class.friend]p1
6453 // A friend of a class is a function or class....
6454 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006455 // It *doesn't* see through dependent types, which is correct
6456 // according to [temp.arg.type]p3:
6457 // If a declaration acquires a function type through a
6458 // type dependent on a template-parameter and this causes
6459 // a declaration that does not use the syntactic form of a
6460 // function declarator to have a function type, the program
6461 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006462 if (!T->isFunctionType()) {
6463 Diag(Loc, diag::err_unexpected_friend);
6464
6465 // It might be worthwhile to try to recover by creating an
6466 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006467 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006468 }
6469
6470 // C++ [namespace.memdef]p3
6471 // - If a friend declaration in a non-local class first declares a
6472 // class or function, the friend class or function is a member
6473 // of the innermost enclosing namespace.
6474 // - The name of the friend is not found by simple name lookup
6475 // until a matching declaration is provided in that namespace
6476 // scope (either before or after the class declaration granting
6477 // friendship).
6478 // - If a friend function is called, its name may be found by the
6479 // name lookup that considers functions from namespaces and
6480 // classes associated with the types of the function arguments.
6481 // - When looking for a prior declaration of a class or a function
6482 // declared as a friend, scopes outside the innermost enclosing
6483 // namespace scope are not considered.
6484
John McCallde3fd222010-10-12 23:13:28 +00006485 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006486 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6487 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006488 assert(Name);
6489
John McCall07e91c02009-08-06 02:15:43 +00006490 // The context we found the declaration in, or in which we should
6491 // create the declaration.
6492 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006493 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006494 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006495 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006496
John McCallde3fd222010-10-12 23:13:28 +00006497 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006498
John McCallde3fd222010-10-12 23:13:28 +00006499 // There are four cases here.
6500 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006501 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006502 // there as appropriate.
6503 // Recover from invalid scope qualifiers as if they just weren't there.
6504 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006505 // C++0x [namespace.memdef]p3:
6506 // If the name in a friend declaration is neither qualified nor
6507 // a template-id and the declaration is a function or an
6508 // elaborated-type-specifier, the lookup to determine whether
6509 // the entity has been previously declared shall not consider
6510 // any scopes outside the innermost enclosing namespace.
6511 // C++0x [class.friend]p11:
6512 // If a friend declaration appears in a local class and the name
6513 // specified is an unqualified name, a prior declaration is
6514 // looked up without considering scopes that are outside the
6515 // innermost enclosing non-class scope. For a friend function
6516 // declaration, if there is no prior declaration, the program is
6517 // ill-formed.
6518 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006519 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006520
John McCallf7cfb222010-10-13 05:45:15 +00006521 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006522 DC = CurContext;
6523 while (true) {
6524 // Skip class contexts. If someone can cite chapter and verse
6525 // for this behavior, that would be nice --- it's what GCC and
6526 // EDG do, and it seems like a reasonable intent, but the spec
6527 // really only says that checks for unqualified existing
6528 // declarations should stop at the nearest enclosing namespace,
6529 // not that they should only consider the nearest enclosing
6530 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006531 while (DC->isRecord())
6532 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006533
John McCall1f82f242009-11-18 22:49:29 +00006534 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006535
6536 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006537 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006538 break;
John McCallf7cfb222010-10-13 05:45:15 +00006539
John McCallf4776592010-10-14 22:22:28 +00006540 if (isTemplateId) {
6541 if (isa<TranslationUnitDecl>(DC)) break;
6542 } else {
6543 if (DC->isFileContext()) break;
6544 }
John McCall07e91c02009-08-06 02:15:43 +00006545 DC = DC->getParent();
6546 }
6547
6548 // C++ [class.friend]p1: A friend of a class is a function or
6549 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006550 // C++0x changes this for both friend types and functions.
6551 // Most C++ 98 compilers do seem to give an error here, so
6552 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006553 if (!Previous.empty() && DC->Equals(CurContext)
6554 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006555 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006556
John McCallccbc0322010-10-13 06:22:15 +00006557 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006558
John McCallde3fd222010-10-12 23:13:28 +00006559 // - There's a non-dependent scope specifier, in which case we
6560 // compute it and do a previous lookup there for a function
6561 // or function template.
6562 } else if (!SS.getScopeRep()->isDependent()) {
6563 DC = computeDeclContext(SS);
6564 if (!DC) return 0;
6565
6566 if (RequireCompleteDeclContext(SS, DC)) return 0;
6567
6568 LookupQualifiedName(Previous, DC);
6569
6570 // Ignore things found implicitly in the wrong scope.
6571 // TODO: better diagnostics for this case. Suggesting the right
6572 // qualified scope would be nice...
6573 LookupResult::Filter F = Previous.makeFilter();
6574 while (F.hasNext()) {
6575 NamedDecl *D = F.next();
6576 if (!DC->InEnclosingNamespaceSetOf(
6577 D->getDeclContext()->getRedeclContext()))
6578 F.erase();
6579 }
6580 F.done();
6581
6582 if (Previous.empty()) {
6583 D.setInvalidType();
6584 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6585 return 0;
6586 }
6587
6588 // C++ [class.friend]p1: A friend of a class is a function or
6589 // class that is not a member of the class . . .
6590 if (DC->Equals(CurContext))
6591 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6592
6593 // - There's a scope specifier that does not match any template
6594 // parameter lists, in which case we use some arbitrary context,
6595 // create a method or method template, and wait for instantiation.
6596 // - There's a scope specifier that does match some template
6597 // parameter lists, which we don't handle right now.
6598 } else {
6599 DC = CurContext;
6600 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006601 }
6602
John McCallf7cfb222010-10-13 05:45:15 +00006603 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006604 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006605 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6606 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6607 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006608 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006609 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6610 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006611 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006612 }
John McCall07e91c02009-08-06 02:15:43 +00006613 }
6614
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006615 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006616 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006617 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006618 IsDefinition,
6619 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006620 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006621
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006622 assert(ND->getDeclContext() == DC);
6623 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006624
John McCall759e32b2009-08-31 22:39:49 +00006625 // Add the function declaration to the appropriate lookup tables,
6626 // adjusting the redeclarations list as necessary. We don't
6627 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006628 //
John McCall759e32b2009-08-31 22:39:49 +00006629 // Also update the scope-based lookup if the target context's
6630 // lookup context is in lexical scope.
6631 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006632 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006633 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006634 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006635 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006636 }
John McCallaa74a0c2009-08-28 07:59:38 +00006637
6638 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006639 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006640 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006641 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006642 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006643
John McCallde3fd222010-10-12 23:13:28 +00006644 if (ND->isInvalidDecl())
6645 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006646 else {
6647 FunctionDecl *FD;
6648 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6649 FD = FTD->getTemplatedDecl();
6650 else
6651 FD = cast<FunctionDecl>(ND);
6652
6653 // Mark templated-scope function declarations as unsupported.
6654 if (FD->getNumTemplateParameterLists())
6655 FrD->setUnsupportedFriend(true);
6656 }
John McCallde3fd222010-10-12 23:13:28 +00006657
John McCall48871652010-08-21 09:40:31 +00006658 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006659}
6660
John McCall48871652010-08-21 09:40:31 +00006661void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6662 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006663
Sebastian Redlf769df52009-03-24 22:27:57 +00006664 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6665 if (!Fn) {
6666 Diag(DelLoc, diag::err_deleted_non_function);
6667 return;
6668 }
6669 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6670 Diag(DelLoc, diag::err_deleted_decl_not_first);
6671 Diag(Prev->getLocation(), diag::note_previous_declaration);
6672 // If the declaration wasn't the first, we delete the function anyway for
6673 // recovery.
6674 }
6675 Fn->setDeleted();
6676}
Sebastian Redl4c018662009-04-27 21:33:24 +00006677
6678static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6679 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6680 ++CI) {
6681 Stmt *SubStmt = *CI;
6682 if (!SubStmt)
6683 continue;
6684 if (isa<ReturnStmt>(SubStmt))
6685 Self.Diag(SubStmt->getSourceRange().getBegin(),
6686 diag::err_return_in_constructor_handler);
6687 if (!isa<Expr>(SubStmt))
6688 SearchForReturnInStmt(Self, SubStmt);
6689 }
6690}
6691
6692void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6693 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6694 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6695 SearchForReturnInStmt(*this, Handler);
6696 }
6697}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006698
Mike Stump11289f42009-09-09 15:08:12 +00006699bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006700 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006701 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6702 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006703
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006704 if (Context.hasSameType(NewTy, OldTy) ||
6705 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006706 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006707
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006708 // Check if the return types are covariant
6709 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006710
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006711 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006712 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6713 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006714 NewClassTy = NewPT->getPointeeType();
6715 OldClassTy = OldPT->getPointeeType();
6716 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006717 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6718 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6719 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6720 NewClassTy = NewRT->getPointeeType();
6721 OldClassTy = OldRT->getPointeeType();
6722 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006723 }
6724 }
Mike Stump11289f42009-09-09 15:08:12 +00006725
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006726 // The return types aren't either both pointers or references to a class type.
6727 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006728 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006729 diag::err_different_return_type_for_overriding_virtual_function)
6730 << New->getDeclName() << NewTy << OldTy;
6731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006732
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006733 return true;
6734 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006735
Anders Carlssone60365b2009-12-31 18:34:24 +00006736 // C++ [class.virtual]p6:
6737 // If the return type of D::f differs from the return type of B::f, the
6738 // class type in the return type of D::f shall be complete at the point of
6739 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006740 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6741 if (!RT->isBeingDefined() &&
6742 RequireCompleteType(New->getLocation(), NewClassTy,
6743 PDiag(diag::err_covariant_return_incomplete)
6744 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006745 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006746 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006747
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006748 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006749 // Check if the new class derives from the old class.
6750 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6751 Diag(New->getLocation(),
6752 diag::err_covariant_return_not_derived)
6753 << New->getDeclName() << NewTy << OldTy;
6754 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6755 return true;
6756 }
Mike Stump11289f42009-09-09 15:08:12 +00006757
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006758 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006759 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006760 diag::err_covariant_return_inaccessible_base,
6761 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6762 // FIXME: Should this point to the return type?
6763 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006764 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6765 return true;
6766 }
6767 }
Mike Stump11289f42009-09-09 15:08:12 +00006768
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006769 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006770 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006771 Diag(New->getLocation(),
6772 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006773 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006774 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6775 return true;
6776 };
Mike Stump11289f42009-09-09 15:08:12 +00006777
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006778
6779 // The new class type must have the same or less qualifiers as the old type.
6780 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6781 Diag(New->getLocation(),
6782 diag::err_covariant_return_type_class_type_more_qualified)
6783 << New->getDeclName() << NewTy << OldTy;
6784 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6785 return true;
6786 };
Mike Stump11289f42009-09-09 15:08:12 +00006787
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006788 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006789}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006790
Alexis Hunt96d5c762009-11-21 08:43:09 +00006791bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6792 const CXXMethodDecl *Old)
6793{
6794 if (Old->hasAttr<FinalAttr>()) {
6795 Diag(New->getLocation(), diag::err_final_function_overridden)
6796 << New->getDeclName();
6797 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6798 return true;
6799 }
6800
6801 return false;
6802}
6803
Douglas Gregor21920e372009-12-01 17:24:26 +00006804/// \brief Mark the given method pure.
6805///
6806/// \param Method the method to be marked pure.
6807///
6808/// \param InitRange the source range that covers the "0" initializer.
6809bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6810 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6811 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006812 return false;
6813 }
6814
6815 if (!Method->isInvalidDecl())
6816 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6817 << Method->getDeclName() << InitRange;
6818 return true;
6819}
6820
John McCall1f4ee7b2009-12-19 09:28:58 +00006821/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6822/// an initializer for the out-of-line declaration 'Dcl'. The scope
6823/// is a fresh scope pushed for just this purpose.
6824///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006825/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6826/// static data member of class X, names should be looked up in the scope of
6827/// class X.
John McCall48871652010-08-21 09:40:31 +00006828void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006829 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006830 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006831
John McCall1f4ee7b2009-12-19 09:28:58 +00006832 // We should only get called for declarations with scope specifiers, like:
6833 // int foo::bar;
6834 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006835 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006836}
6837
6838/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006839/// initializer for the out-of-line declaration 'D'.
6840void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006841 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006842 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006843
John McCall1f4ee7b2009-12-19 09:28:58 +00006844 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006845 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006846}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006847
6848/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6849/// C++ if/switch/while/for statement.
6850/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006851DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006852 // C++ 6.4p2:
6853 // The declarator shall not specify a function or an array.
6854 // The type-specifier-seq shall not contain typedef and shall not declare a
6855 // new class or enumeration.
6856 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6857 "Parser allowed 'typedef' as storage class of condition decl.");
6858
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006859 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006860 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6861 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006862
6863 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6864 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6865 // would be created and CXXConditionDeclExpr wants a VarDecl.
6866 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6867 << D.getSourceRange();
6868 return DeclResult();
6869 } else if (OwnedTag && OwnedTag->isDefinition()) {
6870 // The type-specifier-seq shall not declare a new class or enumeration.
6871 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6872 }
6873
John McCall48871652010-08-21 09:40:31 +00006874 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006875 if (!Dcl)
6876 return DeclResult();
6877
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006878 return Dcl;
6879}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006880
Douglas Gregor88d292c2010-05-13 16:44:06 +00006881void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6882 bool DefinitionRequired) {
6883 // Ignore any vtable uses in unevaluated operands or for classes that do
6884 // not have a vtable.
6885 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6886 CurContext->isDependentContext() ||
6887 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006888 return;
6889
Douglas Gregor88d292c2010-05-13 16:44:06 +00006890 // Try to insert this class into the map.
6891 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6892 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6893 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6894 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006895 // If we already had an entry, check to see if we are promoting this vtable
6896 // to required a definition. If so, we need to reappend to the VTableUses
6897 // list, since we may have already processed the first entry.
6898 if (DefinitionRequired && !Pos.first->second) {
6899 Pos.first->second = true;
6900 } else {
6901 // Otherwise, we can early exit.
6902 return;
6903 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006904 }
6905
6906 // Local classes need to have their virtual members marked
6907 // immediately. For all other classes, we mark their virtual members
6908 // at the end of the translation unit.
6909 if (Class->isLocalClass())
6910 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006911 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006912 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006913}
6914
Douglas Gregor88d292c2010-05-13 16:44:06 +00006915bool Sema::DefineUsedVTables() {
6916 // If any dynamic classes have their key function defined within
6917 // this translation unit, then those vtables are considered "used" and must
6918 // be emitted.
6919 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6920 if (const CXXMethodDecl *KeyFunction
6921 = Context.getKeyFunction(DynamicClasses[I])) {
6922 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006923 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006924 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6925 }
6926 }
6927
6928 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006929 return false;
6930
Douglas Gregor88d292c2010-05-13 16:44:06 +00006931 // Note: The VTableUses vector could grow as a result of marking
6932 // the members of a class as "used", so we check the size each
6933 // time through the loop and prefer indices (with are stable) to
6934 // iterators (which are not).
6935 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006936 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006937 if (!Class)
6938 continue;
6939
6940 SourceLocation Loc = VTableUses[I].second;
6941
6942 // If this class has a key function, but that key function is
6943 // defined in another translation unit, we don't need to emit the
6944 // vtable even though we're using it.
6945 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006946 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006947 switch (KeyFunction->getTemplateSpecializationKind()) {
6948 case TSK_Undeclared:
6949 case TSK_ExplicitSpecialization:
6950 case TSK_ExplicitInstantiationDeclaration:
6951 // The key function is in another translation unit.
6952 continue;
6953
6954 case TSK_ExplicitInstantiationDefinition:
6955 case TSK_ImplicitInstantiation:
6956 // We will be instantiating the key function.
6957 break;
6958 }
6959 } else if (!KeyFunction) {
6960 // If we have a class with no key function that is the subject
6961 // of an explicit instantiation declaration, suppress the
6962 // vtable; it will live with the explicit instantiation
6963 // definition.
6964 bool IsExplicitInstantiationDeclaration
6965 = Class->getTemplateSpecializationKind()
6966 == TSK_ExplicitInstantiationDeclaration;
6967 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6968 REnd = Class->redecls_end();
6969 R != REnd; ++R) {
6970 TemplateSpecializationKind TSK
6971 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6972 if (TSK == TSK_ExplicitInstantiationDeclaration)
6973 IsExplicitInstantiationDeclaration = true;
6974 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6975 IsExplicitInstantiationDeclaration = false;
6976 break;
6977 }
6978 }
6979
6980 if (IsExplicitInstantiationDeclaration)
6981 continue;
6982 }
6983
6984 // Mark all of the virtual members of this class as referenced, so
6985 // that we can build a vtable. Then, tell the AST consumer that a
6986 // vtable for this class is required.
6987 MarkVirtualMembersReferenced(Loc, Class);
6988 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6989 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6990
6991 // Optionally warn if we're emitting a weak vtable.
6992 if (Class->getLinkage() == ExternalLinkage &&
6993 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006994 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006995 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6996 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006997 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006998 VTableUses.clear();
6999
Anders Carlsson82fccd02009-12-07 08:24:59 +00007000 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007001}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007002
Rafael Espindola5b334082010-03-26 00:36:59 +00007003void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7004 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007005 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7006 e = RD->method_end(); i != e; ++i) {
7007 CXXMethodDecl *MD = *i;
7008
7009 // C++ [basic.def.odr]p2:
7010 // [...] A virtual member function is used if it is not pure. [...]
7011 if (MD->isVirtual() && !MD->isPure())
7012 MarkDeclarationReferenced(Loc, MD);
7013 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007014
7015 // Only classes that have virtual bases need a VTT.
7016 if (RD->getNumVBases() == 0)
7017 return;
7018
7019 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7020 e = RD->bases_end(); i != e; ++i) {
7021 const CXXRecordDecl *Base =
7022 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007023 if (Base->getNumVBases() == 0)
7024 continue;
7025 MarkVirtualMembersReferenced(Loc, Base);
7026 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007027}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007028
7029/// SetIvarInitializers - This routine builds initialization ASTs for the
7030/// Objective-C implementation whose ivars need be initialized.
7031void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7032 if (!getLangOptions().CPlusPlus)
7033 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007034 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007035 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7036 CollectIvarsToConstructOrDestruct(OID, ivars);
7037 if (ivars.empty())
7038 return;
7039 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7040 for (unsigned i = 0; i < ivars.size(); i++) {
7041 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007042 if (Field->isInvalidDecl())
7043 continue;
7044
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007045 CXXBaseOrMemberInitializer *Member;
7046 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7047 InitializationKind InitKind =
7048 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7049
7050 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007051 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007052 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00007053 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007054 // Note, MemberInit could actually come back empty if no initialization
7055 // is required (e.g., because it would call a trivial default constructor)
7056 if (!MemberInit.get() || MemberInit.isInvalid())
7057 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007058
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007059 Member =
7060 new (Context) CXXBaseOrMemberInitializer(Context,
7061 Field, SourceLocation(),
7062 SourceLocation(),
7063 MemberInit.takeAs<Expr>(),
7064 SourceLocation());
7065 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007066
7067 // Be sure that the destructor is accessible and is marked as referenced.
7068 if (const RecordType *RecordTy
7069 = Context.getBaseElementType(Field->getType())
7070 ->getAs<RecordType>()) {
7071 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007072 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007073 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7074 CheckDestructorAccess(Field->getLocation(), Destructor,
7075 PDiag(diag::err_access_dtor_ivar)
7076 << Context.getBaseElementType(Field->getType()));
7077 }
7078 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007079 }
7080 ObjCImplementation->setIvarInitializers(Context,
7081 AllToInit.data(), AllToInit.size());
7082 }
7083}