blob: d30faccf24a13d55fd8bbbf6cabb36a5049c945d [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,
Nico Weber20c9f1d2010-11-28 22:53:37 +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
Nick Lewycky9331ed82010-11-20 01:29:55 +00001057 // constructor's class and, if not found in that scope, are looked
1058 // up in the scope containing the constructor's definition.
1059 // [Note: if the constructor's class contains a member with the
1060 // same name as a direct or virtual base class of the class, a
1061 // mem-initializer-id naming the member or base class and composed
1062 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001063 // 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);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001070 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001071 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001072
1073 // Handle anonymous union case.
1074 if (!Member)
1075 if (IndirectFieldDecl* IndirectField
1076 = dyn_cast<IndirectFieldDecl>(*Result.first))
1077 Member = IndirectField->getAnonField();
1078 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001079
Eli Friedman8e1433b2009-07-29 19:44:27 +00001080 if (Member)
1081 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001082 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001083 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001084 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001085 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001086 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001087
1088 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001089 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001090 } else {
1091 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1092 LookupParsedName(R, S, &SS);
1093
1094 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1095 if (!TyD) {
1096 if (R.isAmbiguous()) return true;
1097
John McCallda6841b2010-04-09 19:01:14 +00001098 // We don't want access-control diagnostics here.
1099 R.suppressDiagnostics();
1100
Douglas Gregora3b624a2010-01-19 06:46:48 +00001101 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1102 bool NotUnknownSpecialization = false;
1103 DeclContext *DC = computeDeclContext(SS, false);
1104 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1105 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1106
1107 if (!NotUnknownSpecialization) {
1108 // When the scope specifier can refer to a member of an unknown
1109 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001110 BaseType = CheckTypenameType(ETK_None,
1111 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001112 *MemberOrBase, SourceLocation(),
1113 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001114 if (BaseType.isNull())
1115 return true;
1116
Douglas Gregora3b624a2010-01-19 06:46:48 +00001117 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001118 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001119 }
1120 }
1121
Douglas Gregor15e77a22009-12-31 09:10:24 +00001122 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001123 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001124 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1125 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001126 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001127 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001128 // We have found a non-static data member with a similar
1129 // name to what was typed; complain and initialize that
1130 // member.
1131 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1132 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001133 << FixItHint::CreateReplacement(R.getNameLoc(),
1134 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001135 Diag(Member->getLocation(), diag::note_previous_decl)
1136 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001137
1138 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1139 LParenLoc, RParenLoc);
1140 }
1141 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1142 const CXXBaseSpecifier *DirectBaseSpec;
1143 const CXXBaseSpecifier *VirtualBaseSpec;
1144 if (FindBaseInitializer(*this, ClassDecl,
1145 Context.getTypeDeclType(Type),
1146 DirectBaseSpec, VirtualBaseSpec)) {
1147 // We have found a direct or virtual base class with a
1148 // similar name to what was typed; complain and initialize
1149 // that base class.
1150 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1151 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001152 << FixItHint::CreateReplacement(R.getNameLoc(),
1153 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001154
1155 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1156 : VirtualBaseSpec;
1157 Diag(BaseSpec->getSourceRange().getBegin(),
1158 diag::note_base_class_specified_here)
1159 << BaseSpec->getType()
1160 << BaseSpec->getSourceRange();
1161
Douglas Gregor15e77a22009-12-31 09:10:24 +00001162 TyD = Type;
1163 }
1164 }
1165 }
1166
Douglas Gregora3b624a2010-01-19 06:46:48 +00001167 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001168 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1169 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1170 return true;
1171 }
John McCallb5a0d312009-12-21 10:41:20 +00001172 }
1173
Douglas Gregora3b624a2010-01-19 06:46:48 +00001174 if (BaseType.isNull()) {
1175 BaseType = Context.getTypeDeclType(TyD);
1176 if (SS.isSet()) {
1177 NestedNameSpecifier *Qualifier =
1178 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001179
Douglas Gregora3b624a2010-01-19 06:46:48 +00001180 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001181 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001182 }
John McCallb5a0d312009-12-21 10:41:20 +00001183 }
1184 }
Mike Stump11289f42009-09-09 15:08:12 +00001185
John McCallbcd03502009-12-07 02:54:59 +00001186 if (!TInfo)
1187 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001188
John McCallbcd03502009-12-07 02:54:59 +00001189 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001190 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001191}
1192
John McCalle22a04a2009-11-04 23:02:40 +00001193/// Checks an initializer expression for use of uninitialized fields, such as
1194/// containing the field that is being initialized. Returns true if there is an
1195/// uninitialized field was used an updates the SourceLocation parameter; false
1196/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001197static bool InitExprContainsUninitializedFields(const Stmt *S,
1198 const FieldDecl *LhsField,
1199 SourceLocation *L) {
1200 if (isa<CallExpr>(S)) {
1201 // Do not descend into function calls or constructors, as the use
1202 // of an uninitialized field may be valid. One would have to inspect
1203 // the contents of the function/ctor to determine if it is safe or not.
1204 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1205 // may be safe, depending on what the function/ctor does.
1206 return false;
1207 }
1208 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1209 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001210
1211 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1212 // The member expression points to a static data member.
1213 assert(VD->isStaticDataMember() &&
1214 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001215 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001216 return false;
1217 }
1218
1219 if (isa<EnumConstantDecl>(RhsField)) {
1220 // The member expression points to an enum.
1221 return false;
1222 }
1223
John McCalle22a04a2009-11-04 23:02:40 +00001224 if (RhsField == LhsField) {
1225 // Initializing a field with itself. Throw a warning.
1226 // But wait; there are exceptions!
1227 // Exception #1: The field may not belong to this record.
1228 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001229 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001230 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1231 // Even though the field matches, it does not belong to this record.
1232 return false;
1233 }
1234 // None of the exceptions triggered; return true to indicate an
1235 // uninitialized field was used.
1236 *L = ME->getMemberLoc();
1237 return true;
1238 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001239 } else if (isa<SizeOfAlignOfExpr>(S)) {
1240 // sizeof/alignof doesn't reference contents, do not warn.
1241 return false;
1242 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1243 // address-of doesn't reference contents (the pointer may be dereferenced
1244 // in the same expression but it would be rare; and weird).
1245 if (UOE->getOpcode() == UO_AddrOf)
1246 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001247 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001248 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1249 it != e; ++it) {
1250 if (!*it) {
1251 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001252 continue;
1253 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001254 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1255 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001256 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001257 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001258}
1259
John McCallfaf5fb42010-08-26 23:41:50 +00001260MemInitResult
Eli Friedman8e1433b2009-07-29 19:44:27 +00001261Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1262 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001263 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001264 SourceLocation RParenLoc) {
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001265 if (Member->isInvalidDecl())
1266 return true;
1267
John McCalle22a04a2009-11-04 23:02:40 +00001268 // Diagnose value-uses of fields to initialize themselves, e.g.
1269 // foo(foo)
1270 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001271 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001272 for (unsigned i = 0; i < NumArgs; ++i) {
1273 SourceLocation L;
1274 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1275 // FIXME: Return true in the case when other fields are used before being
1276 // uninitialized. For example, let this field be the i'th field. When
1277 // initializing the i'th field, throw a warning if any of the >= i'th
1278 // fields are used, as they are not yet initialized.
1279 // Right now we are only handling the case where the i'th field uses
1280 // itself in its initializer.
1281 Diag(L, diag::warn_field_is_uninit);
1282 }
1283 }
1284
Eli Friedman8e1433b2009-07-29 19:44:27 +00001285 bool HasDependentArg = false;
1286 for (unsigned i = 0; i < NumArgs; i++)
1287 HasDependentArg |= Args[i]->isTypeDependent();
1288
Eli Friedman9255adf2010-07-24 21:19:15 +00001289 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001290 // Can't check initialization for a member of dependent type or when
1291 // any of the arguments are type-dependent expressions.
John McCallb268a282010-08-23 23:25:46 +00001292 Expr *Init
1293 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1294 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001295
1296 // Erase any temporaries within this evaluation context; we're not
1297 // going to track them in the AST, since we'll be rebuilding the
1298 // ASTs during template instantiation.
1299 ExprTemporaries.erase(
1300 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1301 ExprTemporaries.end());
1302
1303 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1304 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001305 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001306 RParenLoc);
1307
Douglas Gregore8381c02008-11-05 04:29:56 +00001308 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001309
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001310 // Initialize the member.
1311 InitializedEntity MemberEntity =
1312 InitializedEntity::InitializeMember(Member, 0);
1313 InitializationKind Kind =
1314 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1315
1316 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1317
John McCalldadc5752010-08-24 06:29:42 +00001318 ExprResult MemberInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001319 InitSeq.Perform(*this, MemberEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001320 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001321 if (MemberInit.isInvalid())
1322 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001323
1324 CheckImplicitConversions(MemberInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001325
1326 // C++0x [class.base.init]p7:
1327 // The initialization of each base and member constitutes a
1328 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001329 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001330 if (MemberInit.isInvalid())
1331 return true;
1332
1333 // If we are in a dependent context, template instantiation will
1334 // perform this type-checking again. Just save the arguments that we
1335 // received in a ParenListExpr.
1336 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1337 // of the information that we have about the member
1338 // initializer. However, deconstructing the ASTs is a dicey process,
1339 // and this approach is far more likely to get the corner cases right.
1340 if (CurContext->isDependentContext()) {
John McCallb268a282010-08-23 23:25:46 +00001341 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1342 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001343 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1344 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001345 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001346 RParenLoc);
1347 }
1348
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001349 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001350 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001351 MemberInit.get(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001352 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001353}
1354
John McCallfaf5fb42010-08-26 23:41:50 +00001355MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001356Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001357 Expr **Args, unsigned NumArgs,
1358 SourceLocation LParenLoc, SourceLocation RParenLoc,
1359 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001360 bool HasDependentArg = false;
1361 for (unsigned i = 0; i < NumArgs; i++)
1362 HasDependentArg |= Args[i]->isTypeDependent();
1363
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001364 SourceLocation BaseLoc
1365 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1366
1367 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1368 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1369 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1370
1371 // C++ [class.base.init]p2:
1372 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001373 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001374 // of that class, the mem-initializer is ill-formed. A
1375 // mem-initializer-list can initialize a base class using any
1376 // name that denotes that base class type.
1377 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1378
1379 // Check for direct and virtual base classes.
1380 const CXXBaseSpecifier *DirectBaseSpec = 0;
1381 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1382 if (!Dependent) {
1383 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1384 VirtualBaseSpec);
1385
1386 // C++ [base.class.init]p2:
1387 // Unless the mem-initializer-id names a nonstatic data member of the
1388 // constructor's class or a direct or virtual base of that class, the
1389 // mem-initializer is ill-formed.
1390 if (!DirectBaseSpec && !VirtualBaseSpec) {
1391 // If the class has any dependent bases, then it's possible that
1392 // one of those types will resolve to the same type as
1393 // BaseType. Therefore, just treat this as a dependent base
1394 // class initialization. FIXME: Should we try to check the
1395 // initialization anyway? It seems odd.
1396 if (ClassDecl->hasAnyDependentBases())
1397 Dependent = true;
1398 else
1399 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1400 << BaseType << Context.getTypeDeclType(ClassDecl)
1401 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1402 }
1403 }
1404
1405 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001406 // Can't check initialization for a base of dependent type or when
1407 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001408 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001409 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1410 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001411
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001412 // Erase any temporaries within this evaluation context; we're not
1413 // going to track them in the AST, since we'll be rebuilding the
1414 // ASTs during template instantiation.
1415 ExprTemporaries.erase(
1416 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1417 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001419 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001420 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001421 LParenLoc,
1422 BaseInit.takeAs<Expr>(),
1423 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001424 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001425
1426 // C++ [base.class.init]p2:
1427 // If a mem-initializer-id is ambiguous because it designates both
1428 // a direct non-virtual base class and an inherited virtual base
1429 // class, the mem-initializer is ill-formed.
1430 if (DirectBaseSpec && VirtualBaseSpec)
1431 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001432 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001433
1434 CXXBaseSpecifier *BaseSpec
1435 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1436 if (!BaseSpec)
1437 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1438
1439 // Initialize the base.
1440 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001441 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001442 InitializationKind Kind =
1443 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1444
1445 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1446
John McCalldadc5752010-08-24 06:29:42 +00001447 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001448 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001449 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001450 if (BaseInit.isInvalid())
1451 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001452
1453 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001454
1455 // C++0x [class.base.init]p7:
1456 // The initialization of each base and member constitutes a
1457 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001458 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001459 if (BaseInit.isInvalid())
1460 return true;
1461
1462 // If we are in a dependent context, template instantiation will
1463 // perform this type-checking again. Just save the arguments that we
1464 // received in a ParenListExpr.
1465 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1466 // of the information that we have about the base
1467 // initializer. However, deconstructing the ASTs is a dicey process,
1468 // and this approach is far more likely to get the corner cases right.
1469 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001470 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001471 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1472 RParenLoc));
1473 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001474 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001475 LParenLoc,
1476 Init.takeAs<Expr>(),
1477 RParenLoc);
1478 }
1479
1480 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001481 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001482 LParenLoc,
1483 BaseInit.takeAs<Expr>(),
1484 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001485}
1486
Anders Carlsson1b00e242010-04-23 03:10:23 +00001487/// ImplicitInitializerKind - How an implicit base or member initializer should
1488/// initialize its base or member.
1489enum ImplicitInitializerKind {
1490 IIK_Default,
1491 IIK_Copy,
1492 IIK_Move
1493};
1494
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001495static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001496BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001497 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001498 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001499 bool IsInheritedVirtualBase,
1500 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001501 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001502 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1503 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001504
John McCalldadc5752010-08-24 06:29:42 +00001505 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001506
1507 switch (ImplicitInitKind) {
1508 case IIK_Default: {
1509 InitializationKind InitKind
1510 = InitializationKind::CreateDefault(Constructor->getLocation());
1511 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1512 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001513 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001514 break;
1515 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001516
Anders Carlsson1b00e242010-04-23 03:10:23 +00001517 case IIK_Copy: {
1518 ParmVarDecl *Param = Constructor->getParamDecl(0);
1519 QualType ParamType = Param->getType().getNonReferenceType();
1520
1521 Expr *CopyCtorArg =
1522 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001523 Constructor->getLocation(), ParamType,
1524 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001525
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001526 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001527 QualType ArgTy =
1528 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1529 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001530
1531 CXXCastPath BasePath;
1532 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001533 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001534 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001535 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001536
Anders Carlsson1b00e242010-04-23 03:10:23 +00001537 InitializationKind InitKind
1538 = InitializationKind::CreateDirect(Constructor->getLocation(),
1539 SourceLocation(), SourceLocation());
1540 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1541 &CopyCtorArg, 1);
1542 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001543 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001544 break;
1545 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001546
Anders Carlsson1b00e242010-04-23 03:10:23 +00001547 case IIK_Move:
1548 assert(false && "Unhandled initializer kind!");
1549 }
John McCallb268a282010-08-23 23:25:46 +00001550
1551 if (BaseInit.isInvalid())
1552 return true;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001553
John McCallb268a282010-08-23 23:25:46 +00001554 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001555 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001556 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001557
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001558 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001559 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1560 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1561 SourceLocation()),
1562 BaseSpec->isVirtual(),
1563 SourceLocation(),
1564 BaseInit.takeAs<Expr>(),
1565 SourceLocation());
1566
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001567 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001568}
1569
Anders Carlsson3c1db572010-04-23 02:15:47 +00001570static bool
1571BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001572 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001573 FieldDecl *Field,
1574 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001575 if (Field->isInvalidDecl())
1576 return true;
1577
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001578 SourceLocation Loc = Constructor->getLocation();
1579
Anders Carlsson423f5d82010-04-23 16:04:08 +00001580 if (ImplicitInitKind == IIK_Copy) {
1581 ParmVarDecl *Param = Constructor->getParamDecl(0);
1582 QualType ParamType = Param->getType().getNonReferenceType();
1583
1584 Expr *MemberExprBase =
1585 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001586 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001587
1588 // Build a reference to this field within the parameter.
1589 CXXScopeSpec SS;
1590 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1591 Sema::LookupMemberName);
1592 MemberLookup.addDecl(Field, AS_public);
1593 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001594 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001595 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001596 ParamType, Loc,
1597 /*IsArrow=*/false,
1598 SS,
1599 /*FirstQualifierInScope=*/0,
1600 MemberLookup,
1601 /*TemplateArgs=*/0);
1602 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001603 return true;
1604
Douglas Gregor94f9a482010-05-05 05:51:00 +00001605 // When the field we are copying is an array, create index variables for
1606 // each dimension of the array. We use these index variables to subscript
1607 // the source array, and other clients (e.g., CodeGen) will perform the
1608 // necessary iteration with these index variables.
1609 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1610 QualType BaseType = Field->getType();
1611 QualType SizeType = SemaRef.Context.getSizeType();
1612 while (const ConstantArrayType *Array
1613 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1614 // Create the iteration variable for this array index.
1615 IdentifierInfo *IterationVarName = 0;
1616 {
1617 llvm::SmallString<8> Str;
1618 llvm::raw_svector_ostream OS(Str);
1619 OS << "__i" << IndexVariables.size();
1620 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1621 }
1622 VarDecl *IterationVar
1623 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1624 IterationVarName, SizeType,
1625 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001626 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001627 IndexVariables.push_back(IterationVar);
1628
1629 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001630 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001631 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001632 assert(!IterationVarRef.isInvalid() &&
1633 "Reference to invented variable cannot fail!");
1634
1635 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001636 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001637 Loc,
John McCallb268a282010-08-23 23:25:46 +00001638 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001639 Loc);
1640 if (CopyCtorArg.isInvalid())
1641 return true;
1642
1643 BaseType = Array->getElementType();
1644 }
1645
1646 // Construct the entity that we will be initializing. For an array, this
1647 // will be first element in the array, which may require several levels
1648 // of array-subscript entities.
1649 llvm::SmallVector<InitializedEntity, 4> Entities;
1650 Entities.reserve(1 + IndexVariables.size());
1651 Entities.push_back(InitializedEntity::InitializeMember(Field));
1652 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1653 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1654 0,
1655 Entities.back()));
1656
1657 // Direct-initialize to use the copy constructor.
1658 InitializationKind InitKind =
1659 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1660
1661 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1662 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1663 &CopyCtorArgE, 1);
1664
John McCalldadc5752010-08-24 06:29:42 +00001665 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001666 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001667 MultiExprArg(&CopyCtorArgE, 1));
John McCallb268a282010-08-23 23:25:46 +00001668 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor94f9a482010-05-05 05:51:00 +00001669 if (MemberInit.isInvalid())
1670 return true;
1671
1672 CXXMemberInit
1673 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1674 MemberInit.takeAs<Expr>(), Loc,
1675 IndexVariables.data(),
1676 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001677 return false;
1678 }
1679
Anders Carlsson423f5d82010-04-23 16:04:08 +00001680 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1681
Anders Carlsson3c1db572010-04-23 02:15:47 +00001682 QualType FieldBaseElementType =
1683 SemaRef.Context.getBaseElementType(Field->getType());
1684
Anders Carlsson3c1db572010-04-23 02:15:47 +00001685 if (FieldBaseElementType->isRecordType()) {
1686 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001687 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001688 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001689
1690 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001691 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001692 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001693 if (MemberInit.isInvalid())
1694 return true;
1695
1696 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001697 if (MemberInit.isInvalid())
1698 return true;
1699
1700 CXXMemberInit =
1701 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001702 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001703 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001704 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001705 return false;
1706 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001707
1708 if (FieldBaseElementType->isReferenceType()) {
1709 SemaRef.Diag(Constructor->getLocation(),
1710 diag::err_uninitialized_member_in_ctor)
1711 << (int)Constructor->isImplicit()
1712 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1713 << 0 << Field->getDeclName();
1714 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1715 return true;
1716 }
1717
1718 if (FieldBaseElementType.isConstQualified()) {
1719 SemaRef.Diag(Constructor->getLocation(),
1720 diag::err_uninitialized_member_in_ctor)
1721 << (int)Constructor->isImplicit()
1722 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1723 << 1 << Field->getDeclName();
1724 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1725 return true;
1726 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001727
1728 // Nothing to initialize.
1729 CXXMemberInit = 0;
1730 return false;
1731}
John McCallbc83b3f2010-05-20 23:23:51 +00001732
1733namespace {
1734struct BaseAndFieldInfo {
1735 Sema &S;
1736 CXXConstructorDecl *Ctor;
1737 bool AnyErrorsInInits;
1738 ImplicitInitializerKind IIK;
1739 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1740 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1741
1742 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1743 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1744 // FIXME: Handle implicit move constructors.
1745 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1746 IIK = IIK_Copy;
1747 else
1748 IIK = IIK_Default;
1749 }
1750};
1751}
1752
Chandler Carruth139e9622010-06-30 02:59:29 +00001753static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1754 FieldDecl *Top, FieldDecl *Field,
1755 CXXBaseOrMemberInitializer *Init) {
1756 // If the member doesn't need to be initialized, Init will still be null.
1757 if (!Init)
1758 return;
1759
1760 Info.AllToInit.push_back(Init);
1761 if (Field != Top) {
1762 Init->setMember(Top);
1763 Init->setAnonUnionMember(Field);
1764 }
1765}
1766
John McCallbc83b3f2010-05-20 23:23:51 +00001767static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1768 FieldDecl *Top, FieldDecl *Field) {
1769
Chandler Carruth139e9622010-06-30 02:59:29 +00001770 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001771 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001772 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001773 return false;
1774 }
1775
1776 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1777 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1778 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001779 CXXRecordDecl *FieldClassDecl
1780 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001781
1782 // Even though union members never have non-trivial default
1783 // constructions in C++03, we still build member initializers for aggregate
1784 // record types which can be union members, and C++0x allows non-trivial
1785 // default constructors for union members, so we ensure that only one
1786 // member is initialized for these.
1787 if (FieldClassDecl->isUnion()) {
1788 // First check for an explicit initializer for one field.
1789 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1790 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1791 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1792 RecordFieldInitializer(Info, Top, *FA, Init);
1793
1794 // Once we've initialized a field of an anonymous union, the union
1795 // field in the class is also initialized, so exit immediately.
1796 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001797 } else if ((*FA)->isAnonymousStructOrUnion()) {
1798 if (CollectFieldInitializer(Info, Top, *FA))
1799 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001800 }
1801 }
1802
1803 // Fallthrough and construct a default initializer for the union as
1804 // a whole, which can call its default constructor if such a thing exists
1805 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1806 // behavior going forward with C++0x, when anonymous unions there are
1807 // finalized, we should revisit this.
1808 } else {
1809 // For structs, we simply descend through to initialize all members where
1810 // necessary.
1811 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1812 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1813 if (CollectFieldInitializer(Info, Top, *FA))
1814 return true;
1815 }
1816 }
John McCallbc83b3f2010-05-20 23:23:51 +00001817 }
1818
1819 // Don't try to build an implicit initializer if there were semantic
1820 // errors in any of the initializers (and therefore we might be
1821 // missing some that the user actually wrote).
1822 if (Info.AnyErrorsInInits)
1823 return false;
1824
1825 CXXBaseOrMemberInitializer *Init = 0;
1826 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1827 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001828
Chandler Carruth139e9622010-06-30 02:59:29 +00001829 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001830 return false;
1831}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001832
Eli Friedman9cf6b592009-11-09 19:20:36 +00001833bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001834Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001835 CXXBaseOrMemberInitializer **Initializers,
1836 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001837 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001838 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001839 // Just store the initializers as written, they will be checked during
1840 // instantiation.
1841 if (NumInitializers > 0) {
1842 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1843 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1844 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1845 memcpy(baseOrMemberInitializers, Initializers,
1846 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1847 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1848 }
1849
1850 return false;
1851 }
1852
John McCallbc83b3f2010-05-20 23:23:51 +00001853 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001854
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001855 // We need to build the initializer AST according to order of construction
1856 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001857 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001858 if (!ClassDecl)
1859 return true;
1860
Eli Friedman9cf6b592009-11-09 19:20:36 +00001861 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001862
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001863 for (unsigned i = 0; i < NumInitializers; i++) {
1864 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001865
1866 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001867 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001868 else
John McCallbc83b3f2010-05-20 23:23:51 +00001869 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001870 }
1871
Anders Carlsson43c64af2010-04-21 19:52:01 +00001872 // Keep track of the direct virtual bases.
1873 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1874 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1875 E = ClassDecl->bases_end(); I != E; ++I) {
1876 if (I->isVirtual())
1877 DirectVBases.insert(I);
1878 }
1879
Anders Carlssondb0a9652010-04-02 06:26:44 +00001880 // Push virtual bases before others.
1881 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1882 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1883
1884 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001885 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1886 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001887 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001888 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001889 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001890 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001891 VBase, IsInheritedVirtualBase,
1892 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001893 HadError = true;
1894 continue;
1895 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001896
John McCallbc83b3f2010-05-20 23:23:51 +00001897 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001898 }
1899 }
Mike Stump11289f42009-09-09 15:08:12 +00001900
John McCallbc83b3f2010-05-20 23:23:51 +00001901 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001902 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1903 E = ClassDecl->bases_end(); Base != E; ++Base) {
1904 // Virtuals are in the virtual base list and already constructed.
1905 if (Base->isVirtual())
1906 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlssondb0a9652010-04-02 06:26:44 +00001908 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001909 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1910 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001911 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001912 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001913 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001914 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001915 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001916 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001917 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001918 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001919
John McCallbc83b3f2010-05-20 23:23:51 +00001920 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001921 }
1922 }
Mike Stump11289f42009-09-09 15:08:12 +00001923
John McCallbc83b3f2010-05-20 23:23:51 +00001924 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001926 E = ClassDecl->field_end(); Field != E; ++Field) {
1927 if ((*Field)->getType()->isIncompleteArrayType()) {
1928 assert(ClassDecl->hasFlexibleArrayMember() &&
1929 "Incomplete array type is not valid");
1930 continue;
1931 }
John McCallbc83b3f2010-05-20 23:23:51 +00001932 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001933 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001934 }
Mike Stump11289f42009-09-09 15:08:12 +00001935
John McCallbc83b3f2010-05-20 23:23:51 +00001936 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001937 if (NumInitializers > 0) {
1938 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1939 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1940 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001941 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001942 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001943 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001944
John McCalla6309952010-03-16 21:39:52 +00001945 // Constructors implicitly reference the base and member
1946 // destructors.
1947 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1948 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001949 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001950
1951 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001952}
1953
Eli Friedman952c15d2009-07-21 19:28:10 +00001954static void *GetKeyForTopLevelField(FieldDecl *Field) {
1955 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001956 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001957 if (RT->getDecl()->isAnonymousStructOrUnion())
1958 return static_cast<void *>(RT->getDecl());
1959 }
1960 return static_cast<void *>(Field);
1961}
1962
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001963static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1964 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001965}
1966
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001967static void *GetKeyForMember(ASTContext &Context,
1968 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001969 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001970 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001971 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001972
Eli Friedman952c15d2009-07-21 19:28:10 +00001973 // For fields injected into the class via declaration of an anonymous union,
1974 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001975 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001976
Anders Carlssona942dcd2010-03-30 15:39:27 +00001977 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1978 // data member of the class. Data member used in the initializer list is
1979 // in AnonUnionMember field.
1980 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1981 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001982
John McCall23eebd92010-04-10 09:28:51 +00001983 // If the field is a member of an anonymous struct or union, our key
1984 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001985 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001986 if (RD->isAnonymousStructOrUnion()) {
1987 while (true) {
1988 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1989 if (Parent->isAnonymousStructOrUnion())
1990 RD = Parent;
1991 else
1992 break;
1993 }
1994
Anders Carlsson83ac3122010-03-30 16:19:37 +00001995 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Anders Carlssona942dcd2010-03-30 15:39:27 +00001998 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001999}
2000
Anders Carlssone857b292010-04-02 03:37:03 +00002001static void
2002DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002003 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00002004 CXXBaseOrMemberInitializer **Inits,
2005 unsigned NumInits) {
2006 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002007 return;
Mike Stump11289f42009-09-09 15:08:12 +00002008
John McCallbb7b6582010-04-10 07:37:23 +00002009 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2010 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002011 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002012
John McCallbb7b6582010-04-10 07:37:23 +00002013 // Build the list of bases and members in the order that they'll
2014 // actually be initialized. The explicit initializers should be in
2015 // this same order but may be missing things.
2016 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002018 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2019
John McCallbb7b6582010-04-10 07:37:23 +00002020 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002021 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002022 ClassDecl->vbases_begin(),
2023 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002024 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002025
John McCallbb7b6582010-04-10 07:37:23 +00002026 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002027 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002028 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002029 if (Base->isVirtual())
2030 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002031 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCallbb7b6582010-04-10 07:37:23 +00002034 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002035 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2036 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002037 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002038
John McCallbb7b6582010-04-10 07:37:23 +00002039 unsigned NumIdealInits = IdealInitKeys.size();
2040 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002041
John McCallbb7b6582010-04-10 07:37:23 +00002042 CXXBaseOrMemberInitializer *PrevInit = 0;
2043 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2044 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2045 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2046
2047 // Scan forward to try to find this initializer in the idealized
2048 // initializers list.
2049 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2050 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002051 break;
John McCallbb7b6582010-04-10 07:37:23 +00002052
2053 // If we didn't find this initializer, it must be because we
2054 // scanned past it on a previous iteration. That can only
2055 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002056 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002057 Sema::SemaDiagnosticBuilder D =
2058 SemaRef.Diag(PrevInit->getSourceLocation(),
2059 diag::warn_initializer_out_of_order);
2060
2061 if (PrevInit->isMemberInitializer())
2062 D << 0 << PrevInit->getMember()->getDeclName();
2063 else
2064 D << 1 << PrevInit->getBaseClassInfo()->getType();
2065
2066 if (Init->isMemberInitializer())
2067 D << 0 << Init->getMember()->getDeclName();
2068 else
2069 D << 1 << Init->getBaseClassInfo()->getType();
2070
2071 // Move back to the initializer's location in the ideal list.
2072 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2073 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002074 break;
John McCallbb7b6582010-04-10 07:37:23 +00002075
2076 assert(IdealIndex != NumIdealInits &&
2077 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002078 }
John McCallbb7b6582010-04-10 07:37:23 +00002079
2080 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002081 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002082}
2083
John McCall23eebd92010-04-10 09:28:51 +00002084namespace {
2085bool CheckRedundantInit(Sema &S,
2086 CXXBaseOrMemberInitializer *Init,
2087 CXXBaseOrMemberInitializer *&PrevInit) {
2088 if (!PrevInit) {
2089 PrevInit = Init;
2090 return false;
2091 }
2092
2093 if (FieldDecl *Field = Init->getMember())
2094 S.Diag(Init->getSourceLocation(),
2095 diag::err_multiple_mem_initialization)
2096 << Field->getDeclName()
2097 << Init->getSourceRange();
2098 else {
2099 Type *BaseClass = Init->getBaseClass();
2100 assert(BaseClass && "neither field nor base");
2101 S.Diag(Init->getSourceLocation(),
2102 diag::err_multiple_base_initialization)
2103 << QualType(BaseClass, 0)
2104 << Init->getSourceRange();
2105 }
2106 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2107 << 0 << PrevInit->getSourceRange();
2108
2109 return true;
2110}
2111
2112typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2113typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2114
2115bool CheckRedundantUnionInit(Sema &S,
2116 CXXBaseOrMemberInitializer *Init,
2117 RedundantUnionMap &Unions) {
2118 FieldDecl *Field = Init->getMember();
2119 RecordDecl *Parent = Field->getParent();
2120 if (!Parent->isAnonymousStructOrUnion())
2121 return false;
2122
2123 NamedDecl *Child = Field;
2124 do {
2125 if (Parent->isUnion()) {
2126 UnionEntry &En = Unions[Parent];
2127 if (En.first && En.first != Child) {
2128 S.Diag(Init->getSourceLocation(),
2129 diag::err_multiple_mem_union_initialization)
2130 << Field->getDeclName()
2131 << Init->getSourceRange();
2132 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2133 << 0 << En.second->getSourceRange();
2134 return true;
2135 } else if (!En.first) {
2136 En.first = Child;
2137 En.second = Init;
2138 }
2139 }
2140
2141 Child = Parent;
2142 Parent = cast<RecordDecl>(Parent->getDeclContext());
2143 } while (Parent->isAnonymousStructOrUnion());
2144
2145 return false;
2146}
2147}
2148
Anders Carlssone857b292010-04-02 03:37:03 +00002149/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002150void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002151 SourceLocation ColonLoc,
2152 MemInitTy **meminits, unsigned NumMemInits,
2153 bool AnyErrors) {
2154 if (!ConstructorDecl)
2155 return;
2156
2157 AdjustDeclIfTemplate(ConstructorDecl);
2158
2159 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002160 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002161
2162 if (!Constructor) {
2163 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2164 return;
2165 }
2166
2167 CXXBaseOrMemberInitializer **MemInits =
2168 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002169
2170 // Mapping for the duplicate initializers check.
2171 // For member initializers, this is keyed with a FieldDecl*.
2172 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002173 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002174
2175 // Mapping for the inconsistent anonymous-union initializers check.
2176 RedundantUnionMap MemberUnions;
2177
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002178 bool HadError = false;
2179 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002180 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002181
Abramo Bagnara341d7832010-05-26 18:09:23 +00002182 // Set the source order index.
2183 Init->setSourceOrder(i);
2184
John McCall23eebd92010-04-10 09:28:51 +00002185 if (Init->isMemberInitializer()) {
2186 FieldDecl *Field = Init->getMember();
2187 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2188 CheckRedundantUnionInit(*this, Init, MemberUnions))
2189 HadError = true;
2190 } else {
2191 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2192 if (CheckRedundantInit(*this, Init, Members[Key]))
2193 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002194 }
Anders Carlssone857b292010-04-02 03:37:03 +00002195 }
2196
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002197 if (HadError)
2198 return;
2199
Anders Carlssone857b292010-04-02 03:37:03 +00002200 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002201
2202 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002203}
2204
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002205void
John McCalla6309952010-03-16 21:39:52 +00002206Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2207 CXXRecordDecl *ClassDecl) {
2208 // Ignore dependent contexts.
2209 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002210 return;
John McCall1064d7e2010-03-16 05:22:47 +00002211
2212 // FIXME: all the access-control diagnostics are positioned on the
2213 // field/base declaration. That's probably good; that said, the
2214 // user might reasonably want to know why the destructor is being
2215 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002216
Anders Carlssondee9a302009-11-17 04:44:12 +00002217 // Non-static data members.
2218 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2219 E = ClassDecl->field_end(); I != E; ++I) {
2220 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002221 if (Field->isInvalidDecl())
2222 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002223 QualType FieldType = Context.getBaseElementType(Field->getType());
2224
2225 const RecordType* RT = FieldType->getAs<RecordType>();
2226 if (!RT)
2227 continue;
2228
2229 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2230 if (FieldClassDecl->hasTrivialDestructor())
2231 continue;
2232
Douglas Gregore71edda2010-07-01 22:47:18 +00002233 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002234 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002235 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002236 << Field->getDeclName()
2237 << FieldType);
2238
John McCalla6309952010-03-16 21:39:52 +00002239 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002240 }
2241
John McCall1064d7e2010-03-16 05:22:47 +00002242 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2243
Anders Carlssondee9a302009-11-17 04:44:12 +00002244 // Bases.
2245 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2246 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002247 // Bases are always records in a well-formed non-dependent class.
2248 const RecordType *RT = Base->getType()->getAs<RecordType>();
2249
2250 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002251 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002252 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002253
2254 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002255 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002256 if (BaseClassDecl->hasTrivialDestructor())
2257 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002258
Douglas Gregore71edda2010-07-01 22:47:18 +00002259 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002260
2261 // FIXME: caret should be on the start of the class name
2262 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002263 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002264 << Base->getType()
2265 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002266
John McCalla6309952010-03-16 21:39:52 +00002267 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002268 }
2269
2270 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002271 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2272 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002273
2274 // Bases are always records in a well-formed non-dependent class.
2275 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2276
2277 // Ignore direct virtual bases.
2278 if (DirectVirtualBases.count(RT))
2279 continue;
2280
Anders Carlssondee9a302009-11-17 04:44:12 +00002281 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002282 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002283 if (BaseClassDecl->hasTrivialDestructor())
2284 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002285
Douglas Gregore71edda2010-07-01 22:47:18 +00002286 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002287 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002288 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002289 << VBase->getType());
2290
John McCalla6309952010-03-16 21:39:52 +00002291 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002292 }
2293}
2294
John McCall48871652010-08-21 09:40:31 +00002295void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002296 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002297 return;
Mike Stump11289f42009-09-09 15:08:12 +00002298
Mike Stump11289f42009-09-09 15:08:12 +00002299 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002300 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002301 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002302}
2303
Mike Stump11289f42009-09-09 15:08:12 +00002304bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002305 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002306 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002307 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002308 else
John McCall02db245d2010-08-18 09:41:07 +00002309 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002310}
2311
Anders Carlssoneabf7702009-08-27 00:13:57 +00002312bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002313 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002314 if (!getLangOptions().CPlusPlus)
2315 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002316
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002317 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002318 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002320 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002321 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002322 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002323 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002324
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002325 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002326 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002329 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002330 if (!RT)
2331 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002332
John McCall67da35c2010-02-04 22:26:26 +00002333 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002334
John McCall02db245d2010-08-18 09:41:07 +00002335 // We can't answer whether something is abstract until it has a
2336 // definition. If it's currently being defined, we'll walk back
2337 // over all the declarations when we have a full definition.
2338 const CXXRecordDecl *Def = RD->getDefinition();
2339 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002340 return false;
2341
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002342 if (!RD->isAbstract())
2343 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002344
Anders Carlssoneabf7702009-08-27 00:13:57 +00002345 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002346 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002347
John McCall02db245d2010-08-18 09:41:07 +00002348 return true;
2349}
2350
2351void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2352 // Check if we've already emitted the list of pure virtual functions
2353 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002354 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002355 return;
Mike Stump11289f42009-09-09 15:08:12 +00002356
Douglas Gregor4165bd62010-03-23 23:47:56 +00002357 CXXFinalOverriderMap FinalOverriders;
2358 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002359
Anders Carlssona2f74f32010-06-03 01:00:02 +00002360 // Keep a set of seen pure methods so we won't diagnose the same method
2361 // more than once.
2362 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2363
Douglas Gregor4165bd62010-03-23 23:47:56 +00002364 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2365 MEnd = FinalOverriders.end();
2366 M != MEnd;
2367 ++M) {
2368 for (OverridingMethods::iterator SO = M->second.begin(),
2369 SOEnd = M->second.end();
2370 SO != SOEnd; ++SO) {
2371 // C++ [class.abstract]p4:
2372 // A class is abstract if it contains or inherits at least one
2373 // pure virtual function for which the final overrider is pure
2374 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002375
Douglas Gregor4165bd62010-03-23 23:47:56 +00002376 //
2377 if (SO->second.size() != 1)
2378 continue;
2379
2380 if (!SO->second.front().Method->isPure())
2381 continue;
2382
Anders Carlssona2f74f32010-06-03 01:00:02 +00002383 if (!SeenPureMethods.insert(SO->second.front().Method))
2384 continue;
2385
Douglas Gregor4165bd62010-03-23 23:47:56 +00002386 Diag(SO->second.front().Method->getLocation(),
2387 diag::note_pure_virtual_function)
2388 << SO->second.front().Method->getDeclName();
2389 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002390 }
2391
2392 if (!PureVirtualClassDiagSet)
2393 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2394 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002395}
2396
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002397namespace {
John McCall02db245d2010-08-18 09:41:07 +00002398struct AbstractUsageInfo {
2399 Sema &S;
2400 CXXRecordDecl *Record;
2401 CanQualType AbstractType;
2402 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002403
John McCall02db245d2010-08-18 09:41:07 +00002404 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2405 : S(S), Record(Record),
2406 AbstractType(S.Context.getCanonicalType(
2407 S.Context.getTypeDeclType(Record))),
2408 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002409
John McCall02db245d2010-08-18 09:41:07 +00002410 void DiagnoseAbstractType() {
2411 if (Invalid) return;
2412 S.DiagnoseAbstractType(Record);
2413 Invalid = true;
2414 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002415
John McCall02db245d2010-08-18 09:41:07 +00002416 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2417};
2418
2419struct CheckAbstractUsage {
2420 AbstractUsageInfo &Info;
2421 const NamedDecl *Ctx;
2422
2423 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2424 : Info(Info), Ctx(Ctx) {}
2425
2426 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2427 switch (TL.getTypeLocClass()) {
2428#define ABSTRACT_TYPELOC(CLASS, PARENT)
2429#define TYPELOC(CLASS, PARENT) \
2430 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2431#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002432 }
John McCall02db245d2010-08-18 09:41:07 +00002433 }
Mike Stump11289f42009-09-09 15:08:12 +00002434
John McCall02db245d2010-08-18 09:41:07 +00002435 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2436 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2437 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2438 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2439 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002440 }
John McCall02db245d2010-08-18 09:41:07 +00002441 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002442
John McCall02db245d2010-08-18 09:41:07 +00002443 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2444 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
John McCall02db245d2010-08-18 09:41:07 +00002447 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2448 // Visit the type parameters from a permissive context.
2449 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2450 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2451 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2452 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2453 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2454 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002455 }
John McCall02db245d2010-08-18 09:41:07 +00002456 }
Mike Stump11289f42009-09-09 15:08:12 +00002457
John McCall02db245d2010-08-18 09:41:07 +00002458 // Visit pointee types from a permissive context.
2459#define CheckPolymorphic(Type) \
2460 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2461 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2462 }
2463 CheckPolymorphic(PointerTypeLoc)
2464 CheckPolymorphic(ReferenceTypeLoc)
2465 CheckPolymorphic(MemberPointerTypeLoc)
2466 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002467
John McCall02db245d2010-08-18 09:41:07 +00002468 /// Handle all the types we haven't given a more specific
2469 /// implementation for above.
2470 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2471 // Every other kind of type that we haven't called out already
2472 // that has an inner type is either (1) sugar or (2) contains that
2473 // inner type in some way as a subobject.
2474 if (TypeLoc Next = TL.getNextTypeLoc())
2475 return Visit(Next, Sel);
2476
2477 // If there's no inner type and we're in a permissive context,
2478 // don't diagnose.
2479 if (Sel == Sema::AbstractNone) return;
2480
2481 // Check whether the type matches the abstract type.
2482 QualType T = TL.getType();
2483 if (T->isArrayType()) {
2484 Sel = Sema::AbstractArrayType;
2485 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002486 }
John McCall02db245d2010-08-18 09:41:07 +00002487 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2488 if (CT != Info.AbstractType) return;
2489
2490 // It matched; do some magic.
2491 if (Sel == Sema::AbstractArrayType) {
2492 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2493 << T << TL.getSourceRange();
2494 } else {
2495 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2496 << Sel << T << TL.getSourceRange();
2497 }
2498 Info.DiagnoseAbstractType();
2499 }
2500};
2501
2502void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2503 Sema::AbstractDiagSelID Sel) {
2504 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2505}
2506
2507}
2508
2509/// Check for invalid uses of an abstract type in a method declaration.
2510static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2511 CXXMethodDecl *MD) {
2512 // No need to do the check on definitions, which require that
2513 // the return/param types be complete.
2514 if (MD->isThisDeclarationADefinition())
2515 return;
2516
2517 // For safety's sake, just ignore it if we don't have type source
2518 // information. This should never happen for non-implicit methods,
2519 // but...
2520 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2521 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2522}
2523
2524/// Check for invalid uses of an abstract type within a class definition.
2525static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2526 CXXRecordDecl *RD) {
2527 for (CXXRecordDecl::decl_iterator
2528 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2529 Decl *D = *I;
2530 if (D->isImplicit()) continue;
2531
2532 // Methods and method templates.
2533 if (isa<CXXMethodDecl>(D)) {
2534 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2535 } else if (isa<FunctionTemplateDecl>(D)) {
2536 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2537 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2538
2539 // Fields and static variables.
2540 } else if (isa<FieldDecl>(D)) {
2541 FieldDecl *FD = cast<FieldDecl>(D);
2542 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2543 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2544 } else if (isa<VarDecl>(D)) {
2545 VarDecl *VD = cast<VarDecl>(D);
2546 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2547 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2548
2549 // Nested classes and class templates.
2550 } else if (isa<CXXRecordDecl>(D)) {
2551 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2552 } else if (isa<ClassTemplateDecl>(D)) {
2553 CheckAbstractClassUsage(Info,
2554 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2555 }
2556 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002557}
2558
Douglas Gregorc99f1552009-12-03 18:33:45 +00002559/// \brief Perform semantic checks on a class definition that has been
2560/// completing, introducing implicitly-declared members, checking for
2561/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002562void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002563 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002564 return;
2565
John McCall02db245d2010-08-18 09:41:07 +00002566 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2567 AbstractUsageInfo Info(*this, Record);
2568 CheckAbstractClassUsage(Info, Record);
2569 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002570
2571 // If this is not an aggregate type and has no user-declared constructor,
2572 // complain about any non-static data members of reference or const scalar
2573 // type, since they will never get initializers.
2574 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2575 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2576 bool Complained = false;
2577 for (RecordDecl::field_iterator F = Record->field_begin(),
2578 FEnd = Record->field_end();
2579 F != FEnd; ++F) {
2580 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002581 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002582 if (!Complained) {
2583 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2584 << Record->getTagKind() << Record;
2585 Complained = true;
2586 }
2587
2588 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2589 << F->getType()->isReferenceType()
2590 << F->getDeclName();
2591 }
2592 }
2593 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002594
2595 if (Record->isDynamicClass())
2596 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002597
2598 if (Record->getIdentifier()) {
2599 // C++ [class.mem]p13:
2600 // If T is the name of a class, then each of the following shall have a
2601 // name different from T:
2602 // - every member of every anonymous union that is a member of class T.
2603 //
2604 // C++ [class.mem]p14:
2605 // In addition, if class T has a user-declared constructor (12.1), every
2606 // non-static data member of class T shall have a name different from T.
2607 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002608 R.first != R.second; ++R.first) {
2609 NamedDecl *D = *R.first;
2610 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2611 isa<IndirectFieldDecl>(D)) {
2612 Diag(D->getLocation(), diag::err_member_name_of_class)
2613 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002614 break;
2615 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002616 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002617 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002618}
2619
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002620void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002621 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002622 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002623 SourceLocation RBrac,
2624 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002625 if (!TagDecl)
2626 return;
Mike Stump11289f42009-09-09 15:08:12 +00002627
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002628 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002629
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002630 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002631 // strict aliasing violation!
2632 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002633 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002634
Douglas Gregor0be31a22010-07-02 17:43:08 +00002635 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002636 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002637}
2638
Douglas Gregor95755162010-07-01 05:10:53 +00002639namespace {
2640 /// \brief Helper class that collects exception specifications for
2641 /// implicitly-declared special member functions.
2642 class ImplicitExceptionSpecification {
2643 ASTContext &Context;
2644 bool AllowsAllExceptions;
2645 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2646 llvm::SmallVector<QualType, 4> Exceptions;
2647
2648 public:
2649 explicit ImplicitExceptionSpecification(ASTContext &Context)
2650 : Context(Context), AllowsAllExceptions(false) { }
2651
2652 /// \brief Whether the special member function should have any
2653 /// exception specification at all.
2654 bool hasExceptionSpecification() const {
2655 return !AllowsAllExceptions;
2656 }
2657
2658 /// \brief Whether the special member function should have a
2659 /// throw(...) exception specification (a Microsoft extension).
2660 bool hasAnyExceptionSpecification() const {
2661 return false;
2662 }
2663
2664 /// \brief The number of exceptions in the exception specification.
2665 unsigned size() const { return Exceptions.size(); }
2666
2667 /// \brief The set of exceptions in the exception specification.
2668 const QualType *data() const { return Exceptions.data(); }
2669
2670 /// \brief Note that
2671 void CalledDecl(CXXMethodDecl *Method) {
2672 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002673 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002674 return;
2675
2676 const FunctionProtoType *Proto
2677 = Method->getType()->getAs<FunctionProtoType>();
2678
2679 // If this function can throw any exceptions, make a note of that.
2680 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2681 AllowsAllExceptions = true;
2682 ExceptionsSeen.clear();
2683 Exceptions.clear();
2684 return;
2685 }
2686
2687 // Record the exceptions in this function's exception specification.
2688 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2689 EEnd = Proto->exception_end();
2690 E != EEnd; ++E)
2691 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2692 Exceptions.push_back(*E);
2693 }
2694 };
2695}
2696
2697
Douglas Gregor05379422008-11-03 17:51:48 +00002698/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2699/// special functions, such as the default constructor, copy
2700/// constructor, or destructor, to the given C++ class (C++
2701/// [special]p1). This routine can only be executed just before the
2702/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002703void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002704 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002705 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002706
Douglas Gregor54be3392010-07-01 17:57:27 +00002707 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002708 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002709
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002710 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2711 ++ASTContext::NumImplicitCopyAssignmentOperators;
2712
2713 // If we have a dynamic class, then the copy assignment operator may be
2714 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2715 // it shows up in the right place in the vtable and that we diagnose
2716 // problems with the implicit exception specification.
2717 if (ClassDecl->isDynamicClass())
2718 DeclareImplicitCopyAssignment(ClassDecl);
2719 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002720
Douglas Gregor7454c562010-07-02 20:37:36 +00002721 if (!ClassDecl->hasUserDeclaredDestructor()) {
2722 ++ASTContext::NumImplicitDestructors;
2723
2724 // If we have a dynamic class, then the destructor may be virtual, so we
2725 // have to declare the destructor immediately. This ensures that, e.g., it
2726 // shows up in the right place in the vtable and that we diagnose problems
2727 // with the implicit exception specification.
2728 if (ClassDecl->isDynamicClass())
2729 DeclareImplicitDestructor(ClassDecl);
2730 }
Douglas Gregor05379422008-11-03 17:51:48 +00002731}
2732
John McCall48871652010-08-21 09:40:31 +00002733void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002734 if (!D)
2735 return;
2736
2737 TemplateParameterList *Params = 0;
2738 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2739 Params = Template->getTemplateParameters();
2740 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2741 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2742 Params = PartialSpec->getTemplateParameters();
2743 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002744 return;
2745
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002746 for (TemplateParameterList::iterator Param = Params->begin(),
2747 ParamEnd = Params->end();
2748 Param != ParamEnd; ++Param) {
2749 NamedDecl *Named = cast<NamedDecl>(*Param);
2750 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002751 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002752 IdResolver.AddDecl(Named);
2753 }
2754 }
2755}
2756
John McCall48871652010-08-21 09:40:31 +00002757void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002758 if (!RecordD) return;
2759 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002760 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002761 PushDeclContext(S, Record);
2762}
2763
John McCall48871652010-08-21 09:40:31 +00002764void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002765 if (!RecordD) return;
2766 PopDeclContext();
2767}
2768
Douglas Gregor4d87df52008-12-16 21:30:33 +00002769/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2770/// parsing a top-level (non-nested) C++ class, and we are now
2771/// parsing those parts of the given Method declaration that could
2772/// not be parsed earlier (C++ [class.mem]p2), such as default
2773/// arguments. This action should enter the scope of the given
2774/// Method declaration as if we had just parsed the qualified method
2775/// name. However, it should not bring the parameters into scope;
2776/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002777void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002778}
2779
2780/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2781/// C++ method declaration. We're (re-)introducing the given
2782/// function parameter into scope for use in parsing later parts of
2783/// the method declaration. For example, we could see an
2784/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002785void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002786 if (!ParamD)
2787 return;
Mike Stump11289f42009-09-09 15:08:12 +00002788
John McCall48871652010-08-21 09:40:31 +00002789 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002790
2791 // If this parameter has an unparsed default argument, clear it out
2792 // to make way for the parsed default argument.
2793 if (Param->hasUnparsedDefaultArg())
2794 Param->setDefaultArg(0);
2795
John McCall48871652010-08-21 09:40:31 +00002796 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002797 if (Param->getDeclName())
2798 IdResolver.AddDecl(Param);
2799}
2800
2801/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2802/// processing the delayed method declaration for Method. The method
2803/// declaration is now considered finished. There may be a separate
2804/// ActOnStartOfFunctionDef action later (not necessarily
2805/// immediately!) for this method, if it was also defined inside the
2806/// class body.
John McCall48871652010-08-21 09:40:31 +00002807void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002808 if (!MethodD)
2809 return;
Mike Stump11289f42009-09-09 15:08:12 +00002810
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002811 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002812
John McCall48871652010-08-21 09:40:31 +00002813 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002814
2815 // Now that we have our default arguments, check the constructor
2816 // again. It could produce additional diagnostics or affect whether
2817 // the class has implicitly-declared destructors, among other
2818 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002819 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2820 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002821
2822 // Check the default arguments, which we may have added.
2823 if (!Method->isInvalidDecl())
2824 CheckCXXDefaultArguments(Method);
2825}
2826
Douglas Gregor831c93f2008-11-05 20:51:48 +00002827/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002828/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002829/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002830/// emit diagnostics and set the invalid bit to true. In any case, the type
2831/// will be updated to reflect a well-formed type for the constructor and
2832/// returned.
2833QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002834 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002835 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002836
2837 // C++ [class.ctor]p3:
2838 // A constructor shall not be virtual (10.3) or static (9.4). A
2839 // constructor can be invoked for a const, volatile or const
2840 // volatile object. A constructor shall not be declared const,
2841 // volatile, or const volatile (9.3.2).
2842 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002843 if (!D.isInvalidType())
2844 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2845 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2846 << SourceRange(D.getIdentifierLoc());
2847 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002848 }
John McCall8e7d6562010-08-26 03:08:43 +00002849 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002850 if (!D.isInvalidType())
2851 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2852 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2853 << SourceRange(D.getIdentifierLoc());
2854 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002855 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002856 }
Mike Stump11289f42009-09-09 15:08:12 +00002857
Chris Lattner38378bf2009-04-25 08:28:21 +00002858 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2859 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002860 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002861 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2862 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002863 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002864 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2865 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002866 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002867 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2868 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002869 }
Mike Stump11289f42009-09-09 15:08:12 +00002870
Douglas Gregor831c93f2008-11-05 20:51:48 +00002871 // Rebuild the function type "R" without any type qualifiers (in
2872 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002873 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002874 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002875 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2876 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002877 Proto->isVariadic(), 0,
2878 Proto->hasExceptionSpec(),
2879 Proto->hasAnyExceptionSpec(),
2880 Proto->getNumExceptions(),
2881 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002882 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002883}
2884
Douglas Gregor4d87df52008-12-16 21:30:33 +00002885/// CheckConstructor - Checks a fully-formed constructor for
2886/// well-formedness, issuing any diagnostics required. Returns true if
2887/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002888void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002889 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002890 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2891 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002892 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002893
2894 // C++ [class.copy]p3:
2895 // A declaration of a constructor for a class X is ill-formed if
2896 // its first parameter is of type (optionally cv-qualified) X and
2897 // either there are no other parameters or else all other
2898 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002899 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002900 ((Constructor->getNumParams() == 1) ||
2901 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002902 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2903 Constructor->getTemplateSpecializationKind()
2904 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002905 QualType ParamType = Constructor->getParamDecl(0)->getType();
2906 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2907 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002908 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002909 const char *ConstRef
2910 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2911 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002912 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002913 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002914
2915 // FIXME: Rather that making the constructor invalid, we should endeavor
2916 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002917 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002918 }
2919 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002920}
2921
John McCalldeb646e2010-08-04 01:04:25 +00002922/// CheckDestructor - Checks a fully-formed destructor definition for
2923/// well-formedness, issuing any diagnostics required. Returns true
2924/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002925bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002926 CXXRecordDecl *RD = Destructor->getParent();
2927
2928 if (Destructor->isVirtual()) {
2929 SourceLocation Loc;
2930
2931 if (!Destructor->isImplicit())
2932 Loc = Destructor->getLocation();
2933 else
2934 Loc = RD->getLocation();
2935
2936 // If we have a virtual destructor, look up the deallocation function
2937 FunctionDecl *OperatorDelete = 0;
2938 DeclarationName Name =
2939 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002940 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002941 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002942
2943 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002944
2945 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002946 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002947
2948 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002949}
2950
Mike Stump11289f42009-09-09 15:08:12 +00002951static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002952FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2953 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2954 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002955 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002956}
2957
Douglas Gregor831c93f2008-11-05 20:51:48 +00002958/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2959/// the well-formednes of the destructor declarator @p D with type @p
2960/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002961/// emit diagnostics and set the declarator to invalid. Even if this happens,
2962/// will be updated to reflect a well-formed type for the destructor and
2963/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002964QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002965 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002966 // C++ [class.dtor]p1:
2967 // [...] A typedef-name that names a class is a class-name
2968 // (7.1.3); however, a typedef-name that names a class shall not
2969 // be used as the identifier in the declarator for a destructor
2970 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002971 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002972 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002973 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002974 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002975
2976 // C++ [class.dtor]p2:
2977 // A destructor is used to destroy objects of its class type. A
2978 // destructor takes no parameters, and no return type can be
2979 // specified for it (not even void). The address of a destructor
2980 // shall not be taken. A destructor shall not be static. A
2981 // destructor can be invoked for a const, volatile or const
2982 // volatile object. A destructor shall not be declared const,
2983 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002984 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002985 if (!D.isInvalidType())
2986 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2987 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002988 << SourceRange(D.getIdentifierLoc())
2989 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2990
John McCall8e7d6562010-08-26 03:08:43 +00002991 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002992 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002993 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002994 // Destructors don't have return types, but the parser will
2995 // happily parse something like:
2996 //
2997 // class X {
2998 // float ~X();
2999 // };
3000 //
3001 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003002 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3003 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3004 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003005 }
Mike Stump11289f42009-09-09 15:08:12 +00003006
Chris Lattner38378bf2009-04-25 08:28:21 +00003007 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3008 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003009 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003010 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3011 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003012 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003013 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3014 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003015 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003016 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3017 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003018 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003019 }
3020
3021 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003022 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003023 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3024
3025 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003026 FTI.freeArgs();
3027 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003028 }
3029
Mike Stump11289f42009-09-09 15:08:12 +00003030 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003031 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003032 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003033 D.setInvalidType();
3034 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003035
3036 // Rebuild the function type "R" without any type qualifiers or
3037 // parameters (in case any of the errors above fired) and with
3038 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003039 // types.
3040 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3041 if (!Proto)
3042 return QualType();
3043
Douglas Gregor36c569f2010-02-21 22:15:06 +00003044 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00003045 Proto->hasExceptionSpec(),
3046 Proto->hasAnyExceptionSpec(),
3047 Proto->getNumExceptions(),
3048 Proto->exception_begin(),
3049 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003050}
3051
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003052/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3053/// well-formednes of the conversion function declarator @p D with
3054/// type @p R. If there are any errors in the declarator, this routine
3055/// will emit diagnostics and return true. Otherwise, it will return
3056/// false. Either way, the type @p R will be updated to reflect a
3057/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003058void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003059 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003060 // C++ [class.conv.fct]p1:
3061 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003062 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003063 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003064 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003065 if (!D.isInvalidType())
3066 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3067 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3068 << SourceRange(D.getIdentifierLoc());
3069 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003070 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003071 }
John McCall212fa2e2010-04-13 00:04:31 +00003072
3073 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3074
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003075 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003076 // Conversion functions don't have return types, but the parser will
3077 // happily parse something like:
3078 //
3079 // class X {
3080 // float operator bool();
3081 // };
3082 //
3083 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003084 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3085 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3086 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003087 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003088 }
3089
John McCall212fa2e2010-04-13 00:04:31 +00003090 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3091
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003092 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003093 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003094 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3095
3096 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003097 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003098 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003099 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003100 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003101 D.setInvalidType();
3102 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003103
John McCall212fa2e2010-04-13 00:04:31 +00003104 // Diagnose "&operator bool()" and other such nonsense. This
3105 // is actually a gcc extension which we don't support.
3106 if (Proto->getResultType() != ConvType) {
3107 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3108 << Proto->getResultType();
3109 D.setInvalidType();
3110 ConvType = Proto->getResultType();
3111 }
3112
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003113 // C++ [class.conv.fct]p4:
3114 // The conversion-type-id shall not represent a function type nor
3115 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003116 if (ConvType->isArrayType()) {
3117 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3118 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003119 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003120 } else if (ConvType->isFunctionType()) {
3121 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3122 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003123 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003124 }
3125
3126 // Rebuild the function type "R" without any parameters (in case any
3127 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003128 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003129 if (D.isInvalidType()) {
3130 R = Context.getFunctionType(ConvType, 0, 0, false,
3131 Proto->getTypeQuals(),
3132 Proto->hasExceptionSpec(),
3133 Proto->hasAnyExceptionSpec(),
3134 Proto->getNumExceptions(),
3135 Proto->exception_begin(),
3136 Proto->getExtInfo());
3137 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003138
Douglas Gregor5fb53972009-01-14 15:45:31 +00003139 // C++0x explicit conversion operators.
3140 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003141 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003142 diag::warn_explicit_conversion_functions)
3143 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003144}
3145
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003146/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3147/// the declaration of the given C++ conversion function. This routine
3148/// is responsible for recording the conversion function in the C++
3149/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003150Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003151 assert(Conversion && "Expected to receive a conversion function declaration");
3152
Douglas Gregor4287b372008-12-12 08:25:50 +00003153 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003154
3155 // Make sure we aren't redeclaring the conversion function.
3156 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003157
3158 // C++ [class.conv.fct]p1:
3159 // [...] A conversion function is never used to convert a
3160 // (possibly cv-qualified) object to the (possibly cv-qualified)
3161 // same object type (or a reference to it), to a (possibly
3162 // cv-qualified) base class of that type (or a reference to it),
3163 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003164 // FIXME: Suppress this warning if the conversion function ends up being a
3165 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003166 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003167 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003168 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003169 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003170 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3171 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003172 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003173 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003174 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3175 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003176 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003177 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003178 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003179 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003180 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003181 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003182 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003183 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003184 }
3185
Douglas Gregor457104e2010-09-29 04:25:11 +00003186 if (FunctionTemplateDecl *ConversionTemplate
3187 = Conversion->getDescribedFunctionTemplate())
3188 return ConversionTemplate;
3189
John McCall48871652010-08-21 09:40:31 +00003190 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003191}
3192
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003193//===----------------------------------------------------------------------===//
3194// Namespace Handling
3195//===----------------------------------------------------------------------===//
3196
John McCallb1be5232010-08-26 09:15:37 +00003197
3198
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003199/// ActOnStartNamespaceDef - This is called at the start of a namespace
3200/// definition.
John McCall48871652010-08-21 09:40:31 +00003201Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003202 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003203 SourceLocation IdentLoc,
3204 IdentifierInfo *II,
3205 SourceLocation LBrace,
3206 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003207 // anonymous namespace starts at its left brace
3208 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3209 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003210 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003211 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003212
3213 Scope *DeclRegionScope = NamespcScope->getParent();
3214
Anders Carlssona7bcade2010-02-07 01:09:23 +00003215 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3216
Eli Friedman570024a2010-08-05 06:57:20 +00003217 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallb1be5232010-08-26 09:15:37 +00003218 PushVisibilityAttr(attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003219
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003220 if (II) {
3221 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003222 // The identifier in an original-namespace-definition shall not
3223 // have been previously defined in the declarative region in
3224 // which the original-namespace-definition appears. The
3225 // identifier in an original-namespace-definition is the name of
3226 // the namespace. Subsequently in that declarative region, it is
3227 // treated as an original-namespace-name.
3228 //
3229 // Since namespace names are unique in their scope, and we don't
3230 // look through using directives, just
3231 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3232 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003233
Douglas Gregor91f84212008-12-11 16:49:14 +00003234 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3235 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003236 if (Namespc->isInline() != OrigNS->isInline()) {
3237 // inline-ness must match
3238 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3239 << Namespc->isInline();
3240 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3241 Namespc->setInvalidDecl();
3242 // Recover by ignoring the new namespace's inline status.
3243 Namespc->setInline(OrigNS->isInline());
3244 }
3245
Douglas Gregor91f84212008-12-11 16:49:14 +00003246 // Attach this namespace decl to the chain of extended namespace
3247 // definitions.
3248 OrigNS->setNextNamespace(Namespc);
3249 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003250
Mike Stump11289f42009-09-09 15:08:12 +00003251 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003252 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003253 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003254 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003255 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003256 } else if (PrevDecl) {
3257 // This is an invalid name redefinition.
3258 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3259 << Namespc->getDeclName();
3260 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3261 Namespc->setInvalidDecl();
3262 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003263 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003264 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003265 // This is the first "real" definition of the namespace "std", so update
3266 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003267 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003268 // We had already defined a dummy namespace "std". Link this new
3269 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003270 StdNS->setNextNamespace(Namespc);
3271 StdNS->setLocation(IdentLoc);
3272 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003273 }
3274
3275 // Make our StdNamespace cache point at the first real definition of the
3276 // "std" namespace.
3277 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003278 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003279
3280 PushOnScopeChains(Namespc, DeclRegionScope);
3281 } else {
John McCall4fa53422009-10-01 00:25:31 +00003282 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003283 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003284
3285 // Link the anonymous namespace into its parent.
3286 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003287 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003288 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3289 PrevDecl = TU->getAnonymousNamespace();
3290 TU->setAnonymousNamespace(Namespc);
3291 } else {
3292 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3293 PrevDecl = ND->getAnonymousNamespace();
3294 ND->setAnonymousNamespace(Namespc);
3295 }
3296
3297 // Link the anonymous namespace with its previous declaration.
3298 if (PrevDecl) {
3299 assert(PrevDecl->isAnonymousNamespace());
3300 assert(!PrevDecl->getNextNamespace());
3301 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3302 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003303
3304 if (Namespc->isInline() != PrevDecl->isInline()) {
3305 // inline-ness must match
3306 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3307 << Namespc->isInline();
3308 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3309 Namespc->setInvalidDecl();
3310 // Recover by ignoring the new namespace's inline status.
3311 Namespc->setInline(PrevDecl->isInline());
3312 }
John McCall0db42252009-12-16 02:06:49 +00003313 }
John McCall4fa53422009-10-01 00:25:31 +00003314
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003315 CurContext->addDecl(Namespc);
3316
John McCall4fa53422009-10-01 00:25:31 +00003317 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3318 // behaves as if it were replaced by
3319 // namespace unique { /* empty body */ }
3320 // using namespace unique;
3321 // namespace unique { namespace-body }
3322 // where all occurrences of 'unique' in a translation unit are
3323 // replaced by the same identifier and this identifier differs
3324 // from all other identifiers in the entire program.
3325
3326 // We just create the namespace with an empty name and then add an
3327 // implicit using declaration, just like the standard suggests.
3328 //
3329 // CodeGen enforces the "universally unique" aspect by giving all
3330 // declarations semantically contained within an anonymous
3331 // namespace internal linkage.
3332
John McCall0db42252009-12-16 02:06:49 +00003333 if (!PrevDecl) {
3334 UsingDirectiveDecl* UD
3335 = UsingDirectiveDecl::Create(Context, CurContext,
3336 /* 'using' */ LBrace,
3337 /* 'namespace' */ SourceLocation(),
3338 /* qualifier */ SourceRange(),
3339 /* NNS */ NULL,
3340 /* identifier */ SourceLocation(),
3341 Namespc,
3342 /* Ancestor */ CurContext);
3343 UD->setImplicit();
3344 CurContext->addDecl(UD);
3345 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003346 }
3347
3348 // Although we could have an invalid decl (i.e. the namespace name is a
3349 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003350 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3351 // for the namespace has the declarations that showed up in that particular
3352 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003353 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003354 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003355}
3356
Sebastian Redla6602e92009-11-23 15:34:23 +00003357/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3358/// is a namespace alias, returns the namespace it points to.
3359static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3360 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3361 return AD->getNamespace();
3362 return dyn_cast_or_null<NamespaceDecl>(D);
3363}
3364
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003365/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3366/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003367void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003368 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3369 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3370 Namespc->setRBracLoc(RBrace);
3371 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003372 if (Namespc->hasAttr<VisibilityAttr>())
3373 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003374}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003375
John McCall28a0cf72010-08-25 07:42:41 +00003376CXXRecordDecl *Sema::getStdBadAlloc() const {
3377 return cast_or_null<CXXRecordDecl>(
3378 StdBadAlloc.get(Context.getExternalSource()));
3379}
3380
3381NamespaceDecl *Sema::getStdNamespace() const {
3382 return cast_or_null<NamespaceDecl>(
3383 StdNamespace.get(Context.getExternalSource()));
3384}
3385
Douglas Gregorcdf87022010-06-29 17:53:46 +00003386/// \brief Retrieve the special "std" namespace, which may require us to
3387/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003388NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003389 if (!StdNamespace) {
3390 // The "std" namespace has not yet been defined, so build one implicitly.
3391 StdNamespace = NamespaceDecl::Create(Context,
3392 Context.getTranslationUnitDecl(),
3393 SourceLocation(),
3394 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003395 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003396 }
3397
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003398 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003399}
3400
John McCall48871652010-08-21 09:40:31 +00003401Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003402 SourceLocation UsingLoc,
3403 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003404 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003405 SourceLocation IdentLoc,
3406 IdentifierInfo *NamespcName,
3407 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003408 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3409 assert(NamespcName && "Invalid NamespcName.");
3410 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003411
3412 // This can only happen along a recovery path.
3413 while (S->getFlags() & Scope::TemplateParamScope)
3414 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003415 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003416
Douglas Gregor889ceb72009-02-03 19:21:40 +00003417 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003418 NestedNameSpecifier *Qualifier = 0;
3419 if (SS.isSet())
3420 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3421
Douglas Gregor34074322009-01-14 22:20:51 +00003422 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003423 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3424 LookupParsedName(R, S, &SS);
3425 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003426 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003427
Douglas Gregorcdf87022010-06-29 17:53:46 +00003428 if (R.empty()) {
3429 // Allow "using namespace std;" or "using namespace ::std;" even if
3430 // "std" hasn't been defined yet, for GCC compatibility.
3431 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3432 NamespcName->isStr("std")) {
3433 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003434 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003435 R.resolveKind();
3436 }
3437 // Otherwise, attempt typo correction.
3438 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3439 CTC_NoKeywords, 0)) {
3440 if (R.getAsSingle<NamespaceDecl>() ||
3441 R.getAsSingle<NamespaceAliasDecl>()) {
3442 if (DeclContext *DC = computeDeclContext(SS, false))
3443 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3444 << NamespcName << DC << Corrected << SS.getRange()
3445 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3446 else
3447 Diag(IdentLoc, diag::err_using_directive_suggest)
3448 << NamespcName << Corrected
3449 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3450 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3451 << Corrected;
3452
3453 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003454 } else {
3455 R.clear();
3456 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003457 }
3458 }
3459 }
3460
John McCall9f3059a2009-10-09 21:13:30 +00003461 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003462 NamedDecl *Named = R.getFoundDecl();
3463 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3464 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003465 // C++ [namespace.udir]p1:
3466 // A using-directive specifies that the names in the nominated
3467 // namespace can be used in the scope in which the
3468 // using-directive appears after the using-directive. During
3469 // unqualified name lookup (3.4.1), the names appear as if they
3470 // were declared in the nearest enclosing namespace which
3471 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003472 // namespace. [Note: in this context, "contains" means "contains
3473 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003474
3475 // Find enclosing context containing both using-directive and
3476 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003477 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003478 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3479 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3480 CommonAncestor = CommonAncestor->getParent();
3481
Sebastian Redla6602e92009-11-23 15:34:23 +00003482 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003483 SS.getRange(),
3484 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003485 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003486 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003487 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003488 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003489 }
3490
Douglas Gregor889ceb72009-02-03 19:21:40 +00003491 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003492 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003493}
3494
3495void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3496 // If scope has associated entity, then using directive is at namespace
3497 // or translation unit scope. We add UsingDirectiveDecls, into
3498 // it's lookup structure.
3499 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003500 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003501 else
3502 // Otherwise it is block-sope. using-directives will affect lookup
3503 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003504 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003505}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003506
Douglas Gregorfec52632009-06-20 00:51:54 +00003507
John McCall48871652010-08-21 09:40:31 +00003508Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003509 AccessSpecifier AS,
3510 bool HasUsingKeyword,
3511 SourceLocation UsingLoc,
3512 CXXScopeSpec &SS,
3513 UnqualifiedId &Name,
3514 AttributeList *AttrList,
3515 bool IsTypeName,
3516 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003517 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003518
Douglas Gregor220f4272009-11-04 16:30:06 +00003519 switch (Name.getKind()) {
3520 case UnqualifiedId::IK_Identifier:
3521 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003522 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003523 case UnqualifiedId::IK_ConversionFunctionId:
3524 break;
3525
3526 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003527 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003528 // C++0x inherited constructors.
3529 if (getLangOptions().CPlusPlus0x) break;
3530
Douglas Gregor220f4272009-11-04 16:30:06 +00003531 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
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_DestructorName:
3536 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3537 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003538 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003539
3540 case UnqualifiedId::IK_TemplateId:
3541 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3542 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003543 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003544 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003545
3546 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3547 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003548 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003549 return 0;
John McCall3969e302009-12-08 07:46:18 +00003550
John McCalla0097262009-12-11 02:10:03 +00003551 // Warn about using declarations.
3552 // TODO: store that the declaration was written without 'using' and
3553 // talk about access decls instead of using decls in the
3554 // diagnostics.
3555 if (!HasUsingKeyword) {
3556 UsingLoc = Name.getSourceRange().getBegin();
3557
3558 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003559 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003560 }
3561
John McCall3f746822009-11-17 05:59:44 +00003562 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003563 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003564 /* IsInstantiation */ false,
3565 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003566 if (UD)
3567 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003568
John McCall48871652010-08-21 09:40:31 +00003569 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003570}
3571
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003572/// \brief Determine whether a using declaration considers the given
3573/// declarations as "equivalent", e.g., if they are redeclarations of
3574/// the same entity or are both typedefs of the same type.
3575static bool
3576IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3577 bool &SuppressRedeclaration) {
3578 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3579 SuppressRedeclaration = false;
3580 return true;
3581 }
3582
3583 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3584 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3585 SuppressRedeclaration = true;
3586 return Context.hasSameType(TD1->getUnderlyingType(),
3587 TD2->getUnderlyingType());
3588 }
3589
3590 return false;
3591}
3592
3593
John McCall84d87672009-12-10 09:41:52 +00003594/// Determines whether to create a using shadow decl for a particular
3595/// decl, given the set of decls existing prior to this using lookup.
3596bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3597 const LookupResult &Previous) {
3598 // Diagnose finding a decl which is not from a base class of the
3599 // current class. We do this now because there are cases where this
3600 // function will silently decide not to build a shadow decl, which
3601 // will pre-empt further diagnostics.
3602 //
3603 // We don't need to do this in C++0x because we do the check once on
3604 // the qualifier.
3605 //
3606 // FIXME: diagnose the following if we care enough:
3607 // struct A { int foo; };
3608 // struct B : A { using A::foo; };
3609 // template <class T> struct C : A {};
3610 // template <class T> struct D : C<T> { using B::foo; } // <---
3611 // This is invalid (during instantiation) in C++03 because B::foo
3612 // resolves to the using decl in B, which is not a base class of D<T>.
3613 // We can't diagnose it immediately because C<T> is an unknown
3614 // specialization. The UsingShadowDecl in D<T> then points directly
3615 // to A::foo, which will look well-formed when we instantiate.
3616 // The right solution is to not collapse the shadow-decl chain.
3617 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3618 DeclContext *OrigDC = Orig->getDeclContext();
3619
3620 // Handle enums and anonymous structs.
3621 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3622 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3623 while (OrigRec->isAnonymousStructOrUnion())
3624 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3625
3626 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3627 if (OrigDC == CurContext) {
3628 Diag(Using->getLocation(),
3629 diag::err_using_decl_nested_name_specifier_is_current_class)
3630 << Using->getNestedNameRange();
3631 Diag(Orig->getLocation(), diag::note_using_decl_target);
3632 return true;
3633 }
3634
3635 Diag(Using->getNestedNameRange().getBegin(),
3636 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3637 << Using->getTargetNestedNameDecl()
3638 << cast<CXXRecordDecl>(CurContext)
3639 << Using->getNestedNameRange();
3640 Diag(Orig->getLocation(), diag::note_using_decl_target);
3641 return true;
3642 }
3643 }
3644
3645 if (Previous.empty()) return false;
3646
3647 NamedDecl *Target = Orig;
3648 if (isa<UsingShadowDecl>(Target))
3649 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3650
John McCalla17e83e2009-12-11 02:33:26 +00003651 // If the target happens to be one of the previous declarations, we
3652 // don't have a conflict.
3653 //
3654 // FIXME: but we might be increasing its access, in which case we
3655 // should redeclare it.
3656 NamedDecl *NonTag = 0, *Tag = 0;
3657 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3658 I != E; ++I) {
3659 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003660 bool Result;
3661 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3662 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003663
3664 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3665 }
3666
John McCall84d87672009-12-10 09:41:52 +00003667 if (Target->isFunctionOrFunctionTemplate()) {
3668 FunctionDecl *FD;
3669 if (isa<FunctionTemplateDecl>(Target))
3670 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3671 else
3672 FD = cast<FunctionDecl>(Target);
3673
3674 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003675 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003676 case Ovl_Overload:
3677 return false;
3678
3679 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003680 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003681 break;
3682
3683 // We found a decl with the exact signature.
3684 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003685 // If we're in a record, we want to hide the target, so we
3686 // return true (without a diagnostic) to tell the caller not to
3687 // build a shadow decl.
3688 if (CurContext->isRecord())
3689 return true;
3690
3691 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003692 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003693 break;
3694 }
3695
3696 Diag(Target->getLocation(), diag::note_using_decl_target);
3697 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3698 return true;
3699 }
3700
3701 // Target is not a function.
3702
John McCall84d87672009-12-10 09:41:52 +00003703 if (isa<TagDecl>(Target)) {
3704 // No conflict between a tag and a non-tag.
3705 if (!Tag) return false;
3706
John McCalle29c5cd2009-12-10 19:51:03 +00003707 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003708 Diag(Target->getLocation(), diag::note_using_decl_target);
3709 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3710 return true;
3711 }
3712
3713 // No conflict between a tag and a non-tag.
3714 if (!NonTag) return false;
3715
John McCalle29c5cd2009-12-10 19:51:03 +00003716 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003717 Diag(Target->getLocation(), diag::note_using_decl_target);
3718 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3719 return true;
3720}
3721
John McCall3f746822009-11-17 05:59:44 +00003722/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003723UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003724 UsingDecl *UD,
3725 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003726
3727 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003728 NamedDecl *Target = Orig;
3729 if (isa<UsingShadowDecl>(Target)) {
3730 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3731 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003732 }
3733
3734 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003735 = UsingShadowDecl::Create(Context, CurContext,
3736 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003737 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003738
3739 Shadow->setAccess(UD->getAccess());
3740 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3741 Shadow->setInvalidDecl();
3742
John McCall3f746822009-11-17 05:59:44 +00003743 if (S)
John McCall3969e302009-12-08 07:46:18 +00003744 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003745 else
John McCall3969e302009-12-08 07:46:18 +00003746 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003747
John McCall3969e302009-12-08 07:46:18 +00003748
John McCall84d87672009-12-10 09:41:52 +00003749 return Shadow;
3750}
John McCall3969e302009-12-08 07:46:18 +00003751
John McCall84d87672009-12-10 09:41:52 +00003752/// Hides a using shadow declaration. This is required by the current
3753/// using-decl implementation when a resolvable using declaration in a
3754/// class is followed by a declaration which would hide or override
3755/// one or more of the using decl's targets; for example:
3756///
3757/// struct Base { void foo(int); };
3758/// struct Derived : Base {
3759/// using Base::foo;
3760/// void foo(int);
3761/// };
3762///
3763/// The governing language is C++03 [namespace.udecl]p12:
3764///
3765/// When a using-declaration brings names from a base class into a
3766/// derived class scope, member functions in the derived class
3767/// override and/or hide member functions with the same name and
3768/// parameter types in a base class (rather than conflicting).
3769///
3770/// There are two ways to implement this:
3771/// (1) optimistically create shadow decls when they're not hidden
3772/// by existing declarations, or
3773/// (2) don't create any shadow decls (or at least don't make them
3774/// visible) until we've fully parsed/instantiated the class.
3775/// The problem with (1) is that we might have to retroactively remove
3776/// a shadow decl, which requires several O(n) operations because the
3777/// decl structures are (very reasonably) not designed for removal.
3778/// (2) avoids this but is very fiddly and phase-dependent.
3779void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003780 if (Shadow->getDeclName().getNameKind() ==
3781 DeclarationName::CXXConversionFunctionName)
3782 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3783
John McCall84d87672009-12-10 09:41:52 +00003784 // Remove it from the DeclContext...
3785 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003786
John McCall84d87672009-12-10 09:41:52 +00003787 // ...and the scope, if applicable...
3788 if (S) {
John McCall48871652010-08-21 09:40:31 +00003789 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003790 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003791 }
3792
John McCall84d87672009-12-10 09:41:52 +00003793 // ...and the using decl.
3794 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3795
3796 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003797 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003798}
3799
John McCalle61f2ba2009-11-18 02:36:19 +00003800/// Builds a using declaration.
3801///
3802/// \param IsInstantiation - Whether this call arises from an
3803/// instantiation of an unresolved using declaration. We treat
3804/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003805NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3806 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003807 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003808 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003809 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003810 bool IsInstantiation,
3811 bool IsTypeName,
3812 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003813 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003814 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003815 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003816
Anders Carlssonf038fc22009-08-28 05:49:21 +00003817 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003818
Anders Carlsson59140b32009-08-28 03:16:11 +00003819 if (SS.isEmpty()) {
3820 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003821 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003822 }
Mike Stump11289f42009-09-09 15:08:12 +00003823
John McCall84d87672009-12-10 09:41:52 +00003824 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003825 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003826 ForRedeclaration);
3827 Previous.setHideTags(false);
3828 if (S) {
3829 LookupName(Previous, S);
3830
3831 // It is really dumb that we have to do this.
3832 LookupResult::Filter F = Previous.makeFilter();
3833 while (F.hasNext()) {
3834 NamedDecl *D = F.next();
3835 if (!isDeclInScope(D, CurContext, S))
3836 F.erase();
3837 }
3838 F.done();
3839 } else {
3840 assert(IsInstantiation && "no scope in non-instantiation");
3841 assert(CurContext->isRecord() && "scope not record in instantiation");
3842 LookupQualifiedName(Previous, CurContext);
3843 }
3844
Mike Stump11289f42009-09-09 15:08:12 +00003845 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003846 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3847
John McCall84d87672009-12-10 09:41:52 +00003848 // Check for invalid redeclarations.
3849 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3850 return 0;
3851
3852 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003853 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3854 return 0;
3855
John McCall84c16cf2009-11-12 03:15:40 +00003856 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003857 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003858 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003859 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003860 // FIXME: not all declaration name kinds are legal here
3861 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3862 UsingLoc, TypenameLoc,
3863 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003864 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003865 } else {
3866 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003867 UsingLoc, SS.getRange(),
3868 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003869 }
John McCallb96ec562009-12-04 22:46:56 +00003870 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003871 D = UsingDecl::Create(Context, CurContext,
3872 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003873 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003874 }
John McCallb96ec562009-12-04 22:46:56 +00003875 D->setAccess(AS);
3876 CurContext->addDecl(D);
3877
3878 if (!LookupContext) return D;
3879 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003880
John McCall0b66eb32010-05-01 00:40:08 +00003881 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003882 UD->setInvalidDecl();
3883 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003884 }
3885
John McCall3969e302009-12-08 07:46:18 +00003886 // Look up the target name.
3887
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003888 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003889
John McCall3969e302009-12-08 07:46:18 +00003890 // Unlike most lookups, we don't always want to hide tag
3891 // declarations: tag names are visible through the using declaration
3892 // even if hidden by ordinary names, *except* in a dependent context
3893 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003894 if (!IsInstantiation)
3895 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003896
John McCall27b18f82009-11-17 02:14:36 +00003897 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003898
John McCall9f3059a2009-10-09 21:13:30 +00003899 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003900 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003901 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003902 UD->setInvalidDecl();
3903 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003904 }
3905
John McCallb96ec562009-12-04 22:46:56 +00003906 if (R.isAmbiguous()) {
3907 UD->setInvalidDecl();
3908 return UD;
3909 }
Mike Stump11289f42009-09-09 15:08:12 +00003910
John McCalle61f2ba2009-11-18 02:36:19 +00003911 if (IsTypeName) {
3912 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003913 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003914 Diag(IdentLoc, diag::err_using_typename_non_type);
3915 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3916 Diag((*I)->getUnderlyingDecl()->getLocation(),
3917 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003918 UD->setInvalidDecl();
3919 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003920 }
3921 } else {
3922 // If we asked for a non-typename and we got a type, error out,
3923 // but only if this is an instantiation of an unresolved using
3924 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003925 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003926 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3927 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003928 UD->setInvalidDecl();
3929 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003930 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003931 }
3932
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003933 // C++0x N2914 [namespace.udecl]p6:
3934 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003935 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003936 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3937 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003938 UD->setInvalidDecl();
3939 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003940 }
Mike Stump11289f42009-09-09 15:08:12 +00003941
John McCall84d87672009-12-10 09:41:52 +00003942 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3943 if (!CheckUsingShadowDecl(UD, *I, Previous))
3944 BuildUsingShadowDecl(S, UD, *I);
3945 }
John McCall3f746822009-11-17 05:59:44 +00003946
3947 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003948}
3949
John McCall84d87672009-12-10 09:41:52 +00003950/// Checks that the given using declaration is not an invalid
3951/// redeclaration. Note that this is checking only for the using decl
3952/// itself, not for any ill-formedness among the UsingShadowDecls.
3953bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3954 bool isTypeName,
3955 const CXXScopeSpec &SS,
3956 SourceLocation NameLoc,
3957 const LookupResult &Prev) {
3958 // C++03 [namespace.udecl]p8:
3959 // C++0x [namespace.udecl]p10:
3960 // A using-declaration is a declaration and can therefore be used
3961 // repeatedly where (and only where) multiple declarations are
3962 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003963 //
John McCall032092f2010-11-29 18:01:58 +00003964 // That's in non-member contexts.
3965 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003966 return false;
3967
3968 NestedNameSpecifier *Qual
3969 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3970
3971 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3972 NamedDecl *D = *I;
3973
3974 bool DTypename;
3975 NestedNameSpecifier *DQual;
3976 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3977 DTypename = UD->isTypeName();
3978 DQual = UD->getTargetNestedNameDecl();
3979 } else if (UnresolvedUsingValueDecl *UD
3980 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3981 DTypename = false;
3982 DQual = UD->getTargetNestedNameSpecifier();
3983 } else if (UnresolvedUsingTypenameDecl *UD
3984 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3985 DTypename = true;
3986 DQual = UD->getTargetNestedNameSpecifier();
3987 } else continue;
3988
3989 // using decls differ if one says 'typename' and the other doesn't.
3990 // FIXME: non-dependent using decls?
3991 if (isTypeName != DTypename) continue;
3992
3993 // using decls differ if they name different scopes (but note that
3994 // template instantiation can cause this check to trigger when it
3995 // didn't before instantiation).
3996 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3997 Context.getCanonicalNestedNameSpecifier(DQual))
3998 continue;
3999
4000 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004001 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004002 return true;
4003 }
4004
4005 return false;
4006}
4007
John McCall3969e302009-12-08 07:46:18 +00004008
John McCallb96ec562009-12-04 22:46:56 +00004009/// Checks that the given nested-name qualifier used in a using decl
4010/// in the current context is appropriately related to the current
4011/// scope. If an error is found, diagnoses it and returns true.
4012bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4013 const CXXScopeSpec &SS,
4014 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004015 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004016
John McCall3969e302009-12-08 07:46:18 +00004017 if (!CurContext->isRecord()) {
4018 // C++03 [namespace.udecl]p3:
4019 // C++0x [namespace.udecl]p8:
4020 // A using-declaration for a class member shall be a member-declaration.
4021
4022 // If we weren't able to compute a valid scope, it must be a
4023 // dependent class scope.
4024 if (!NamedContext || NamedContext->isRecord()) {
4025 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4026 << SS.getRange();
4027 return true;
4028 }
4029
4030 // Otherwise, everything is known to be fine.
4031 return false;
4032 }
4033
4034 // The current scope is a record.
4035
4036 // If the named context is dependent, we can't decide much.
4037 if (!NamedContext) {
4038 // FIXME: in C++0x, we can diagnose if we can prove that the
4039 // nested-name-specifier does not refer to a base class, which is
4040 // still possible in some cases.
4041
4042 // Otherwise we have to conservatively report that things might be
4043 // okay.
4044 return false;
4045 }
4046
4047 if (!NamedContext->isRecord()) {
4048 // Ideally this would point at the last name in the specifier,
4049 // but we don't have that level of source info.
4050 Diag(SS.getRange().getBegin(),
4051 diag::err_using_decl_nested_name_specifier_is_not_class)
4052 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4053 return true;
4054 }
4055
4056 if (getLangOptions().CPlusPlus0x) {
4057 // C++0x [namespace.udecl]p3:
4058 // In a using-declaration used as a member-declaration, the
4059 // nested-name-specifier shall name a base class of the class
4060 // being defined.
4061
4062 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4063 cast<CXXRecordDecl>(NamedContext))) {
4064 if (CurContext == NamedContext) {
4065 Diag(NameLoc,
4066 diag::err_using_decl_nested_name_specifier_is_current_class)
4067 << SS.getRange();
4068 return true;
4069 }
4070
4071 Diag(SS.getRange().getBegin(),
4072 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4073 << (NestedNameSpecifier*) SS.getScopeRep()
4074 << cast<CXXRecordDecl>(CurContext)
4075 << SS.getRange();
4076 return true;
4077 }
4078
4079 return false;
4080 }
4081
4082 // C++03 [namespace.udecl]p4:
4083 // A using-declaration used as a member-declaration shall refer
4084 // to a member of a base class of the class being defined [etc.].
4085
4086 // Salient point: SS doesn't have to name a base class as long as
4087 // lookup only finds members from base classes. Therefore we can
4088 // diagnose here only if we can prove that that can't happen,
4089 // i.e. if the class hierarchies provably don't intersect.
4090
4091 // TODO: it would be nice if "definitely valid" results were cached
4092 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4093 // need to be repeated.
4094
4095 struct UserData {
4096 llvm::DenseSet<const CXXRecordDecl*> Bases;
4097
4098 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4099 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4100 Data->Bases.insert(Base);
4101 return true;
4102 }
4103
4104 bool hasDependentBases(const CXXRecordDecl *Class) {
4105 return !Class->forallBases(collect, this);
4106 }
4107
4108 /// Returns true if the base is dependent or is one of the
4109 /// accumulated base classes.
4110 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4111 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4112 return !Data->Bases.count(Base);
4113 }
4114
4115 bool mightShareBases(const CXXRecordDecl *Class) {
4116 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4117 }
4118 };
4119
4120 UserData Data;
4121
4122 // Returns false if we find a dependent base.
4123 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4124 return false;
4125
4126 // Returns false if the class has a dependent base or if it or one
4127 // of its bases is present in the base set of the current context.
4128 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4129 return false;
4130
4131 Diag(SS.getRange().getBegin(),
4132 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4133 << (NestedNameSpecifier*) SS.getScopeRep()
4134 << cast<CXXRecordDecl>(CurContext)
4135 << SS.getRange();
4136
4137 return true;
John McCallb96ec562009-12-04 22:46:56 +00004138}
4139
John McCall48871652010-08-21 09:40:31 +00004140Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004141 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004142 SourceLocation AliasLoc,
4143 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004144 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004145 SourceLocation IdentLoc,
4146 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004147
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004148 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004149 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4150 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004151
Anders Carlssondca83c42009-03-28 06:23:46 +00004152 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004153 NamedDecl *PrevDecl
4154 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4155 ForRedeclaration);
4156 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4157 PrevDecl = 0;
4158
4159 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004160 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004161 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004162 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004163 // FIXME: At some point, we'll want to create the (redundant)
4164 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004165 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004166 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004167 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004168 }
Mike Stump11289f42009-09-09 15:08:12 +00004169
Anders Carlssondca83c42009-03-28 06:23:46 +00004170 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4171 diag::err_redefinition_different_kind;
4172 Diag(AliasLoc, DiagID) << Alias;
4173 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004174 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004175 }
4176
John McCall27b18f82009-11-17 02:14:36 +00004177 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004178 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004179
John McCall9f3059a2009-10-09 21:13:30 +00004180 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004181 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4182 CTC_NoKeywords, 0)) {
4183 if (R.getAsSingle<NamespaceDecl>() ||
4184 R.getAsSingle<NamespaceAliasDecl>()) {
4185 if (DeclContext *DC = computeDeclContext(SS, false))
4186 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4187 << Ident << DC << Corrected << SS.getRange()
4188 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4189 else
4190 Diag(IdentLoc, diag::err_using_directive_suggest)
4191 << Ident << Corrected
4192 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4193
4194 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4195 << Corrected;
4196
4197 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004198 } else {
4199 R.clear();
4200 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004201 }
4202 }
4203
4204 if (R.empty()) {
4205 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004206 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004207 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004208 }
Mike Stump11289f42009-09-09 15:08:12 +00004209
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004210 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004211 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4212 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004213 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004214 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004215
John McCalld8d0d432010-02-16 06:53:13 +00004216 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004217 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004218}
4219
Douglas Gregora57478e2010-05-01 15:04:51 +00004220namespace {
4221 /// \brief Scoped object used to handle the state changes required in Sema
4222 /// to implicitly define the body of a C++ member function;
4223 class ImplicitlyDefinedFunctionScope {
4224 Sema &S;
4225 DeclContext *PreviousContext;
4226
4227 public:
4228 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4229 : S(S), PreviousContext(S.CurContext)
4230 {
4231 S.CurContext = Method;
4232 S.PushFunctionScope();
4233 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4234 }
4235
4236 ~ImplicitlyDefinedFunctionScope() {
4237 S.PopExpressionEvaluationContext();
4238 S.PopFunctionOrBlockScope();
4239 S.CurContext = PreviousContext;
4240 }
4241 };
4242}
4243
Sebastian Redlc15c3262010-09-13 22:02:47 +00004244static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4245 CXXRecordDecl *D) {
4246 ASTContext &Context = Self.Context;
4247 QualType ClassType = Context.getTypeDeclType(D);
4248 DeclarationName ConstructorName
4249 = Context.DeclarationNames.getCXXConstructorName(
4250 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4251
4252 DeclContext::lookup_const_iterator Con, ConEnd;
4253 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4254 Con != ConEnd; ++Con) {
4255 // FIXME: In C++0x, a constructor template can be a default constructor.
4256 if (isa<FunctionTemplateDecl>(*Con))
4257 continue;
4258
4259 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4260 if (Constructor->isDefaultConstructor())
4261 return Constructor;
4262 }
4263 return 0;
4264}
4265
Douglas Gregor0be31a22010-07-02 17:43:08 +00004266CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4267 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004268 // C++ [class.ctor]p5:
4269 // A default constructor for a class X is a constructor of class X
4270 // that can be called without an argument. If there is no
4271 // user-declared constructor for class X, a default constructor is
4272 // implicitly declared. An implicitly-declared default constructor
4273 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004274 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4275 "Should not build implicit default constructor!");
4276
Douglas Gregor6d880b12010-07-01 22:31:05 +00004277 // C++ [except.spec]p14:
4278 // An implicitly declared special member function (Clause 12) shall have an
4279 // exception-specification. [...]
4280 ImplicitExceptionSpecification ExceptSpec(Context);
4281
4282 // Direct base-class destructors.
4283 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4284 BEnd = ClassDecl->bases_end();
4285 B != BEnd; ++B) {
4286 if (B->isVirtual()) // Handled below.
4287 continue;
4288
Douglas Gregor9672f922010-07-03 00:47:00 +00004289 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4290 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4291 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4292 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004293 else if (CXXConstructorDecl *Constructor
4294 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004295 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004296 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004297 }
4298
4299 // Virtual base-class destructors.
4300 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4301 BEnd = ClassDecl->vbases_end();
4302 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004303 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4304 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4305 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4306 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4307 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004308 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004309 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004310 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004311 }
4312
4313 // Field destructors.
4314 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4315 FEnd = ClassDecl->field_end();
4316 F != FEnd; ++F) {
4317 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004318 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4319 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4320 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4321 ExceptSpec.CalledDecl(
4322 DeclareImplicitDefaultConstructor(FieldClassDecl));
4323 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004324 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004325 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004326 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004327 }
4328
4329
4330 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004331 CanQualType ClassType
4332 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4333 DeclarationName Name
4334 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004335 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004336 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004337 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004338 Context.getFunctionType(Context.VoidTy,
4339 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004340 ExceptSpec.hasExceptionSpecification(),
4341 ExceptSpec.hasAnyExceptionSpecification(),
4342 ExceptSpec.size(),
4343 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004344 FunctionType::ExtInfo()),
4345 /*TInfo=*/0,
4346 /*isExplicit=*/false,
4347 /*isInline=*/true,
4348 /*isImplicitlyDeclared=*/true);
4349 DefaultCon->setAccess(AS_public);
4350 DefaultCon->setImplicit();
4351 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004352
4353 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004354 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4355
Douglas Gregor0be31a22010-07-02 17:43:08 +00004356 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004357 PushOnScopeChains(DefaultCon, S, false);
4358 ClassDecl->addDecl(DefaultCon);
4359
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004360 return DefaultCon;
4361}
4362
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004363void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4364 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004365 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004366 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004367 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004368
Anders Carlsson423f5d82010-04-23 16:04:08 +00004369 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004370 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004371
Douglas Gregora57478e2010-05-01 15:04:51 +00004372 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004373 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor54818f02010-05-12 16:39:35 +00004374 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4375 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004376 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004377 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004378 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004379 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004380 }
Douglas Gregor73193272010-09-20 16:48:21 +00004381
4382 SourceLocation Loc = Constructor->getLocation();
4383 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4384
4385 Constructor->setUsed();
4386 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004387}
4388
Douglas Gregor0be31a22010-07-02 17:43:08 +00004389CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004390 // C++ [class.dtor]p2:
4391 // If a class has no user-declared destructor, a destructor is
4392 // declared implicitly. An implicitly-declared destructor is an
4393 // inline public member of its class.
4394
4395 // C++ [except.spec]p14:
4396 // An implicitly declared special member function (Clause 12) shall have
4397 // an exception-specification.
4398 ImplicitExceptionSpecification ExceptSpec(Context);
4399
4400 // Direct base-class destructors.
4401 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4402 BEnd = ClassDecl->bases_end();
4403 B != BEnd; ++B) {
4404 if (B->isVirtual()) // Handled below.
4405 continue;
4406
4407 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4408 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004409 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004410 }
4411
4412 // Virtual base-class destructors.
4413 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4414 BEnd = ClassDecl->vbases_end();
4415 B != BEnd; ++B) {
4416 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4417 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004418 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004419 }
4420
4421 // Field destructors.
4422 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4423 FEnd = ClassDecl->field_end();
4424 F != FEnd; ++F) {
4425 if (const RecordType *RecordTy
4426 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4427 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004428 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004429 }
4430
Douglas Gregor7454c562010-07-02 20:37:36 +00004431 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004432 QualType Ty = Context.getFunctionType(Context.VoidTy,
4433 0, 0, false, 0,
4434 ExceptSpec.hasExceptionSpecification(),
4435 ExceptSpec.hasAnyExceptionSpecification(),
4436 ExceptSpec.size(),
4437 ExceptSpec.data(),
4438 FunctionType::ExtInfo());
4439
4440 CanQualType ClassType
4441 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4442 DeclarationName Name
4443 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004444 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004445 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004446 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004447 /*isInline=*/true,
4448 /*isImplicitlyDeclared=*/true);
4449 Destructor->setAccess(AS_public);
4450 Destructor->setImplicit();
4451 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004452
4453 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004454 ++ASTContext::NumImplicitDestructorsDeclared;
4455
4456 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004457 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004458 PushOnScopeChains(Destructor, S, false);
4459 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004460
4461 // This could be uniqued if it ever proves significant.
4462 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4463
4464 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004465
Douglas Gregorf1203042010-07-01 19:09:28 +00004466 return Destructor;
4467}
4468
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004469void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004470 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004471 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004472 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004473 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004474 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004475
Douglas Gregor54818f02010-05-12 16:39:35 +00004476 if (Destructor->isInvalidDecl())
4477 return;
4478
Douglas Gregora57478e2010-05-01 15:04:51 +00004479 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004480
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004481 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004482 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4483 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004484
Douglas Gregor54818f02010-05-12 16:39:35 +00004485 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004486 Diag(CurrentLocation, diag::note_member_synthesized_at)
4487 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4488
4489 Destructor->setInvalidDecl();
4490 return;
4491 }
4492
Douglas Gregor73193272010-09-20 16:48:21 +00004493 SourceLocation Loc = Destructor->getLocation();
4494 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4495
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004496 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004497 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004498}
4499
Douglas Gregorb139cd52010-05-01 20:49:11 +00004500/// \brief Builds a statement that copies the given entity from \p From to
4501/// \c To.
4502///
4503/// This routine is used to copy the members of a class with an
4504/// implicitly-declared copy assignment operator. When the entities being
4505/// copied are arrays, this routine builds for loops to copy them.
4506///
4507/// \param S The Sema object used for type-checking.
4508///
4509/// \param Loc The location where the implicit copy is being generated.
4510///
4511/// \param T The type of the expressions being copied. Both expressions must
4512/// have this type.
4513///
4514/// \param To The expression we are copying to.
4515///
4516/// \param From The expression we are copying from.
4517///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004518/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4519/// Otherwise, it's a non-static member subobject.
4520///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004521/// \param Depth Internal parameter recording the depth of the recursion.
4522///
4523/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004524static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004525BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004526 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004527 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004528 // C++0x [class.copy]p30:
4529 // Each subobject is assigned in the manner appropriate to its type:
4530 //
4531 // - if the subobject is of class type, the copy assignment operator
4532 // for the class is used (as if by explicit qualification; that is,
4533 // ignoring any possible virtual overriding functions in more derived
4534 // classes);
4535 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4536 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4537
4538 // Look for operator=.
4539 DeclarationName Name
4540 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4541 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4542 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4543
4544 // Filter out any result that isn't a copy-assignment operator.
4545 LookupResult::Filter F = OpLookup.makeFilter();
4546 while (F.hasNext()) {
4547 NamedDecl *D = F.next();
4548 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4549 if (Method->isCopyAssignmentOperator())
4550 continue;
4551
4552 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004553 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004554 F.done();
4555
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004556 // Suppress the protected check (C++ [class.protected]) for each of the
4557 // assignment operators we found. This strange dance is required when
4558 // we're assigning via a base classes's copy-assignment operator. To
4559 // ensure that we're getting the right base class subobject (without
4560 // ambiguities), we need to cast "this" to that subobject type; to
4561 // ensure that we don't go through the virtual call mechanism, we need
4562 // to qualify the operator= name with the base class (see below). However,
4563 // this means that if the base class has a protected copy assignment
4564 // operator, the protected member access check will fail. So, we
4565 // rewrite "protected" access to "public" access in this case, since we
4566 // know by construction that we're calling from a derived class.
4567 if (CopyingBaseSubobject) {
4568 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4569 L != LEnd; ++L) {
4570 if (L.getAccess() == AS_protected)
4571 L.setAccess(AS_public);
4572 }
4573 }
4574
Douglas Gregorb139cd52010-05-01 20:49:11 +00004575 // Create the nested-name-specifier that will be used to qualify the
4576 // reference to operator=; this is required to suppress the virtual
4577 // call mechanism.
4578 CXXScopeSpec SS;
4579 SS.setRange(Loc);
4580 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4581 T.getTypePtr()));
4582
4583 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004584 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004585 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004586 /*FirstQualifierInScope=*/0, OpLookup,
4587 /*TemplateArgs=*/0,
4588 /*SuppressQualifierCheck=*/true);
4589 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004590 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004591
4592 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004593
John McCalldadc5752010-08-24 06:29:42 +00004594 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004595 OpEqualRef.takeAs<Expr>(),
4596 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004597 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004598 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004599
4600 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004601 }
John McCallab8c2732010-03-16 06:11:48 +00004602
Douglas Gregorb139cd52010-05-01 20:49:11 +00004603 // - if the subobject is of scalar type, the built-in assignment
4604 // operator is used.
4605 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4606 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004607 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004608 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004609 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004610
4611 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004612 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004613
4614 // - if the subobject is an array, each element is assigned, in the
4615 // manner appropriate to the element type;
4616
4617 // Construct a loop over the array bounds, e.g.,
4618 //
4619 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4620 //
4621 // that will copy each of the array elements.
4622 QualType SizeType = S.Context.getSizeType();
4623
4624 // Create the iteration variable.
4625 IdentifierInfo *IterationVarName = 0;
4626 {
4627 llvm::SmallString<8> Str;
4628 llvm::raw_svector_ostream OS(Str);
4629 OS << "__i" << Depth;
4630 IterationVarName = &S.Context.Idents.get(OS.str());
4631 }
4632 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4633 IterationVarName, SizeType,
4634 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004635 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004636
4637 // Initialize the iteration variable to zero.
4638 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004639 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004640
4641 // Create a reference to the iteration variable; we'll use this several
4642 // times throughout.
4643 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004644 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004645 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4646
4647 // Create the DeclStmt that holds the iteration variable.
4648 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4649
4650 // Create the comparison against the array bound.
4651 llvm::APInt Upper = ArrayTy->getSize();
4652 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004653 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004654 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004655 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4656 BO_NE, S.Context.BoolTy,
4657 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004658
4659 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004660 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004661 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4662 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004663
4664 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004665 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4666 IterationVarRef, Loc));
4667 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4668 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004669
4670 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004671 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4672 To, From, CopyingBaseSubobject,
4673 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004674 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004675 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004676
4677 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004678 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004679 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004680 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004681 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004682}
4683
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004684/// \brief Determine whether the given class has a copy assignment operator
4685/// that accepts a const-qualified argument.
4686static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4687 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4688
4689 if (!Class->hasDeclaredCopyAssignment())
4690 S.DeclareImplicitCopyAssignment(Class);
4691
4692 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4693 DeclarationName OpName
4694 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4695
4696 DeclContext::lookup_const_iterator Op, OpEnd;
4697 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4698 // C++ [class.copy]p9:
4699 // A user-declared copy assignment operator is a non-static non-template
4700 // member function of class X with exactly one parameter of type X, X&,
4701 // const X&, volatile X& or const volatile X&.
4702 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4703 if (!Method)
4704 continue;
4705
4706 if (Method->isStatic())
4707 continue;
4708 if (Method->getPrimaryTemplate())
4709 continue;
4710 const FunctionProtoType *FnType =
4711 Method->getType()->getAs<FunctionProtoType>();
4712 assert(FnType && "Overloaded operator has no prototype.");
4713 // Don't assert on this; an invalid decl might have been left in the AST.
4714 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4715 continue;
4716 bool AcceptsConst = true;
4717 QualType ArgType = FnType->getArgType(0);
4718 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4719 ArgType = Ref->getPointeeType();
4720 // Is it a non-const lvalue reference?
4721 if (!ArgType.isConstQualified())
4722 AcceptsConst = false;
4723 }
4724 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4725 continue;
4726
4727 // We have a single argument of type cv X or cv X&, i.e. we've found the
4728 // copy assignment operator. Return whether it accepts const arguments.
4729 return AcceptsConst;
4730 }
4731 assert(Class->isInvalidDecl() &&
4732 "No copy assignment operator declared in valid code.");
4733 return false;
4734}
4735
Douglas Gregor0be31a22010-07-02 17:43:08 +00004736CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004737 // Note: The following rules are largely analoguous to the copy
4738 // constructor rules. Note that virtual bases are not taken into account
4739 // for determining the argument type of the operator. Note also that
4740 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004741
4742
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004743 // C++ [class.copy]p10:
4744 // If the class definition does not explicitly declare a copy
4745 // assignment operator, one is declared implicitly.
4746 // The implicitly-defined copy assignment operator for a class X
4747 // will have the form
4748 //
4749 // X& X::operator=(const X&)
4750 //
4751 // if
4752 bool HasConstCopyAssignment = true;
4753
4754 // -- each direct base class B of X has a copy assignment operator
4755 // whose parameter is of type const B&, const volatile B& or B,
4756 // and
4757 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4758 BaseEnd = ClassDecl->bases_end();
4759 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4760 assert(!Base->getType()->isDependentType() &&
4761 "Cannot generate implicit members for class with dependent bases.");
4762 const CXXRecordDecl *BaseClassDecl
4763 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004764 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004765 }
4766
4767 // -- for all the nonstatic data members of X that are of a class
4768 // type M (or array thereof), each such class type has a copy
4769 // assignment operator whose parameter is of type const M&,
4770 // const volatile M& or M.
4771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4772 FieldEnd = ClassDecl->field_end();
4773 HasConstCopyAssignment && Field != FieldEnd;
4774 ++Field) {
4775 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4776 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4777 const CXXRecordDecl *FieldClassDecl
4778 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004779 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004780 }
4781 }
4782
4783 // Otherwise, the implicitly declared copy assignment operator will
4784 // have the form
4785 //
4786 // X& X::operator=(X&)
4787 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4788 QualType RetType = Context.getLValueReferenceType(ArgType);
4789 if (HasConstCopyAssignment)
4790 ArgType = ArgType.withConst();
4791 ArgType = Context.getLValueReferenceType(ArgType);
4792
Douglas Gregor68e11362010-07-01 17:48:08 +00004793 // C++ [except.spec]p14:
4794 // An implicitly declared special member function (Clause 12) shall have an
4795 // exception-specification. [...]
4796 ImplicitExceptionSpecification ExceptSpec(Context);
4797 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4798 BaseEnd = ClassDecl->bases_end();
4799 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004800 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004801 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004802
4803 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4804 DeclareImplicitCopyAssignment(BaseClassDecl);
4805
Douglas Gregor68e11362010-07-01 17:48:08 +00004806 if (CXXMethodDecl *CopyAssign
4807 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4808 ExceptSpec.CalledDecl(CopyAssign);
4809 }
4810 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4811 FieldEnd = ClassDecl->field_end();
4812 Field != FieldEnd;
4813 ++Field) {
4814 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4815 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004816 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004817 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004818
4819 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4820 DeclareImplicitCopyAssignment(FieldClassDecl);
4821
Douglas Gregor68e11362010-07-01 17:48:08 +00004822 if (CXXMethodDecl *CopyAssign
4823 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4824 ExceptSpec.CalledDecl(CopyAssign);
4825 }
4826 }
4827
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004828 // An implicitly-declared copy assignment operator is an inline public
4829 // member of its class.
4830 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004831 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004832 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004833 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004834 Context.getFunctionType(RetType, &ArgType, 1,
4835 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004836 ExceptSpec.hasExceptionSpecification(),
4837 ExceptSpec.hasAnyExceptionSpecification(),
4838 ExceptSpec.size(),
4839 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004840 FunctionType::ExtInfo()),
4841 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004842 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004843 /*isInline=*/true);
4844 CopyAssignment->setAccess(AS_public);
4845 CopyAssignment->setImplicit();
4846 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004847
4848 // Add the parameter to the operator.
4849 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4850 ClassDecl->getLocation(),
4851 /*Id=*/0,
4852 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004853 SC_None,
4854 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004855 CopyAssignment->setParams(&FromParam, 1);
4856
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004857 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004858 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4859
Douglas Gregor0be31a22010-07-02 17:43:08 +00004860 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004861 PushOnScopeChains(CopyAssignment, S, false);
4862 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004863
4864 AddOverriddenMethods(ClassDecl, CopyAssignment);
4865 return CopyAssignment;
4866}
4867
Douglas Gregorb139cd52010-05-01 20:49:11 +00004868void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4869 CXXMethodDecl *CopyAssignOperator) {
4870 assert((CopyAssignOperator->isImplicit() &&
4871 CopyAssignOperator->isOverloadedOperator() &&
4872 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004873 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004874 "DefineImplicitCopyAssignment called for wrong function");
4875
4876 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4877
4878 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4879 CopyAssignOperator->setInvalidDecl();
4880 return;
4881 }
4882
4883 CopyAssignOperator->setUsed();
4884
4885 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004886 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004887
4888 // C++0x [class.copy]p30:
4889 // The implicitly-defined or explicitly-defaulted copy assignment operator
4890 // for a non-union class X performs memberwise copy assignment of its
4891 // subobjects. The direct base classes of X are assigned first, in the
4892 // order of their declaration in the base-specifier-list, and then the
4893 // immediate non-static data members of X are assigned, in the order in
4894 // which they were declared in the class definition.
4895
4896 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004897 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004898
4899 // The parameter for the "other" object, which we are copying from.
4900 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4901 Qualifiers OtherQuals = Other->getType().getQualifiers();
4902 QualType OtherRefType = Other->getType();
4903 if (const LValueReferenceType *OtherRef
4904 = OtherRefType->getAs<LValueReferenceType>()) {
4905 OtherRefType = OtherRef->getPointeeType();
4906 OtherQuals = OtherRefType.getQualifiers();
4907 }
4908
4909 // Our location for everything implicitly-generated.
4910 SourceLocation Loc = CopyAssignOperator->getLocation();
4911
4912 // Construct a reference to the "other" object. We'll be using this
4913 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00004914 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004915 assert(OtherRef && "Reference to parameter cannot fail!");
4916
4917 // Construct the "this" pointer. We'll be using this throughout the generated
4918 // ASTs.
4919 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4920 assert(This && "Reference to this cannot fail!");
4921
4922 // Assign base classes.
4923 bool Invalid = false;
4924 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4925 E = ClassDecl->bases_end(); Base != E; ++Base) {
4926 // Form the assignment:
4927 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4928 QualType BaseType = Base->getType().getUnqualifiedType();
4929 CXXRecordDecl *BaseClassDecl = 0;
4930 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4931 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4932 else {
4933 Invalid = true;
4934 continue;
4935 }
4936
John McCallcf142162010-08-07 06:22:56 +00004937 CXXCastPath BasePath;
4938 BasePath.push_back(Base);
4939
Douglas Gregorb139cd52010-05-01 20:49:11 +00004940 // Construct the "from" expression, which is an implicit cast to the
4941 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00004942 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004943 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004944 CK_UncheckedDerivedToBase,
4945 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004946
4947 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004948 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004949
4950 // Implicitly cast "this" to the appropriately-qualified base type.
4951 Expr *ToE = To.takeAs<Expr>();
4952 ImpCastExprToType(ToE,
4953 Context.getCVRQualifiedType(BaseType,
4954 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004955 CK_UncheckedDerivedToBase,
4956 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004957 To = Owned(ToE);
4958
4959 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004960 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004961 To.get(), From,
4962 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004963 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004964 Diag(CurrentLocation, diag::note_member_synthesized_at)
4965 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4966 CopyAssignOperator->setInvalidDecl();
4967 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004968 }
4969
4970 // Success! Record the copy.
4971 Statements.push_back(Copy.takeAs<Expr>());
4972 }
4973
4974 // \brief Reference to the __builtin_memcpy function.
4975 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004976 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004977 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004978
4979 // Assign non-static members.
4980 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4981 FieldEnd = ClassDecl->field_end();
4982 Field != FieldEnd; ++Field) {
4983 // Check for members of reference type; we can't copy those.
4984 if (Field->getType()->isReferenceType()) {
4985 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4986 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4987 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004988 Diag(CurrentLocation, diag::note_member_synthesized_at)
4989 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004990 Invalid = true;
4991 continue;
4992 }
4993
4994 // Check for members of const-qualified, non-class type.
4995 QualType BaseType = Context.getBaseElementType(Field->getType());
4996 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4997 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4998 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4999 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005000 Diag(CurrentLocation, diag::note_member_synthesized_at)
5001 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005002 Invalid = true;
5003 continue;
5004 }
5005
5006 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005007 if (FieldType->isIncompleteArrayType()) {
5008 assert(ClassDecl->hasFlexibleArrayMember() &&
5009 "Incomplete array type is not valid");
5010 continue;
5011 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005012
5013 // Build references to the field in the object we're copying from and to.
5014 CXXScopeSpec SS; // Intentionally empty
5015 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5016 LookupMemberName);
5017 MemberLookup.addDecl(*Field);
5018 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005019 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005020 Loc, /*IsArrow=*/false,
5021 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005022 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005023 Loc, /*IsArrow=*/true,
5024 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005025 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5026 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5027
5028 // If the field should be copied with __builtin_memcpy rather than via
5029 // explicit assignments, do so. This optimization only applies for arrays
5030 // of scalars and arrays of class type with trivial copy-assignment
5031 // operators.
5032 if (FieldType->isArrayType() &&
5033 (!BaseType->isRecordType() ||
5034 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5035 ->hasTrivialCopyAssignment())) {
5036 // Compute the size of the memory buffer to be copied.
5037 QualType SizeType = Context.getSizeType();
5038 llvm::APInt Size(Context.getTypeSize(SizeType),
5039 Context.getTypeSizeInChars(BaseType).getQuantity());
5040 for (const ConstantArrayType *Array
5041 = Context.getAsConstantArrayType(FieldType);
5042 Array;
5043 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5044 llvm::APInt ArraySize = Array->getSize();
5045 ArraySize.zextOrTrunc(Size.getBitWidth());
5046 Size *= ArraySize;
5047 }
5048
5049 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005050 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5051 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005052
5053 bool NeedsCollectableMemCpy =
5054 (BaseType->isRecordType() &&
5055 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5056
5057 if (NeedsCollectableMemCpy) {
5058 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005059 // Create a reference to the __builtin_objc_memmove_collectable function.
5060 LookupResult R(*this,
5061 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005062 Loc, LookupOrdinaryName);
5063 LookupName(R, TUScope, true);
5064
5065 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5066 if (!CollectableMemCpy) {
5067 // Something went horribly wrong earlier, and we will have
5068 // complained about it.
5069 Invalid = true;
5070 continue;
5071 }
5072
5073 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5074 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005075 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005076 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5077 }
5078 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005079 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005080 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005081 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5082 LookupOrdinaryName);
5083 LookupName(R, TUScope, true);
5084
5085 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5086 if (!BuiltinMemCpy) {
5087 // Something went horribly wrong earlier, and we will have complained
5088 // about it.
5089 Invalid = true;
5090 continue;
5091 }
5092
5093 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5094 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005095 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005096 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5097 }
5098
John McCall37ad5512010-08-23 06:44:23 +00005099 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005100 CallArgs.push_back(To.takeAs<Expr>());
5101 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005102 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005103 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005104 if (NeedsCollectableMemCpy)
5105 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005106 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005107 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005108 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005109 else
5110 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005111 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005112 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005113 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005114
Douglas Gregorb139cd52010-05-01 20:49:11 +00005115 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5116 Statements.push_back(Call.takeAs<Expr>());
5117 continue;
5118 }
5119
5120 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005121 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005122 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005123 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005124 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005125 Diag(CurrentLocation, diag::note_member_synthesized_at)
5126 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5127 CopyAssignOperator->setInvalidDecl();
5128 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005129 }
5130
5131 // Success! Record the copy.
5132 Statements.push_back(Copy.takeAs<Stmt>());
5133 }
5134
5135 if (!Invalid) {
5136 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005137 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005138
John McCalldadc5752010-08-24 06:29:42 +00005139 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005140 if (Return.isInvalid())
5141 Invalid = true;
5142 else {
5143 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005144
5145 if (Trap.hasErrorOccurred()) {
5146 Diag(CurrentLocation, diag::note_member_synthesized_at)
5147 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5148 Invalid = true;
5149 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005150 }
5151 }
5152
5153 if (Invalid) {
5154 CopyAssignOperator->setInvalidDecl();
5155 return;
5156 }
5157
John McCalldadc5752010-08-24 06:29:42 +00005158 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005159 /*isStmtExpr=*/false);
5160 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5161 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005162}
5163
Douglas Gregor0be31a22010-07-02 17:43:08 +00005164CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5165 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005166 // C++ [class.copy]p4:
5167 // If the class definition does not explicitly declare a copy
5168 // constructor, one is declared implicitly.
5169
Douglas Gregor54be3392010-07-01 17:57:27 +00005170 // C++ [class.copy]p5:
5171 // The implicitly-declared copy constructor for a class X will
5172 // have the form
5173 //
5174 // X::X(const X&)
5175 //
5176 // if
5177 bool HasConstCopyConstructor = true;
5178
5179 // -- each direct or virtual base class B of X has a copy
5180 // constructor whose first parameter is of type const B& or
5181 // const volatile B&, and
5182 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5183 BaseEnd = ClassDecl->bases_end();
5184 HasConstCopyConstructor && Base != BaseEnd;
5185 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005186 // Virtual bases are handled below.
5187 if (Base->isVirtual())
5188 continue;
5189
Douglas Gregora6d69502010-07-02 23:41:54 +00005190 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005191 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005192 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5193 DeclareImplicitCopyConstructor(BaseClassDecl);
5194
Douglas Gregorcfe68222010-07-01 18:27:03 +00005195 HasConstCopyConstructor
5196 = BaseClassDecl->hasConstCopyConstructor(Context);
5197 }
5198
5199 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5200 BaseEnd = ClassDecl->vbases_end();
5201 HasConstCopyConstructor && Base != BaseEnd;
5202 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005203 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005204 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005205 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5206 DeclareImplicitCopyConstructor(BaseClassDecl);
5207
Douglas Gregor54be3392010-07-01 17:57:27 +00005208 HasConstCopyConstructor
5209 = BaseClassDecl->hasConstCopyConstructor(Context);
5210 }
5211
5212 // -- for all the nonstatic data members of X that are of a
5213 // class type M (or array thereof), each such class type
5214 // has a copy constructor whose first parameter is of type
5215 // const M& or const volatile M&.
5216 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5217 FieldEnd = ClassDecl->field_end();
5218 HasConstCopyConstructor && Field != FieldEnd;
5219 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005220 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005221 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005222 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005223 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005224 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5225 DeclareImplicitCopyConstructor(FieldClassDecl);
5226
Douglas Gregor54be3392010-07-01 17:57:27 +00005227 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005228 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005229 }
5230 }
5231
5232 // Otherwise, the implicitly declared copy constructor will have
5233 // the form
5234 //
5235 // X::X(X&)
5236 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5237 QualType ArgType = ClassType;
5238 if (HasConstCopyConstructor)
5239 ArgType = ArgType.withConst();
5240 ArgType = Context.getLValueReferenceType(ArgType);
5241
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005242 // C++ [except.spec]p14:
5243 // An implicitly declared special member function (Clause 12) shall have an
5244 // exception-specification. [...]
5245 ImplicitExceptionSpecification ExceptSpec(Context);
5246 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5247 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5248 BaseEnd = ClassDecl->bases_end();
5249 Base != BaseEnd;
5250 ++Base) {
5251 // Virtual bases are handled below.
5252 if (Base->isVirtual())
5253 continue;
5254
Douglas Gregora6d69502010-07-02 23:41:54 +00005255 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005256 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005257 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5258 DeclareImplicitCopyConstructor(BaseClassDecl);
5259
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005260 if (CXXConstructorDecl *CopyConstructor
5261 = BaseClassDecl->getCopyConstructor(Context, Quals))
5262 ExceptSpec.CalledDecl(CopyConstructor);
5263 }
5264 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5265 BaseEnd = ClassDecl->vbases_end();
5266 Base != BaseEnd;
5267 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005268 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005269 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005270 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5271 DeclareImplicitCopyConstructor(BaseClassDecl);
5272
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005273 if (CXXConstructorDecl *CopyConstructor
5274 = BaseClassDecl->getCopyConstructor(Context, Quals))
5275 ExceptSpec.CalledDecl(CopyConstructor);
5276 }
5277 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5278 FieldEnd = ClassDecl->field_end();
5279 Field != FieldEnd;
5280 ++Field) {
5281 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5282 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005283 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005284 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005285 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5286 DeclareImplicitCopyConstructor(FieldClassDecl);
5287
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005288 if (CXXConstructorDecl *CopyConstructor
5289 = FieldClassDecl->getCopyConstructor(Context, Quals))
5290 ExceptSpec.CalledDecl(CopyConstructor);
5291 }
5292 }
5293
Douglas Gregor54be3392010-07-01 17:57:27 +00005294 // An implicitly-declared copy constructor is an inline public
5295 // member of its class.
5296 DeclarationName Name
5297 = Context.DeclarationNames.getCXXConstructorName(
5298 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005299 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005300 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005301 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005302 Context.getFunctionType(Context.VoidTy,
5303 &ArgType, 1,
5304 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005305 ExceptSpec.hasExceptionSpecification(),
5306 ExceptSpec.hasAnyExceptionSpecification(),
5307 ExceptSpec.size(),
5308 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005309 FunctionType::ExtInfo()),
5310 /*TInfo=*/0,
5311 /*isExplicit=*/false,
5312 /*isInline=*/true,
5313 /*isImplicitlyDeclared=*/true);
5314 CopyConstructor->setAccess(AS_public);
5315 CopyConstructor->setImplicit();
5316 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5317
Douglas Gregora6d69502010-07-02 23:41:54 +00005318 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005319 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5320
Douglas Gregor54be3392010-07-01 17:57:27 +00005321 // Add the parameter to the constructor.
5322 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5323 ClassDecl->getLocation(),
5324 /*IdentifierInfo=*/0,
5325 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005326 SC_None,
5327 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005328 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005329 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005330 PushOnScopeChains(CopyConstructor, S, false);
5331 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005332
5333 return CopyConstructor;
5334}
5335
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005336void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5337 CXXConstructorDecl *CopyConstructor,
5338 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005339 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005340 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005341 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005342 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005343
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005344 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005345 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005346
Douglas Gregora57478e2010-05-01 15:04:51 +00005347 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005348 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005349
Douglas Gregor54818f02010-05-12 16:39:35 +00005350 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5351 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005352 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005353 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005354 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005355 } else {
5356 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5357 CopyConstructor->getLocation(),
5358 MultiStmtArg(*this, 0, 0),
5359 /*isStmtExpr=*/false)
5360 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005361 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005362
5363 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005364}
5365
John McCalldadc5752010-08-24 06:29:42 +00005366ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005367Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005368 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005369 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005370 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005371 unsigned ConstructKind,
5372 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005373 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005374
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005375 // C++0x [class.copy]p34:
5376 // When certain criteria are met, an implementation is allowed to
5377 // omit the copy/move construction of a class object, even if the
5378 // copy/move constructor and/or destructor for the object have
5379 // side effects. [...]
5380 // - when a temporary class object that has not been bound to a
5381 // reference (12.2) would be copied/moved to a class object
5382 // with the same cv-unqualified type, the copy/move operation
5383 // can be omitted by constructing the temporary object
5384 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005385 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5386 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005387 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005388 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005389 }
Mike Stump11289f42009-09-09 15:08:12 +00005390
5391 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005392 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005393 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005394}
5395
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005396/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5397/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005398ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005399Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5400 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005401 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005402 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005403 unsigned ConstructKind,
5404 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005405 unsigned NumExprs = ExprArgs.size();
5406 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005407
Douglas Gregor27381f32009-11-23 12:27:39 +00005408 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005409 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005410 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005411 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005412 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5413 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005414}
5415
Mike Stump11289f42009-09-09 15:08:12 +00005416bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005417 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005418 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005419 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005420 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005421 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005422 move(Exprs), false, CXXConstructExpr::CK_Complete,
5423 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005424 if (TempResult.isInvalid())
5425 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005426
Anders Carlsson6eb55572009-08-25 05:12:04 +00005427 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005428 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005429 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005430 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005431 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005432
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005433 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005434}
5435
John McCall03c48482010-02-02 09:10:11 +00005436void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005438 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005439 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005440 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005441 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005442 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005443 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005444 << VD->getDeclName()
5445 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005446
John McCall386dfc72010-09-18 05:25:11 +00005447 // TODO: this should be re-enabled for static locals by !CXAAtExit
5448 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005449 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005450 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005451}
5452
Mike Stump11289f42009-09-09 15:08:12 +00005453/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005454/// ActOnDeclarator, when a C++ direct initializer is present.
5455/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005456void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005457 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005458 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005459 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005460 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005461
5462 // If there is no declaration, there was an error parsing it. Just ignore
5463 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005464 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005465 return;
Mike Stump11289f42009-09-09 15:08:12 +00005466
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005467 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5468 if (!VDecl) {
5469 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5470 RealDecl->setInvalidDecl();
5471 return;
5472 }
5473
Douglas Gregor402250f2009-08-26 21:14:46 +00005474 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005475 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005476 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5477 //
5478 // Clients that want to distinguish between the two forms, can check for
5479 // direct initializer using VarDecl::hasCXXDirectInitializer().
5480 // A major benefit is that clients that don't particularly care about which
5481 // exactly form was it (like the CodeGen) can handle both cases without
5482 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005483
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005484 // C++ 8.5p11:
5485 // The form of initialization (using parentheses or '=') is generally
5486 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005487 // class type.
5488
Douglas Gregor50dc2192010-02-11 22:55:30 +00005489 if (!VDecl->getType()->isDependentType() &&
5490 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005491 diag::err_typecheck_decl_incomplete_type)) {
5492 VDecl->setInvalidDecl();
5493 return;
5494 }
5495
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005496 // The variable can not have an abstract class type.
5497 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5498 diag::err_abstract_type_in_decl,
5499 AbstractVariableType))
5500 VDecl->setInvalidDecl();
5501
Sebastian Redl5ca79842010-02-01 20:16:42 +00005502 const VarDecl *Def;
5503 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005504 Diag(VDecl->getLocation(), diag::err_redefinition)
5505 << VDecl->getDeclName();
5506 Diag(Def->getLocation(), diag::note_previous_definition);
5507 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005508 return;
5509 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005510
Douglas Gregorf0f83692010-08-24 05:27:49 +00005511 // C++ [class.static.data]p4
5512 // If a static data member is of const integral or const
5513 // enumeration type, its declaration in the class definition can
5514 // specify a constant-initializer which shall be an integral
5515 // constant expression (5.19). In that case, the member can appear
5516 // in integral constant expressions. The member shall still be
5517 // defined in a namespace scope if it is used in the program and the
5518 // namespace scope definition shall not contain an initializer.
5519 //
5520 // We already performed a redefinition check above, but for static
5521 // data members we also need to check whether there was an in-class
5522 // declaration with an initializer.
5523 const VarDecl* PrevInit = 0;
5524 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5525 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5526 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5527 return;
5528 }
5529
Douglas Gregor50dc2192010-02-11 22:55:30 +00005530 // If either the declaration has a dependent type or if any of the
5531 // expressions is type-dependent, we represent the initialization
5532 // via a ParenListExpr for later use during template instantiation.
5533 if (VDecl->getType()->isDependentType() ||
5534 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5535 // Let clients know that initialization was done with a direct initializer.
5536 VDecl->setCXXDirectInitializer(true);
5537
5538 // Store the initialization expressions as a ParenListExpr.
5539 unsigned NumExprs = Exprs.size();
5540 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5541 (Expr **)Exprs.release(),
5542 NumExprs, RParenLoc));
5543 return;
5544 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005545
5546 // Capture the variable that is being initialized and the style of
5547 // initialization.
5548 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5549
5550 // FIXME: Poor source location information.
5551 InitializationKind Kind
5552 = InitializationKind::CreateDirect(VDecl->getLocation(),
5553 LParenLoc, RParenLoc);
5554
5555 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005556 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005557 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005558 if (Result.isInvalid()) {
5559 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005560 return;
5561 }
John McCallacf0ee52010-10-08 02:01:28 +00005562
5563 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005564
John McCallb268a282010-08-23 23:25:46 +00005565 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregord5058122010-02-11 01:19:42 +00005566 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005567 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005568
John McCall8b0f4ff2010-08-02 21:13:48 +00005569 if (!VDecl->isInvalidDecl() &&
5570 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005571 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005572 !VDecl->getInit()->isConstantInitializer(Context,
5573 VDecl->getType()->isReferenceType()))
5574 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5575 << VDecl->getInit()->getSourceRange();
5576
John McCall03c48482010-02-02 09:10:11 +00005577 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5578 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005579}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005580
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005581/// \brief Given a constructor and the set of arguments provided for the
5582/// constructor, convert the arguments and add any required default arguments
5583/// to form a proper call to this constructor.
5584///
5585/// \returns true if an error occurred, false otherwise.
5586bool
5587Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5588 MultiExprArg ArgsPtr,
5589 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005590 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005591 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5592 unsigned NumArgs = ArgsPtr.size();
5593 Expr **Args = (Expr **)ArgsPtr.get();
5594
5595 const FunctionProtoType *Proto
5596 = Constructor->getType()->getAs<FunctionProtoType>();
5597 assert(Proto && "Constructor without a prototype?");
5598 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005599
5600 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005601 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005602 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005603 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005604 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005605
5606 VariadicCallType CallType =
5607 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5608 llvm::SmallVector<Expr *, 8> AllArgs;
5609 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5610 Proto, 0, Args, NumArgs, AllArgs,
5611 CallType);
5612 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5613 ConvertedArgs.push_back(AllArgs[i]);
5614 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005615}
5616
Anders Carlssone363c8e2009-12-12 00:32:00 +00005617static inline bool
5618CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5619 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005620 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005621 if (isa<NamespaceDecl>(DC)) {
5622 return SemaRef.Diag(FnDecl->getLocation(),
5623 diag::err_operator_new_delete_declared_in_namespace)
5624 << FnDecl->getDeclName();
5625 }
5626
5627 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005628 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005629 return SemaRef.Diag(FnDecl->getLocation(),
5630 diag::err_operator_new_delete_declared_static)
5631 << FnDecl->getDeclName();
5632 }
5633
Anders Carlsson60659a82009-12-12 02:43:16 +00005634 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005635}
5636
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005637static inline bool
5638CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5639 CanQualType ExpectedResultType,
5640 CanQualType ExpectedFirstParamType,
5641 unsigned DependentParamTypeDiag,
5642 unsigned InvalidParamTypeDiag) {
5643 QualType ResultType =
5644 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5645
5646 // Check that the result type is not dependent.
5647 if (ResultType->isDependentType())
5648 return SemaRef.Diag(FnDecl->getLocation(),
5649 diag::err_operator_new_delete_dependent_result_type)
5650 << FnDecl->getDeclName() << ExpectedResultType;
5651
5652 // Check that the result type is what we expect.
5653 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5654 return SemaRef.Diag(FnDecl->getLocation(),
5655 diag::err_operator_new_delete_invalid_result_type)
5656 << FnDecl->getDeclName() << ExpectedResultType;
5657
5658 // A function template must have at least 2 parameters.
5659 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5660 return SemaRef.Diag(FnDecl->getLocation(),
5661 diag::err_operator_new_delete_template_too_few_parameters)
5662 << FnDecl->getDeclName();
5663
5664 // The function decl must have at least 1 parameter.
5665 if (FnDecl->getNumParams() == 0)
5666 return SemaRef.Diag(FnDecl->getLocation(),
5667 diag::err_operator_new_delete_too_few_parameters)
5668 << FnDecl->getDeclName();
5669
5670 // Check the the first parameter type is not dependent.
5671 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5672 if (FirstParamType->isDependentType())
5673 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5674 << FnDecl->getDeclName() << ExpectedFirstParamType;
5675
5676 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005677 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005678 ExpectedFirstParamType)
5679 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5680 << FnDecl->getDeclName() << ExpectedFirstParamType;
5681
5682 return false;
5683}
5684
Anders Carlsson12308f42009-12-11 23:23:22 +00005685static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005686CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005687 // C++ [basic.stc.dynamic.allocation]p1:
5688 // A program is ill-formed if an allocation function is declared in a
5689 // namespace scope other than global scope or declared static in global
5690 // scope.
5691 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5692 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005693
5694 CanQualType SizeTy =
5695 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5696
5697 // C++ [basic.stc.dynamic.allocation]p1:
5698 // The return type shall be void*. The first parameter shall have type
5699 // std::size_t.
5700 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5701 SizeTy,
5702 diag::err_operator_new_dependent_param_type,
5703 diag::err_operator_new_param_type))
5704 return true;
5705
5706 // C++ [basic.stc.dynamic.allocation]p1:
5707 // The first parameter shall not have an associated default argument.
5708 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005709 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005710 diag::err_operator_new_default_arg)
5711 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5712
5713 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005714}
5715
5716static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005717CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5718 // C++ [basic.stc.dynamic.deallocation]p1:
5719 // A program is ill-formed if deallocation functions are declared in a
5720 // namespace scope other than global scope or declared static in global
5721 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005722 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5723 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005724
5725 // C++ [basic.stc.dynamic.deallocation]p2:
5726 // Each deallocation function shall return void and its first parameter
5727 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005728 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5729 SemaRef.Context.VoidPtrTy,
5730 diag::err_operator_delete_dependent_param_type,
5731 diag::err_operator_delete_param_type))
5732 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005733
Anders Carlsson12308f42009-12-11 23:23:22 +00005734 return false;
5735}
5736
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005737/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5738/// of this overloaded operator is well-formed. If so, returns false;
5739/// otherwise, emits appropriate diagnostics and returns true.
5740bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005741 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005742 "Expected an overloaded operator declaration");
5743
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005744 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5745
Mike Stump11289f42009-09-09 15:08:12 +00005746 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005747 // The allocation and deallocation functions, operator new,
5748 // operator new[], operator delete and operator delete[], are
5749 // described completely in 3.7.3. The attributes and restrictions
5750 // found in the rest of this subclause do not apply to them unless
5751 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005752 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005753 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005754
Anders Carlsson22f443f2009-12-12 00:26:23 +00005755 if (Op == OO_New || Op == OO_Array_New)
5756 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005757
5758 // C++ [over.oper]p6:
5759 // An operator function shall either be a non-static member
5760 // function or be a non-member function and have at least one
5761 // parameter whose type is a class, a reference to a class, an
5762 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005763 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5764 if (MethodDecl->isStatic())
5765 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005766 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005767 } else {
5768 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005769 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5770 ParamEnd = FnDecl->param_end();
5771 Param != ParamEnd; ++Param) {
5772 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005773 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5774 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005775 ClassOrEnumParam = true;
5776 break;
5777 }
5778 }
5779
Douglas Gregord69246b2008-11-17 16:14:12 +00005780 if (!ClassOrEnumParam)
5781 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005782 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005783 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005784 }
5785
5786 // C++ [over.oper]p8:
5787 // An operator function cannot have default arguments (8.3.6),
5788 // except where explicitly stated below.
5789 //
Mike Stump11289f42009-09-09 15:08:12 +00005790 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005791 // (C++ [over.call]p1).
5792 if (Op != OO_Call) {
5793 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5794 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005795 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005796 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005797 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005798 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005799 }
5800 }
5801
Douglas Gregor6cf08062008-11-10 13:38:07 +00005802 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5803 { false, false, false }
5804#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5805 , { Unary, Binary, MemberOnly }
5806#include "clang/Basic/OperatorKinds.def"
5807 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005808
Douglas Gregor6cf08062008-11-10 13:38:07 +00005809 bool CanBeUnaryOperator = OperatorUses[Op][0];
5810 bool CanBeBinaryOperator = OperatorUses[Op][1];
5811 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005812
5813 // C++ [over.oper]p8:
5814 // [...] Operator functions cannot have more or fewer parameters
5815 // than the number required for the corresponding operator, as
5816 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005817 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005818 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005819 if (Op != OO_Call &&
5820 ((NumParams == 1 && !CanBeUnaryOperator) ||
5821 (NumParams == 2 && !CanBeBinaryOperator) ||
5822 (NumParams < 1) || (NumParams > 2))) {
5823 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005824 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005825 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005826 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005827 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005828 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005829 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005830 assert(CanBeBinaryOperator &&
5831 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005832 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005833 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005834
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005835 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005836 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005837 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005838
Douglas Gregord69246b2008-11-17 16:14:12 +00005839 // Overloaded operators other than operator() cannot be variadic.
5840 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005841 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005842 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005843 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005844 }
5845
5846 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005847 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5848 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005849 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005850 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005851 }
5852
5853 // C++ [over.inc]p1:
5854 // The user-defined function called operator++ implements the
5855 // prefix and postfix ++ operator. If this function is a member
5856 // function with no parameters, or a non-member function with one
5857 // parameter of class or enumeration type, it defines the prefix
5858 // increment operator ++ for objects of that type. If the function
5859 // is a member function with one parameter (which shall be of type
5860 // int) or a non-member function with two parameters (the second
5861 // of which shall be of type int), it defines the postfix
5862 // increment operator ++ for objects of that type.
5863 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5864 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5865 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005866 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005867 ParamIsInt = BT->getKind() == BuiltinType::Int;
5868
Chris Lattner2b786902008-11-21 07:50:02 +00005869 if (!ParamIsInt)
5870 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005871 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005872 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005873 }
5874
Douglas Gregord69246b2008-11-17 16:14:12 +00005875 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005876}
Chris Lattner3b024a32008-12-17 07:09:26 +00005877
Alexis Huntc88db062010-01-13 09:01:02 +00005878/// CheckLiteralOperatorDeclaration - Check whether the declaration
5879/// of this literal operator function is well-formed. If so, returns
5880/// false; otherwise, emits appropriate diagnostics and returns true.
5881bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5882 DeclContext *DC = FnDecl->getDeclContext();
5883 Decl::Kind Kind = DC->getDeclKind();
5884 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5885 Kind != Decl::LinkageSpec) {
5886 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5887 << FnDecl->getDeclName();
5888 return true;
5889 }
5890
5891 bool Valid = false;
5892
Alexis Hunt7dd26172010-04-07 23:11:06 +00005893 // template <char...> type operator "" name() is the only valid template
5894 // signature, and the only valid signature with no parameters.
5895 if (FnDecl->param_size() == 0) {
5896 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5897 // Must have only one template parameter
5898 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5899 if (Params->size() == 1) {
5900 NonTypeTemplateParmDecl *PmDecl =
5901 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005902
Alexis Hunt7dd26172010-04-07 23:11:06 +00005903 // The template parameter must be a char parameter pack.
5904 // FIXME: This test will always fail because non-type parameter packs
5905 // have not been implemented.
5906 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5907 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5908 Valid = true;
5909 }
5910 }
5911 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005912 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005913 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5914
Alexis Huntc88db062010-01-13 09:01:02 +00005915 QualType T = (*Param)->getType();
5916
Alexis Hunt079a6f72010-04-07 22:57:35 +00005917 // unsigned long long int, long double, and any character type are allowed
5918 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005919 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5920 Context.hasSameType(T, Context.LongDoubleTy) ||
5921 Context.hasSameType(T, Context.CharTy) ||
5922 Context.hasSameType(T, Context.WCharTy) ||
5923 Context.hasSameType(T, Context.Char16Ty) ||
5924 Context.hasSameType(T, Context.Char32Ty)) {
5925 if (++Param == FnDecl->param_end())
5926 Valid = true;
5927 goto FinishedParams;
5928 }
5929
Alexis Hunt079a6f72010-04-07 22:57:35 +00005930 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005931 const PointerType *PT = T->getAs<PointerType>();
5932 if (!PT)
5933 goto FinishedParams;
5934 T = PT->getPointeeType();
5935 if (!T.isConstQualified())
5936 goto FinishedParams;
5937 T = T.getUnqualifiedType();
5938
5939 // Move on to the second parameter;
5940 ++Param;
5941
5942 // If there is no second parameter, the first must be a const char *
5943 if (Param == FnDecl->param_end()) {
5944 if (Context.hasSameType(T, Context.CharTy))
5945 Valid = true;
5946 goto FinishedParams;
5947 }
5948
5949 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5950 // are allowed as the first parameter to a two-parameter function
5951 if (!(Context.hasSameType(T, Context.CharTy) ||
5952 Context.hasSameType(T, Context.WCharTy) ||
5953 Context.hasSameType(T, Context.Char16Ty) ||
5954 Context.hasSameType(T, Context.Char32Ty)))
5955 goto FinishedParams;
5956
5957 // The second and final parameter must be an std::size_t
5958 T = (*Param)->getType().getUnqualifiedType();
5959 if (Context.hasSameType(T, Context.getSizeType()) &&
5960 ++Param == FnDecl->param_end())
5961 Valid = true;
5962 }
5963
5964 // FIXME: This diagnostic is absolutely terrible.
5965FinishedParams:
5966 if (!Valid) {
5967 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5968 << FnDecl->getDeclName();
5969 return true;
5970 }
5971
5972 return false;
5973}
5974
Douglas Gregor07665a62009-01-05 19:45:36 +00005975/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5976/// linkage specification, including the language and (if present)
5977/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5978/// the location of the language string literal, which is provided
5979/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5980/// the '{' brace. Otherwise, this linkage specification does not
5981/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00005982Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5983 SourceLocation LangLoc,
5984 llvm::StringRef Lang,
5985 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005986 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005987 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005988 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005989 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005990 Language = LinkageSpecDecl::lang_cxx;
5991 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005992 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00005993 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00005994 }
Mike Stump11289f42009-09-09 15:08:12 +00005995
Chris Lattner438e5012008-12-17 07:13:27 +00005996 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005997
Douglas Gregor07665a62009-01-05 19:45:36 +00005998 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005999 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006000 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006001 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006002 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006003 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006004}
6005
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006006/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006007/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6008/// valid, it's the position of the closing '}' brace in a linkage
6009/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006010Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6011 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006012 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006013 if (LinkageSpec)
6014 PopDeclContext();
6015 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006016}
6017
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006018/// \brief Perform semantic analysis for the variable declaration that
6019/// occurs within a C++ catch clause, returning the newly-created
6020/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006021VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006022 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006023 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006024 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006025 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006026 QualType ExDeclType = TInfo->getType();
6027
Sebastian Redl54c04d42008-12-22 19:15:10 +00006028 // Arrays and functions decay.
6029 if (ExDeclType->isArrayType())
6030 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6031 else if (ExDeclType->isFunctionType())
6032 ExDeclType = Context.getPointerType(ExDeclType);
6033
6034 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6035 // The exception-declaration shall not denote a pointer or reference to an
6036 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006037 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006038 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006039 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006040 Invalid = true;
6041 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006042
Douglas Gregor104ee002010-03-08 01:47:36 +00006043 // GCC allows catching pointers and references to incomplete types
6044 // as an extension; so do we, but we warn by default.
6045
Sebastian Redl54c04d42008-12-22 19:15:10 +00006046 QualType BaseType = ExDeclType;
6047 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006048 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006049 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006050 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006051 BaseType = Ptr->getPointeeType();
6052 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006053 DK = diag::ext_catch_incomplete_ptr;
6054 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006055 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006056 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006057 BaseType = Ref->getPointeeType();
6058 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006059 DK = diag::ext_catch_incomplete_ref;
6060 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006061 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006062 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006063 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6064 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006065 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006066
Mike Stump11289f42009-09-09 15:08:12 +00006067 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006068 RequireNonAbstractType(Loc, ExDeclType,
6069 diag::err_abstract_type_in_decl,
6070 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006071 Invalid = true;
6072
John McCall2ca705e2010-07-24 00:37:23 +00006073 // Only the non-fragile NeXT runtime currently supports C++ catches
6074 // of ObjC types, and no runtime supports catching ObjC types by value.
6075 if (!Invalid && getLangOptions().ObjC1) {
6076 QualType T = ExDeclType;
6077 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6078 T = RT->getPointeeType();
6079
6080 if (T->isObjCObjectType()) {
6081 Diag(Loc, diag::err_objc_object_catch);
6082 Invalid = true;
6083 } else if (T->isObjCObjectPointerType()) {
6084 if (!getLangOptions().NeXTRuntime) {
6085 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6086 Invalid = true;
6087 } else if (!getLangOptions().ObjCNonFragileABI) {
6088 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6089 Invalid = true;
6090 }
6091 }
6092 }
6093
Mike Stump11289f42009-09-09 15:08:12 +00006094 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006095 Name, ExDeclType, TInfo, SC_None,
6096 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006097 ExDecl->setExceptionVariable(true);
6098
Douglas Gregor6de584c2010-03-05 23:38:39 +00006099 if (!Invalid) {
6100 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6101 // C++ [except.handle]p16:
6102 // The object declared in an exception-declaration or, if the
6103 // exception-declaration does not specify a name, a temporary (12.2) is
6104 // copy-initialized (8.5) from the exception object. [...]
6105 // The object is destroyed when the handler exits, after the destruction
6106 // of any automatic objects initialized within the handler.
6107 //
6108 // We just pretend to initialize the object with itself, then make sure
6109 // it can be destroyed later.
6110 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6111 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006112 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006113 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6114 SourceLocation());
6115 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006116 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006117 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006118 if (Result.isInvalid())
6119 Invalid = true;
6120 else
6121 FinalizeVarWithDestructor(ExDecl, RecordTy);
6122 }
6123 }
6124
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006125 if (Invalid)
6126 ExDecl->setInvalidDecl();
6127
6128 return ExDecl;
6129}
6130
6131/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6132/// handler.
John McCall48871652010-08-21 09:40:31 +00006133Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006134 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6135 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006136
6137 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006138 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006139 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006140 LookupOrdinaryName,
6141 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006142 // The scope should be freshly made just for us. There is just no way
6143 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006144 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006145 if (PrevDecl->isTemplateParameter()) {
6146 // Maybe we will complain about the shadowed template parameter.
6147 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006148 }
6149 }
6150
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006151 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006152 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6153 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006154 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006155 }
6156
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006157 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006158 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006159 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006160
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006161 if (Invalid)
6162 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006163
Sebastian Redl54c04d42008-12-22 19:15:10 +00006164 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006165 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006166 PushOnScopeChains(ExDecl, S);
6167 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006168 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006169
Douglas Gregor758a8692009-06-17 21:51:59 +00006170 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006171 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006172}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006173
John McCall48871652010-08-21 09:40:31 +00006174Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006175 Expr *AssertExpr,
6176 Expr *AssertMessageExpr_) {
6177 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006178
Anders Carlsson54b26982009-03-14 00:33:21 +00006179 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6180 llvm::APSInt Value(32);
6181 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6182 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6183 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006184 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006185 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006186
Anders Carlsson54b26982009-03-14 00:33:21 +00006187 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006188 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006189 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006190 }
6191 }
Mike Stump11289f42009-09-09 15:08:12 +00006192
Mike Stump11289f42009-09-09 15:08:12 +00006193 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006194 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006195
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006196 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006197 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006198}
Sebastian Redlf769df52009-03-24 22:27:57 +00006199
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006200/// \brief Perform semantic analysis of the given friend type declaration.
6201///
6202/// \returns A friend declaration that.
6203FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6204 TypeSourceInfo *TSInfo) {
6205 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6206
6207 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006208 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006209
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006210 if (!getLangOptions().CPlusPlus0x) {
6211 // C++03 [class.friend]p2:
6212 // An elaborated-type-specifier shall be used in a friend declaration
6213 // for a class.*
6214 //
6215 // * The class-key of the elaborated-type-specifier is required.
6216 if (!ActiveTemplateInstantiations.empty()) {
6217 // Do not complain about the form of friend template types during
6218 // template instantiation; we will already have complained when the
6219 // template was declared.
6220 } else if (!T->isElaboratedTypeSpecifier()) {
6221 // If we evaluated the type to a record type, suggest putting
6222 // a tag in front.
6223 if (const RecordType *RT = T->getAs<RecordType>()) {
6224 RecordDecl *RD = RT->getDecl();
6225
6226 std::string InsertionText = std::string(" ") + RD->getKindName();
6227
6228 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6229 << (unsigned) RD->getTagKind()
6230 << T
6231 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6232 InsertionText);
6233 } else {
6234 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6235 << T
6236 << SourceRange(FriendLoc, TypeRange.getEnd());
6237 }
6238 } else if (T->getAs<EnumType>()) {
6239 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006240 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006241 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006242 }
6243 }
6244
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006245 // C++0x [class.friend]p3:
6246 // If the type specifier in a friend declaration designates a (possibly
6247 // cv-qualified) class type, that class is declared as a friend; otherwise,
6248 // the friend declaration is ignored.
6249
6250 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6251 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006252
6253 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6254}
6255
John McCallace48cd2010-10-19 01:40:49 +00006256/// Handle a friend tag declaration where the scope specifier was
6257/// templated.
6258Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6259 unsigned TagSpec, SourceLocation TagLoc,
6260 CXXScopeSpec &SS,
6261 IdentifierInfo *Name, SourceLocation NameLoc,
6262 AttributeList *Attr,
6263 MultiTemplateParamsArg TempParamLists) {
6264 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6265
6266 bool isExplicitSpecialization = false;
6267 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6268 bool Invalid = false;
6269
6270 if (TemplateParameterList *TemplateParams
6271 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6272 TempParamLists.get(),
6273 TempParamLists.size(),
6274 /*friend*/ true,
6275 isExplicitSpecialization,
6276 Invalid)) {
6277 --NumMatchedTemplateParamLists;
6278
6279 if (TemplateParams->size() > 0) {
6280 // This is a declaration of a class template.
6281 if (Invalid)
6282 return 0;
6283
6284 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6285 SS, Name, NameLoc, Attr,
6286 TemplateParams, AS_public).take();
6287 } else {
6288 // The "template<>" header is extraneous.
6289 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6290 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6291 isExplicitSpecialization = true;
6292 }
6293 }
6294
6295 if (Invalid) return 0;
6296
6297 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6298
6299 bool isAllExplicitSpecializations = true;
6300 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6301 if (TempParamLists.get()[I]->size()) {
6302 isAllExplicitSpecializations = false;
6303 break;
6304 }
6305 }
6306
6307 // FIXME: don't ignore attributes.
6308
6309 // If it's explicit specializations all the way down, just forget
6310 // about the template header and build an appropriate non-templated
6311 // friend. TODO: for source fidelity, remember the headers.
6312 if (isAllExplicitSpecializations) {
6313 ElaboratedTypeKeyword Keyword
6314 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6315 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6316 TagLoc, SS.getRange(), NameLoc);
6317 if (T.isNull())
6318 return 0;
6319
6320 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6321 if (isa<DependentNameType>(T)) {
6322 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6323 TL.setKeywordLoc(TagLoc);
6324 TL.setQualifierRange(SS.getRange());
6325 TL.setNameLoc(NameLoc);
6326 } else {
6327 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6328 TL.setKeywordLoc(TagLoc);
6329 TL.setQualifierRange(SS.getRange());
6330 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6331 }
6332
6333 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6334 TSI, FriendLoc);
6335 Friend->setAccess(AS_public);
6336 CurContext->addDecl(Friend);
6337 return Friend;
6338 }
6339
6340 // Handle the case of a templated-scope friend class. e.g.
6341 // template <class T> class A<T>::B;
6342 // FIXME: we don't support these right now.
6343 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6344 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6345 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6346 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6347 TL.setKeywordLoc(TagLoc);
6348 TL.setQualifierRange(SS.getRange());
6349 TL.setNameLoc(NameLoc);
6350
6351 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6352 TSI, FriendLoc);
6353 Friend->setAccess(AS_public);
6354 Friend->setUnsupportedFriend(true);
6355 CurContext->addDecl(Friend);
6356 return Friend;
6357}
6358
6359
John McCall11083da2009-09-16 22:47:08 +00006360/// Handle a friend type declaration. This works in tandem with
6361/// ActOnTag.
6362///
6363/// Notes on friend class templates:
6364///
6365/// We generally treat friend class declarations as if they were
6366/// declaring a class. So, for example, the elaborated type specifier
6367/// in a friend declaration is required to obey the restrictions of a
6368/// class-head (i.e. no typedefs in the scope chain), template
6369/// parameters are required to match up with simple template-ids, &c.
6370/// However, unlike when declaring a template specialization, it's
6371/// okay to refer to a template specialization without an empty
6372/// template parameter declaration, e.g.
6373/// friend class A<T>::B<unsigned>;
6374/// We permit this as a special case; if there are any template
6375/// parameters present at all, require proper matching, i.e.
6376/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006377Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006378 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006379 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006380
6381 assert(DS.isFriendSpecified());
6382 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6383
John McCall11083da2009-09-16 22:47:08 +00006384 // Try to convert the decl specifier to a type. This works for
6385 // friend templates because ActOnTag never produces a ClassTemplateDecl
6386 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006387 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006388 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6389 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006390 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006391 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006392
John McCall11083da2009-09-16 22:47:08 +00006393 // This is definitely an error in C++98. It's probably meant to
6394 // be forbidden in C++0x, too, but the specification is just
6395 // poorly written.
6396 //
6397 // The problem is with declarations like the following:
6398 // template <T> friend A<T>::foo;
6399 // where deciding whether a class C is a friend or not now hinges
6400 // on whether there exists an instantiation of A that causes
6401 // 'foo' to equal C. There are restrictions on class-heads
6402 // (which we declare (by fiat) elaborated friend declarations to
6403 // be) that makes this tractable.
6404 //
6405 // FIXME: handle "template <> friend class A<T>;", which
6406 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006407 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006408 Diag(Loc, diag::err_tagless_friend_type_template)
6409 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006410 return 0;
John McCall11083da2009-09-16 22:47:08 +00006411 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006412
John McCallaa74a0c2009-08-28 07:59:38 +00006413 // C++98 [class.friend]p1: A friend of a class is a function
6414 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006415 // This is fixed in DR77, which just barely didn't make the C++03
6416 // deadline. It's also a very silly restriction that seriously
6417 // affects inner classes and which nobody else seems to implement;
6418 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006419 //
6420 // But note that we could warn about it: it's always useless to
6421 // friend one of your own members (it's not, however, worthless to
6422 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006423
John McCall11083da2009-09-16 22:47:08 +00006424 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006425 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006426 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006427 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006428 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006429 TSI,
John McCall11083da2009-09-16 22:47:08 +00006430 DS.getFriendSpecLoc());
6431 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006432 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6433
6434 if (!D)
John McCall48871652010-08-21 09:40:31 +00006435 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006436
John McCall11083da2009-09-16 22:47:08 +00006437 D->setAccess(AS_public);
6438 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006439
John McCall48871652010-08-21 09:40:31 +00006440 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006441}
6442
John McCallde3fd222010-10-12 23:13:28 +00006443Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6444 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006445 const DeclSpec &DS = D.getDeclSpec();
6446
6447 assert(DS.isFriendSpecified());
6448 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6449
6450 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006451 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6452 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006453
6454 // C++ [class.friend]p1
6455 // A friend of a class is a function or class....
6456 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006457 // It *doesn't* see through dependent types, which is correct
6458 // according to [temp.arg.type]p3:
6459 // If a declaration acquires a function type through a
6460 // type dependent on a template-parameter and this causes
6461 // a declaration that does not use the syntactic form of a
6462 // function declarator to have a function type, the program
6463 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006464 if (!T->isFunctionType()) {
6465 Diag(Loc, diag::err_unexpected_friend);
6466
6467 // It might be worthwhile to try to recover by creating an
6468 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006469 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006470 }
6471
6472 // C++ [namespace.memdef]p3
6473 // - If a friend declaration in a non-local class first declares a
6474 // class or function, the friend class or function is a member
6475 // of the innermost enclosing namespace.
6476 // - The name of the friend is not found by simple name lookup
6477 // until a matching declaration is provided in that namespace
6478 // scope (either before or after the class declaration granting
6479 // friendship).
6480 // - If a friend function is called, its name may be found by the
6481 // name lookup that considers functions from namespaces and
6482 // classes associated with the types of the function arguments.
6483 // - When looking for a prior declaration of a class or a function
6484 // declared as a friend, scopes outside the innermost enclosing
6485 // namespace scope are not considered.
6486
John McCallde3fd222010-10-12 23:13:28 +00006487 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006488 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6489 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006490 assert(Name);
6491
John McCall07e91c02009-08-06 02:15:43 +00006492 // The context we found the declaration in, or in which we should
6493 // create the declaration.
6494 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006495 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006496 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006497 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006498
John McCallde3fd222010-10-12 23:13:28 +00006499 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006500
John McCallde3fd222010-10-12 23:13:28 +00006501 // There are four cases here.
6502 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006503 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006504 // there as appropriate.
6505 // Recover from invalid scope qualifiers as if they just weren't there.
6506 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006507 // C++0x [namespace.memdef]p3:
6508 // If the name in a friend declaration is neither qualified nor
6509 // a template-id and the declaration is a function or an
6510 // elaborated-type-specifier, the lookup to determine whether
6511 // the entity has been previously declared shall not consider
6512 // any scopes outside the innermost enclosing namespace.
6513 // C++0x [class.friend]p11:
6514 // If a friend declaration appears in a local class and the name
6515 // specified is an unqualified name, a prior declaration is
6516 // looked up without considering scopes that are outside the
6517 // innermost enclosing non-class scope. For a friend function
6518 // declaration, if there is no prior declaration, the program is
6519 // ill-formed.
6520 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006521 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006522
John McCallf7cfb222010-10-13 05:45:15 +00006523 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006524 DC = CurContext;
6525 while (true) {
6526 // Skip class contexts. If someone can cite chapter and verse
6527 // for this behavior, that would be nice --- it's what GCC and
6528 // EDG do, and it seems like a reasonable intent, but the spec
6529 // really only says that checks for unqualified existing
6530 // declarations should stop at the nearest enclosing namespace,
6531 // not that they should only consider the nearest enclosing
6532 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006533 while (DC->isRecord())
6534 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006535
John McCall1f82f242009-11-18 22:49:29 +00006536 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006537
6538 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006539 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006540 break;
John McCallf7cfb222010-10-13 05:45:15 +00006541
John McCallf4776592010-10-14 22:22:28 +00006542 if (isTemplateId) {
6543 if (isa<TranslationUnitDecl>(DC)) break;
6544 } else {
6545 if (DC->isFileContext()) break;
6546 }
John McCall07e91c02009-08-06 02:15:43 +00006547 DC = DC->getParent();
6548 }
6549
6550 // C++ [class.friend]p1: A friend of a class is a function or
6551 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006552 // C++0x changes this for both friend types and functions.
6553 // Most C++ 98 compilers do seem to give an error here, so
6554 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006555 if (!Previous.empty() && DC->Equals(CurContext)
6556 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006557 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006558
John McCallccbc0322010-10-13 06:22:15 +00006559 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006560
John McCallde3fd222010-10-12 23:13:28 +00006561 // - There's a non-dependent scope specifier, in which case we
6562 // compute it and do a previous lookup there for a function
6563 // or function template.
6564 } else if (!SS.getScopeRep()->isDependent()) {
6565 DC = computeDeclContext(SS);
6566 if (!DC) return 0;
6567
6568 if (RequireCompleteDeclContext(SS, DC)) return 0;
6569
6570 LookupQualifiedName(Previous, DC);
6571
6572 // Ignore things found implicitly in the wrong scope.
6573 // TODO: better diagnostics for this case. Suggesting the right
6574 // qualified scope would be nice...
6575 LookupResult::Filter F = Previous.makeFilter();
6576 while (F.hasNext()) {
6577 NamedDecl *D = F.next();
6578 if (!DC->InEnclosingNamespaceSetOf(
6579 D->getDeclContext()->getRedeclContext()))
6580 F.erase();
6581 }
6582 F.done();
6583
6584 if (Previous.empty()) {
6585 D.setInvalidType();
6586 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6587 return 0;
6588 }
6589
6590 // C++ [class.friend]p1: A friend of a class is a function or
6591 // class that is not a member of the class . . .
6592 if (DC->Equals(CurContext))
6593 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6594
6595 // - There's a scope specifier that does not match any template
6596 // parameter lists, in which case we use some arbitrary context,
6597 // create a method or method template, and wait for instantiation.
6598 // - There's a scope specifier that does match some template
6599 // parameter lists, which we don't handle right now.
6600 } else {
6601 DC = CurContext;
6602 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006603 }
6604
John McCallf7cfb222010-10-13 05:45:15 +00006605 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006606 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006607 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6608 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6609 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006610 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006611 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6612 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006613 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006614 }
John McCall07e91c02009-08-06 02:15:43 +00006615 }
6616
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006617 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006618 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006619 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006620 IsDefinition,
6621 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006622 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006623
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006624 assert(ND->getDeclContext() == DC);
6625 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006626
John McCall759e32b2009-08-31 22:39:49 +00006627 // Add the function declaration to the appropriate lookup tables,
6628 // adjusting the redeclarations list as necessary. We don't
6629 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006630 //
John McCall759e32b2009-08-31 22:39:49 +00006631 // Also update the scope-based lookup if the target context's
6632 // lookup context is in lexical scope.
6633 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006634 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006635 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006636 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006637 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006638 }
John McCallaa74a0c2009-08-28 07:59:38 +00006639
6640 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006641 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006642 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006643 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006644 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006645
John McCallde3fd222010-10-12 23:13:28 +00006646 if (ND->isInvalidDecl())
6647 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006648 else {
6649 FunctionDecl *FD;
6650 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6651 FD = FTD->getTemplatedDecl();
6652 else
6653 FD = cast<FunctionDecl>(ND);
6654
6655 // Mark templated-scope function declarations as unsupported.
6656 if (FD->getNumTemplateParameterLists())
6657 FrD->setUnsupportedFriend(true);
6658 }
John McCallde3fd222010-10-12 23:13:28 +00006659
John McCall48871652010-08-21 09:40:31 +00006660 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006661}
6662
John McCall48871652010-08-21 09:40:31 +00006663void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6664 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006665
Sebastian Redlf769df52009-03-24 22:27:57 +00006666 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6667 if (!Fn) {
6668 Diag(DelLoc, diag::err_deleted_non_function);
6669 return;
6670 }
6671 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6672 Diag(DelLoc, diag::err_deleted_decl_not_first);
6673 Diag(Prev->getLocation(), diag::note_previous_declaration);
6674 // If the declaration wasn't the first, we delete the function anyway for
6675 // recovery.
6676 }
6677 Fn->setDeleted();
6678}
Sebastian Redl4c018662009-04-27 21:33:24 +00006679
6680static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6681 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6682 ++CI) {
6683 Stmt *SubStmt = *CI;
6684 if (!SubStmt)
6685 continue;
6686 if (isa<ReturnStmt>(SubStmt))
6687 Self.Diag(SubStmt->getSourceRange().getBegin(),
6688 diag::err_return_in_constructor_handler);
6689 if (!isa<Expr>(SubStmt))
6690 SearchForReturnInStmt(Self, SubStmt);
6691 }
6692}
6693
6694void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6695 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6696 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6697 SearchForReturnInStmt(*this, Handler);
6698 }
6699}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006700
Mike Stump11289f42009-09-09 15:08:12 +00006701bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006702 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006703 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6704 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006705
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006706 if (Context.hasSameType(NewTy, OldTy) ||
6707 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006708 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006709
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006710 // Check if the return types are covariant
6711 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006712
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006713 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006714 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6715 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006716 NewClassTy = NewPT->getPointeeType();
6717 OldClassTy = OldPT->getPointeeType();
6718 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006719 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6720 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6721 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6722 NewClassTy = NewRT->getPointeeType();
6723 OldClassTy = OldRT->getPointeeType();
6724 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006725 }
6726 }
Mike Stump11289f42009-09-09 15:08:12 +00006727
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006728 // The return types aren't either both pointers or references to a class type.
6729 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006730 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006731 diag::err_different_return_type_for_overriding_virtual_function)
6732 << New->getDeclName() << NewTy << OldTy;
6733 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006734
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006735 return true;
6736 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006737
Anders Carlssone60365b2009-12-31 18:34:24 +00006738 // C++ [class.virtual]p6:
6739 // If the return type of D::f differs from the return type of B::f, the
6740 // class type in the return type of D::f shall be complete at the point of
6741 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006742 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6743 if (!RT->isBeingDefined() &&
6744 RequireCompleteType(New->getLocation(), NewClassTy,
6745 PDiag(diag::err_covariant_return_incomplete)
6746 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006747 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006748 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006749
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006750 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006751 // Check if the new class derives from the old class.
6752 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6753 Diag(New->getLocation(),
6754 diag::err_covariant_return_not_derived)
6755 << New->getDeclName() << NewTy << OldTy;
6756 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6757 return true;
6758 }
Mike Stump11289f42009-09-09 15:08:12 +00006759
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006760 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006761 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006762 diag::err_covariant_return_inaccessible_base,
6763 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6764 // FIXME: Should this point to the return type?
6765 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006766 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6767 return true;
6768 }
6769 }
Mike Stump11289f42009-09-09 15:08:12 +00006770
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006771 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006772 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006773 Diag(New->getLocation(),
6774 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006775 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006776 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6777 return true;
6778 };
Mike Stump11289f42009-09-09 15:08:12 +00006779
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006780
6781 // The new class type must have the same or less qualifiers as the old type.
6782 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6783 Diag(New->getLocation(),
6784 diag::err_covariant_return_type_class_type_more_qualified)
6785 << New->getDeclName() << NewTy << OldTy;
6786 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6787 return true;
6788 };
Mike Stump11289f42009-09-09 15:08:12 +00006789
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006790 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006791}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006792
Alexis Hunt96d5c762009-11-21 08:43:09 +00006793bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6794 const CXXMethodDecl *Old)
6795{
6796 if (Old->hasAttr<FinalAttr>()) {
6797 Diag(New->getLocation(), diag::err_final_function_overridden)
6798 << New->getDeclName();
6799 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6800 return true;
6801 }
6802
6803 return false;
6804}
6805
Douglas Gregor21920e372009-12-01 17:24:26 +00006806/// \brief Mark the given method pure.
6807///
6808/// \param Method the method to be marked pure.
6809///
6810/// \param InitRange the source range that covers the "0" initializer.
6811bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6812 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6813 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006814 return false;
6815 }
6816
6817 if (!Method->isInvalidDecl())
6818 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6819 << Method->getDeclName() << InitRange;
6820 return true;
6821}
6822
John McCall1f4ee7b2009-12-19 09:28:58 +00006823/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6824/// an initializer for the out-of-line declaration 'Dcl'. The scope
6825/// is a fresh scope pushed for just this purpose.
6826///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006827/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6828/// static data member of class X, names should be looked up in the scope of
6829/// class X.
John McCall48871652010-08-21 09:40:31 +00006830void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006831 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006832 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006833
John McCall1f4ee7b2009-12-19 09:28:58 +00006834 // We should only get called for declarations with scope specifiers, like:
6835 // int foo::bar;
6836 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006837 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006838}
6839
6840/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006841/// initializer for the out-of-line declaration 'D'.
6842void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006843 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006844 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006845
John McCall1f4ee7b2009-12-19 09:28:58 +00006846 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006847 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006848}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006849
6850/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6851/// C++ if/switch/while/for statement.
6852/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006853DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006854 // C++ 6.4p2:
6855 // The declarator shall not specify a function or an array.
6856 // The type-specifier-seq shall not contain typedef and shall not declare a
6857 // new class or enumeration.
6858 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6859 "Parser allowed 'typedef' as storage class of condition decl.");
6860
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006861 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006862 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6863 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006864
6865 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6866 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6867 // would be created and CXXConditionDeclExpr wants a VarDecl.
6868 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6869 << D.getSourceRange();
6870 return DeclResult();
6871 } else if (OwnedTag && OwnedTag->isDefinition()) {
6872 // The type-specifier-seq shall not declare a new class or enumeration.
6873 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6874 }
6875
John McCall48871652010-08-21 09:40:31 +00006876 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006877 if (!Dcl)
6878 return DeclResult();
6879
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006880 return Dcl;
6881}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006882
Douglas Gregor88d292c2010-05-13 16:44:06 +00006883void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6884 bool DefinitionRequired) {
6885 // Ignore any vtable uses in unevaluated operands or for classes that do
6886 // not have a vtable.
6887 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6888 CurContext->isDependentContext() ||
6889 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006890 return;
6891
Douglas Gregor88d292c2010-05-13 16:44:06 +00006892 // Try to insert this class into the map.
6893 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6894 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6895 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6896 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006897 // If we already had an entry, check to see if we are promoting this vtable
6898 // to required a definition. If so, we need to reappend to the VTableUses
6899 // list, since we may have already processed the first entry.
6900 if (DefinitionRequired && !Pos.first->second) {
6901 Pos.first->second = true;
6902 } else {
6903 // Otherwise, we can early exit.
6904 return;
6905 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006906 }
6907
6908 // Local classes need to have their virtual members marked
6909 // immediately. For all other classes, we mark their virtual members
6910 // at the end of the translation unit.
6911 if (Class->isLocalClass())
6912 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006913 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006914 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006915}
6916
Douglas Gregor88d292c2010-05-13 16:44:06 +00006917bool Sema::DefineUsedVTables() {
6918 // If any dynamic classes have their key function defined within
6919 // this translation unit, then those vtables are considered "used" and must
6920 // be emitted.
6921 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6922 if (const CXXMethodDecl *KeyFunction
6923 = Context.getKeyFunction(DynamicClasses[I])) {
6924 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006925 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006926 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6927 }
6928 }
6929
6930 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006931 return false;
6932
Douglas Gregor88d292c2010-05-13 16:44:06 +00006933 // Note: The VTableUses vector could grow as a result of marking
6934 // the members of a class as "used", so we check the size each
6935 // time through the loop and prefer indices (with are stable) to
6936 // iterators (which are not).
6937 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006938 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006939 if (!Class)
6940 continue;
6941
6942 SourceLocation Loc = VTableUses[I].second;
6943
6944 // If this class has a key function, but that key function is
6945 // defined in another translation unit, we don't need to emit the
6946 // vtable even though we're using it.
6947 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006948 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006949 switch (KeyFunction->getTemplateSpecializationKind()) {
6950 case TSK_Undeclared:
6951 case TSK_ExplicitSpecialization:
6952 case TSK_ExplicitInstantiationDeclaration:
6953 // The key function is in another translation unit.
6954 continue;
6955
6956 case TSK_ExplicitInstantiationDefinition:
6957 case TSK_ImplicitInstantiation:
6958 // We will be instantiating the key function.
6959 break;
6960 }
6961 } else if (!KeyFunction) {
6962 // If we have a class with no key function that is the subject
6963 // of an explicit instantiation declaration, suppress the
6964 // vtable; it will live with the explicit instantiation
6965 // definition.
6966 bool IsExplicitInstantiationDeclaration
6967 = Class->getTemplateSpecializationKind()
6968 == TSK_ExplicitInstantiationDeclaration;
6969 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6970 REnd = Class->redecls_end();
6971 R != REnd; ++R) {
6972 TemplateSpecializationKind TSK
6973 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6974 if (TSK == TSK_ExplicitInstantiationDeclaration)
6975 IsExplicitInstantiationDeclaration = true;
6976 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6977 IsExplicitInstantiationDeclaration = false;
6978 break;
6979 }
6980 }
6981
6982 if (IsExplicitInstantiationDeclaration)
6983 continue;
6984 }
6985
6986 // Mark all of the virtual members of this class as referenced, so
6987 // that we can build a vtable. Then, tell the AST consumer that a
6988 // vtable for this class is required.
6989 MarkVirtualMembersReferenced(Loc, Class);
6990 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6991 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6992
6993 // Optionally warn if we're emitting a weak vtable.
6994 if (Class->getLinkage() == ExternalLinkage &&
6995 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006996 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006997 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6998 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006999 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007000 VTableUses.clear();
7001
Anders Carlsson82fccd02009-12-07 08:24:59 +00007002 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007003}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007004
Rafael Espindola5b334082010-03-26 00:36:59 +00007005void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7006 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007007 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7008 e = RD->method_end(); i != e; ++i) {
7009 CXXMethodDecl *MD = *i;
7010
7011 // C++ [basic.def.odr]p2:
7012 // [...] A virtual member function is used if it is not pure. [...]
7013 if (MD->isVirtual() && !MD->isPure())
7014 MarkDeclarationReferenced(Loc, MD);
7015 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007016
7017 // Only classes that have virtual bases need a VTT.
7018 if (RD->getNumVBases() == 0)
7019 return;
7020
7021 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7022 e = RD->bases_end(); i != e; ++i) {
7023 const CXXRecordDecl *Base =
7024 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007025 if (Base->getNumVBases() == 0)
7026 continue;
7027 MarkVirtualMembersReferenced(Loc, Base);
7028 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007029}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007030
7031/// SetIvarInitializers - This routine builds initialization ASTs for the
7032/// Objective-C implementation whose ivars need be initialized.
7033void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7034 if (!getLangOptions().CPlusPlus)
7035 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007036 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007037 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7038 CollectIvarsToConstructOrDestruct(OID, ivars);
7039 if (ivars.empty())
7040 return;
7041 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7042 for (unsigned i = 0; i < ivars.size(); i++) {
7043 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007044 if (Field->isInvalidDecl())
7045 continue;
7046
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007047 CXXBaseOrMemberInitializer *Member;
7048 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7049 InitializationKind InitKind =
7050 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7051
7052 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007053 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007054 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00007055 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007056 // Note, MemberInit could actually come back empty if no initialization
7057 // is required (e.g., because it would call a trivial default constructor)
7058 if (!MemberInit.get() || MemberInit.isInvalid())
7059 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007060
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007061 Member =
7062 new (Context) CXXBaseOrMemberInitializer(Context,
7063 Field, SourceLocation(),
7064 SourceLocation(),
7065 MemberInit.takeAs<Expr>(),
7066 SourceLocation());
7067 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007068
7069 // Be sure that the destructor is accessible and is marked as referenced.
7070 if (const RecordType *RecordTy
7071 = Context.getBaseElementType(Field->getType())
7072 ->getAs<RecordType>()) {
7073 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007074 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007075 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7076 CheckDestructorAccess(Field->getLocation(), Destructor,
7077 PDiag(diag::err_access_dtor_ivar)
7078 << Context.getBaseElementType(Field->getType()));
7079 }
7080 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007081 }
7082 ObjCImplementation->setIvarInitializers(Context,
7083 AllToInit.data(), AllToInit.size());
7084 }
7085}