blob: 564dab49de83bcab440906fd4a0535d2670be282 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-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 Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-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 Carlssoned961f92009-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 Jahanian745da3a2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000138
John McCallb4eb64d2010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
Anders Carlsson0ece4912009-12-15 20:51:39 +0000140 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8cfb7a32010-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 Carlsson9351c172009-08-25 03:18:48 +0000157 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000158}
159
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000163void
John McCalld226f652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCalld226f652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177 return;
178 }
179
Anders Carlsson66e30672009-08-25 01:02:06 +0000180 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000181 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
182 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000183 Param->setInvalidDecl();
184 return;
185 }
Mike Stump1eb44332009-09-09 15:08:12 +0000186
John McCall9ae2f072010-08-23 23:25:46 +0000187 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000188}
189
Douglas Gregor61366e92008-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 McCalld226f652010-08-21 09:40:31 +0000194void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 SourceLocation EqualLoc,
196 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
John McCalld226f652010-08-21 09:40:31 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000201 if (Param)
202 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000205}
206
Douglas Gregor72b505b2008-12-16 21:30:33 +0000207/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
208/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000209void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000210 if (!param)
211 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000212
John McCalld226f652010-08-21 09:40:31 +0000213 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Anders Carlsson5e300d12009-06-12 16:51:40 +0000215 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Anders Carlsson5e300d12009-06-12 16:51:40 +0000217 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000218}
219
Douglas Gregor6d6eb572008-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 Lattnerb28317a2009-03-28 19:18:32 +0000233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000234 DeclaratorChunk &chunk = D.getTypeObject(i);
235 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000236 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
237 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000238 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000239 if (Param->hasUnparsedDefaultArg()) {
240 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-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 Gregor61366e92008-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 Gregor6d6eb572008-05-07 04:49:29 +0000249 }
250 }
251 }
252 }
253}
254
Chris Lattner3d1cee32008-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 Gregorcda9c672009-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 Lattner3d1cee32008-04-08 05:04:30 +0000262 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-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 Gregor6cc15182009-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 Lattner3d1cee32008-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 Gregor6cc15182009-09-11 18:44:32 +0000284 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-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 Stump1eb44332009-09-09 15:08:12 +0000294 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000295 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000296 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-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 Gregorcda9c672009-02-16 17:45:42 +0000310 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000311 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-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 McCallbf73b352010-03-12 18:31:32 +0000315 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000316 if (OldParam->hasUninstantiatedDefaultArg())
317 NewParam->setUninstantiatedDefaultArg(
318 OldParam->getUninstantiatedDefaultArg());
319 else
John McCall3d6c1782010-05-04 01:53:42 +0000320 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-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 Gregor096ebfd2009-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 Gregor8c638ab2009-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 Gregor096ebfd2009-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 Gregor6cc15182009-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 Lattner3d1cee32008-04-08 05:04:30 +0000371 }
372 }
373
Douglas Gregore13ad832010-02-12 07:32:17 +0000374 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000375 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000376
Douglas Gregorcda9c672009-02-16 17:45:42 +0000377 return Invalid;
Chris Lattner3d1cee32008-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 Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-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 Stump1eb44332009-09-09 15:08:12 +0000401 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000403 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000404 if (Param->isInvalidDecl())
405 /* We already complained about this parameter. */;
406 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000407 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000408 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000409 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000410 else
Mike Stump1eb44332009-09-09 15:08:12 +0000411 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000412 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner3d1cee32008-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 Carlsson5e300d12009-06-12 16:51:40 +0000425 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000426 Param->setDefaultArg(0);
427 }
428 }
429 }
430}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000431
Douglas Gregorb48fe382008-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 Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000436bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
437 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000438 assert(getLangOptions().CPlusPlus && "No class names in C!");
439
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000440 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000441 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000442 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-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 Gregor6f7a17b2010-02-05 06:12:42 +0000447 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000448 return &II == CurDecl->getIdentifier();
449 else
450 return false;
451}
452
Mike Stump1eb44332009-09-09 15:08:12 +0000453/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-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 Lewycky56062202010-07-26 16:56:01 +0000461 TypeSourceInfo *TInfo) {
462 QualType BaseType = TInfo->getType();
463
Douglas Gregor2943aed2009-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 Stump1eb44332009-09-09 15:08:12 +0000473 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000474 Class->getTagKind() == TTK_Class,
475 Access, TInfo);
476
477 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-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 Stump1eb44332009-09-09 15:08:12 +0000495 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000496 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000497 << SpecifierRange)) {
498 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499 return 0;
John McCall572fc622010-08-17 07:23:57 +0000500 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000501
Eli Friedman1d954f62009-08-15 21:55:26 +0000502 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000503 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000504 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000505 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000506 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000507 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
508 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000509
Sean Huntbbd37c62009-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 Gregor9af2f522009-12-01 16:58:18 +0000513 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
514 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000515 return 0;
516 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000517
John McCall572fc622010-08-17 07:23:57 +0000518 if (BaseDecl->isInvalidDecl())
519 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000520
521 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000522 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000523 Class->getTagKind() == TTK_Class,
524 Access, TInfo);
Anders Carlsson51f94042009-12-03 17:49:57 +0000525}
526
Douglas Gregore37ac4f2008-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 Stump1eb44332009-09-09 15:08:12 +0000529/// example:
530/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000531/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000532BaseResult
John McCalld226f652010-08-21 09:40:31 +0000533Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000534 bool Virtual, AccessSpecifier Access,
John McCallb3d87482010-08-24 05:47:05 +0000535 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000536 if (!classdecl)
537 return true;
538
Douglas Gregor40808ce2009-03-09 23:48:35 +0000539 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000541 if (!Class)
542 return true;
543
Nick Lewycky56062202010-07-26 16:56:01 +0000544 TypeSourceInfo *TInfo = 0;
545 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000546 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000547 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000548 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Douglas Gregor2943aed2009-03-03 04:44:36 +0000550 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000551}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000552
Douglas Gregor2943aed2009-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 Gregorf8268ae2008-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 Gregor57c856b2008-10-23 18:13:27 +0000562 // that the key is always the unqualified canonical type of the base
563 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000564 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
565
566 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000567 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000569 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000570 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000572 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-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 Gregorf8268ae2008-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 Gregor2943aed2009-03-03 04:44:36 +0000584 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000585 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000586 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000587 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000588
589 // Delete the duplicate base class specifier; we're going to
590 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000591 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000592
593 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000594 } else {
595 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 KnownBaseTypes[NewBaseType] = Bases[idx];
597 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000598 }
599 }
600
601 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000602 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-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 Gregor2aef06d2009-07-22 20:55:49 +0000607 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-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 McCalld226f652010-08-21 09:40:31 +0000615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 unsigned NumBases) {
617 if (!ClassDecl || !Bases || !NumBases)
618 return;
619
620 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000622 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000623}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000624
John McCall3cb0ebd2010-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 Gregora8f32e02009-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 McCall3cb0ebd2010-03-10 03:28:59 +0000639
640 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
641 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000642 return false;
643
John McCall3cb0ebd2010-03-10 03:28:59 +0000644 CXXRecordDecl *BaseRD = GetClassForType(Base);
645 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000646 return false;
647
John McCall86ff3082010-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 Gregora8f32e02009-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 McCall3cb0ebd2010-03-10 03:28:59 +0000658 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
659 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000660 return false;
661
John McCall3cb0ebd2010-03-10 03:28:59 +0000662 CXXRecordDecl *BaseRD = GetClassForType(Base);
663 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000664 return false;
665
Douglas Gregora8f32e02009-10-06 17:59:45 +0000666 return DerivedRD->isDerivedFrom(BaseRD, Paths);
667}
668
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000669void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000670 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-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 McCallf871d0c2010-08-07 06:22:56 +0000689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000690}
691
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000692/// \brief Determine whether the given base path includes a virtual
693/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000694bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
695 for (CXXCastPath::const_iterator B = BasePath.begin(),
696 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000697 B != BEnd; ++B)
698 if ((*B)->isVirtual())
699 return true;
700
701 return false;
702}
703
Douglas Gregora8f32e02009-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 McCall58e6f342010-03-16 05:22:47 +0000714 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715 unsigned AmbigiousBaseConvID,
716 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000717 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000718 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-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 Carlsson5cf86ba2010-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 Carlssone25a96c2010-04-24 17:11:09 +0000741 }
John McCall6b2accb2010-02-10 09:31:12 +0000742 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000743
744 // Build a base path if necessary.
745 if (BasePath)
746 BuildBasePathArray(Paths, *BasePath);
747 return false;
Douglas Gregora8f32e02009-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 Redla82e4ae2009-11-14 21:15:49 +0000775 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000776 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000777 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000778 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000779 IgnoreAccess ? 0
780 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000781 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000782 Loc, Range, DeclarationName(),
783 BasePath);
Douglas Gregora8f32e02009-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 Kyrtzidis07952322008-07-01 10:37:29 +0000818//===----------------------------------------------------------------------===//
819// C++ class member Handling
820//===----------------------------------------------------------------------===//
821
Abramo Bagnara6206d532010-06-05 05:09:32 +0000822/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000823Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
824 SourceLocation ASLoc,
825 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000826 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000827 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000828 ASLoc, ColonLoc);
829 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000830 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000831}
832
Argyrios Kyrtzidis07952322008-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 Lattnerb6688e02009-04-12 22:37:57 +0000836/// any.
John McCalld226f652010-08-21 09:40:31 +0000837Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000838Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000839 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000840 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
841 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000843 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
844 DeclarationName Name = NameInfo.getName();
845 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000846 Expr *BitWidth = static_cast<Expr*>(BW);
847 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000848
John McCall4bde1e12010-06-04 08:34:12 +0000849 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000850 assert(!DS.isFriendSpecified());
851
John McCall4bde1e12010-06-04 08:34:12 +0000852 bool isFunc = false;
853 if (D.isFunctionDeclarator())
854 isFunc = true;
855 else if (D.getNumTypeObjects() == 0 &&
856 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000857 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000858 isFunc = TDType->isFunctionType();
859 }
860
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000861 // C++ 9.2p6: A member shall not be declared to have automatic storage
862 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000863 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
864 // data members and cannot be applied to names declared const or static,
865 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000866 switch (DS.getStorageClassSpec()) {
867 case DeclSpec::SCS_unspecified:
868 case DeclSpec::SCS_typedef:
869 case DeclSpec::SCS_static:
870 // FALL THROUGH.
871 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000872 case DeclSpec::SCS_mutable:
873 if (isFunc) {
874 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000875 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000876 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000877 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Sebastian Redla11f42f2008-11-17 23:24:37 +0000879 // FIXME: It would be nicer if the keyword was ignored only for this
880 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000881 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000882 }
883 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884 default:
885 if (DS.getStorageClassSpecLoc().isValid())
886 Diag(DS.getStorageClassSpecLoc(),
887 diag::err_storageclass_invalid_for_member);
888 else
889 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
890 D.getMutableDeclSpec().ClearStorageClassSpecs();
891 }
892
Sebastian Redl669d5d72008-11-14 23:42:31 +0000893 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
894 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000895 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000896
897 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000898 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000899 CXXScopeSpec &SS = D.getCXXScopeSpec();
900
901
902 if (SS.isSet() && !SS.isInvalid()) {
903 // The user provided a superfluous scope specifier inside a class
904 // definition:
905 //
906 // class X {
907 // int X::member;
908 // };
909 DeclContext *DC = 0;
910 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
911 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
912 << Name << FixItHint::CreateRemoval(SS.getRange());
913 else
914 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
915 << Name << SS.getRange();
916
917 SS.clear();
918 }
919
Douglas Gregor37b372b2009-08-20 22:52:58 +0000920 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000921 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
922 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000923 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000924 } else {
John McCalld226f652010-08-21 09:40:31 +0000925 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000926 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000927 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000928 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000929
930 // Non-instance-fields can't have a bitfield.
931 if (BitWidth) {
932 if (Member->isInvalidDecl()) {
933 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000934 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000935 // C++ 9.6p3: A bit-field shall not be a static member.
936 // "static member 'A' cannot be a bit-field"
937 Diag(Loc, diag::err_static_not_bitfield)
938 << Name << BitWidth->getSourceRange();
939 } else if (isa<TypedefDecl>(Member)) {
940 // "typedef member 'x' cannot be a bit-field"
941 Diag(Loc, diag::err_typedef_not_bitfield)
942 << Name << BitWidth->getSourceRange();
943 } else {
944 // A function typedef ("typedef int f(); f a;").
945 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
946 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000947 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000948 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner8b963ef2009-03-05 23:01:03 +0000951 BitWidth = 0;
952 Member->setInvalidDecl();
953 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000954
955 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregor37b372b2009-08-20 22:52:58 +0000957 // If we have declared a member function template, set the access of the
958 // templated declaration as well.
959 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
960 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000961 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000962
Douglas Gregor10bd3682008-11-17 22:58:34 +0000963 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000964
Douglas Gregor021c3b32009-03-11 23:00:04 +0000965 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +0000966 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000967 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +0000968 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000969
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000970 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000971 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +0000972 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000973 }
John McCalld226f652010-08-21 09:40:31 +0000974 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000975}
976
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000977/// \brief Find the direct and/or virtual base specifiers that
978/// correspond to the given base type, for use in base initialization
979/// within a constructor.
980static bool FindBaseInitializer(Sema &SemaRef,
981 CXXRecordDecl *ClassDecl,
982 QualType BaseType,
983 const CXXBaseSpecifier *&DirectBaseSpec,
984 const CXXBaseSpecifier *&VirtualBaseSpec) {
985 // First, check for a direct base class.
986 DirectBaseSpec = 0;
987 for (CXXRecordDecl::base_class_const_iterator Base
988 = ClassDecl->bases_begin();
989 Base != ClassDecl->bases_end(); ++Base) {
990 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
991 // We found a direct base of this type. That's what we're
992 // initializing.
993 DirectBaseSpec = &*Base;
994 break;
995 }
996 }
997
998 // Check for a virtual base class.
999 // FIXME: We might be able to short-circuit this if we know in advance that
1000 // there are no virtual bases.
1001 VirtualBaseSpec = 0;
1002 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1003 // We haven't found a base yet; search the class hierarchy for a
1004 // virtual base class.
1005 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1006 /*DetectVirtual=*/false);
1007 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1008 BaseType, Paths)) {
1009 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1010 Path != Paths.end(); ++Path) {
1011 if (Path->back().Base->isVirtual()) {
1012 VirtualBaseSpec = Path->back().Base;
1013 break;
1014 }
1015 }
1016 }
1017 }
1018
1019 return DirectBaseSpec || VirtualBaseSpec;
1020}
1021
Douglas Gregor7ad83902008-11-05 04:29:56 +00001022/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001023MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001024Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001025 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001026 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001027 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001028 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001029 SourceLocation IdLoc,
1030 SourceLocation LParenLoc,
1031 ExprTy **Args, unsigned NumArgs,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001032 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001033 if (!ConstructorD)
1034 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001036 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001037
1038 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001039 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001040 if (!Constructor) {
1041 // The user wrote a constructor initializer on a function that is
1042 // not a C++ constructor. Ignore the error for now, because we may
1043 // have more member initializers coming; we'll diagnose it just
1044 // once in ActOnMemInitializers.
1045 return true;
1046 }
1047
1048 CXXRecordDecl *ClassDecl = Constructor->getParent();
1049
1050 // C++ [class.base.init]p2:
1051 // Names in a mem-initializer-id are looked up in the scope of the
1052 // constructor’s class and, if not found in that scope, are looked
1053 // up in the scope containing the constructor’s
1054 // definition. [Note: if the constructor’s class contains a member
1055 // with the same name as a direct or virtual base class of the
1056 // class, a mem-initializer-id naming the member or base class and
1057 // composed of a single identifier refers to the class member. A
1058 // mem-initializer-id for the hidden base class may be specified
1059 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001060 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001061 // Look for a member, first.
1062 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001063 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001064 = ClassDecl->lookup(MemberOrBase);
1065 if (Result.first != Result.second)
1066 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001067
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001068 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001069
Eli Friedman59c04372009-07-29 19:44:27 +00001070 if (Member)
1071 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001072 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001073 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001074 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001075 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001076 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001077
1078 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001079 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001080 } else {
1081 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1082 LookupParsedName(R, S, &SS);
1083
1084 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1085 if (!TyD) {
1086 if (R.isAmbiguous()) return true;
1087
John McCallfd225442010-04-09 19:01:14 +00001088 // We don't want access-control diagnostics here.
1089 R.suppressDiagnostics();
1090
Douglas Gregor7a886e12010-01-19 06:46:48 +00001091 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1092 bool NotUnknownSpecialization = false;
1093 DeclContext *DC = computeDeclContext(SS, false);
1094 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1095 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1096
1097 if (!NotUnknownSpecialization) {
1098 // When the scope specifier can refer to a member of an unknown
1099 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001100 BaseType = CheckTypenameType(ETK_None,
1101 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001102 *MemberOrBase, SourceLocation(),
1103 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001104 if (BaseType.isNull())
1105 return true;
1106
Douglas Gregor7a886e12010-01-19 06:46:48 +00001107 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001108 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001109 }
1110 }
1111
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001112 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001113 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001114 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1115 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001116 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001117 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001118 // We have found a non-static data member with a similar
1119 // name to what was typed; complain and initialize that
1120 // member.
1121 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1122 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001123 << FixItHint::CreateReplacement(R.getNameLoc(),
1124 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001125 Diag(Member->getLocation(), diag::note_previous_decl)
1126 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001127
1128 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1129 LParenLoc, RParenLoc);
1130 }
1131 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1132 const CXXBaseSpecifier *DirectBaseSpec;
1133 const CXXBaseSpecifier *VirtualBaseSpec;
1134 if (FindBaseInitializer(*this, ClassDecl,
1135 Context.getTypeDeclType(Type),
1136 DirectBaseSpec, VirtualBaseSpec)) {
1137 // We have found a direct or virtual base class with a
1138 // similar name to what was typed; complain and initialize
1139 // that base class.
1140 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1141 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001142 << FixItHint::CreateReplacement(R.getNameLoc(),
1143 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001144
1145 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1146 : VirtualBaseSpec;
1147 Diag(BaseSpec->getSourceRange().getBegin(),
1148 diag::note_base_class_specified_here)
1149 << BaseSpec->getType()
1150 << BaseSpec->getSourceRange();
1151
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001152 TyD = Type;
1153 }
1154 }
1155 }
1156
Douglas Gregor7a886e12010-01-19 06:46:48 +00001157 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001158 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1159 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1160 return true;
1161 }
John McCall2b194412009-12-21 10:41:20 +00001162 }
1163
Douglas Gregor7a886e12010-01-19 06:46:48 +00001164 if (BaseType.isNull()) {
1165 BaseType = Context.getTypeDeclType(TyD);
1166 if (SS.isSet()) {
1167 NestedNameSpecifier *Qualifier =
1168 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001169
Douglas Gregor7a886e12010-01-19 06:46:48 +00001170 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001171 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001172 }
John McCall2b194412009-12-21 10:41:20 +00001173 }
1174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
John McCalla93c9342009-12-07 02:54:59 +00001176 if (!TInfo)
1177 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001178
John McCalla93c9342009-12-07 02:54:59 +00001179 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001180 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001181}
1182
John McCallb4190042009-11-04 23:02:40 +00001183/// Checks an initializer expression for use of uninitialized fields, such as
1184/// containing the field that is being initialized. Returns true if there is an
1185/// uninitialized field was used an updates the SourceLocation parameter; false
1186/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001187static bool InitExprContainsUninitializedFields(const Stmt *S,
1188 const FieldDecl *LhsField,
1189 SourceLocation *L) {
1190 if (isa<CallExpr>(S)) {
1191 // Do not descend into function calls or constructors, as the use
1192 // of an uninitialized field may be valid. One would have to inspect
1193 // the contents of the function/ctor to determine if it is safe or not.
1194 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1195 // may be safe, depending on what the function/ctor does.
1196 return false;
1197 }
1198 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1199 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001200
1201 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1202 // The member expression points to a static data member.
1203 assert(VD->isStaticDataMember() &&
1204 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001205 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001206 return false;
1207 }
1208
1209 if (isa<EnumConstantDecl>(RhsField)) {
1210 // The member expression points to an enum.
1211 return false;
1212 }
1213
John McCallb4190042009-11-04 23:02:40 +00001214 if (RhsField == LhsField) {
1215 // Initializing a field with itself. Throw a warning.
1216 // But wait; there are exceptions!
1217 // Exception #1: The field may not belong to this record.
1218 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001219 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001220 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1221 // Even though the field matches, it does not belong to this record.
1222 return false;
1223 }
1224 // None of the exceptions triggered; return true to indicate an
1225 // uninitialized field was used.
1226 *L = ME->getMemberLoc();
1227 return true;
1228 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001229 } else if (isa<SizeOfAlignOfExpr>(S)) {
1230 // sizeof/alignof doesn't reference contents, do not warn.
1231 return false;
1232 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1233 // address-of doesn't reference contents (the pointer may be dereferenced
1234 // in the same expression but it would be rare; and weird).
1235 if (UOE->getOpcode() == UO_AddrOf)
1236 return false;
John McCallb4190042009-11-04 23:02:40 +00001237 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001238 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1239 it != e; ++it) {
1240 if (!*it) {
1241 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001242 continue;
1243 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001244 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1245 return true;
John McCallb4190042009-11-04 23:02:40 +00001246 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001247 return false;
John McCallb4190042009-11-04 23:02:40 +00001248}
1249
John McCallf312b1e2010-08-26 23:41:50 +00001250MemInitResult
Eli Friedman59c04372009-07-29 19:44:27 +00001251Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1252 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001253 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001254 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001255 // Diagnose value-uses of fields to initialize themselves, e.g.
1256 // foo(foo)
1257 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001258 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001259 for (unsigned i = 0; i < NumArgs; ++i) {
1260 SourceLocation L;
1261 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1262 // FIXME: Return true in the case when other fields are used before being
1263 // uninitialized. For example, let this field be the i'th field. When
1264 // initializing the i'th field, throw a warning if any of the >= i'th
1265 // fields are used, as they are not yet initialized.
1266 // Right now we are only handling the case where the i'th field uses
1267 // itself in its initializer.
1268 Diag(L, diag::warn_field_is_uninit);
1269 }
1270 }
1271
Eli Friedman59c04372009-07-29 19:44:27 +00001272 bool HasDependentArg = false;
1273 for (unsigned i = 0; i < NumArgs; i++)
1274 HasDependentArg |= Args[i]->isTypeDependent();
1275
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001276 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001277 // Can't check initialization for a member of dependent type or when
1278 // any of the arguments are type-dependent expressions.
John McCall9ae2f072010-08-23 23:25:46 +00001279 Expr *Init
1280 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1281 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001282
1283 // Erase any temporaries within this evaluation context; we're not
1284 // going to track them in the AST, since we'll be rebuilding the
1285 // ASTs during template instantiation.
1286 ExprTemporaries.erase(
1287 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1288 ExprTemporaries.end());
1289
1290 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1291 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001292 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001293 RParenLoc);
1294
Douglas Gregor7ad83902008-11-05 04:29:56 +00001295 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001296
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001297 if (Member->isInvalidDecl())
1298 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001299
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001300 // Initialize the member.
1301 InitializedEntity MemberEntity =
1302 InitializedEntity::InitializeMember(Member, 0);
1303 InitializationKind Kind =
1304 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1305
1306 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1307
John McCall60d7b3a2010-08-24 06:29:42 +00001308 ExprResult MemberInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001309 InitSeq.Perform(*this, MemberEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001310 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001311 if (MemberInit.isInvalid())
1312 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001313
1314 CheckImplicitConversions(MemberInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001315
1316 // C++0x [class.base.init]p7:
1317 // The initialization of each base and member constitutes a
1318 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001319 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001320 if (MemberInit.isInvalid())
1321 return true;
1322
1323 // If we are in a dependent context, template instantiation will
1324 // perform this type-checking again. Just save the arguments that we
1325 // received in a ParenListExpr.
1326 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1327 // of the information that we have about the member
1328 // initializer. However, deconstructing the ASTs is a dicey process,
1329 // and this approach is far more likely to get the corner cases right.
1330 if (CurContext->isDependentContext()) {
1331 // Bump the reference count of all of the arguments.
1332 for (unsigned I = 0; I != NumArgs; ++I)
1333 Args[I]->Retain();
1334
John McCall9ae2f072010-08-23 23:25:46 +00001335 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1336 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001337 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1338 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001339 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001340 RParenLoc);
1341 }
1342
Douglas Gregor802ab452009-12-02 22:36:29 +00001343 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001344 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001345 MemberInit.get(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001346 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001347}
1348
John McCallf312b1e2010-08-26 23:41:50 +00001349MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001350Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001351 Expr **Args, unsigned NumArgs,
1352 SourceLocation LParenLoc, SourceLocation RParenLoc,
1353 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001354 bool HasDependentArg = false;
1355 for (unsigned i = 0; i < NumArgs; i++)
1356 HasDependentArg |= Args[i]->isTypeDependent();
1357
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001358 SourceLocation BaseLoc
1359 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1360
1361 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1362 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1363 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1364
1365 // C++ [class.base.init]p2:
1366 // [...] Unless the mem-initializer-id names a nonstatic data
1367 // member of the constructor’s class or a direct or virtual base
1368 // of that class, the mem-initializer is ill-formed. A
1369 // mem-initializer-list can initialize a base class using any
1370 // name that denotes that base class type.
1371 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1372
1373 // Check for direct and virtual base classes.
1374 const CXXBaseSpecifier *DirectBaseSpec = 0;
1375 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1376 if (!Dependent) {
1377 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1378 VirtualBaseSpec);
1379
1380 // C++ [base.class.init]p2:
1381 // Unless the mem-initializer-id names a nonstatic data member of the
1382 // constructor's class or a direct or virtual base of that class, the
1383 // mem-initializer is ill-formed.
1384 if (!DirectBaseSpec && !VirtualBaseSpec) {
1385 // If the class has any dependent bases, then it's possible that
1386 // one of those types will resolve to the same type as
1387 // BaseType. Therefore, just treat this as a dependent base
1388 // class initialization. FIXME: Should we try to check the
1389 // initialization anyway? It seems odd.
1390 if (ClassDecl->hasAnyDependentBases())
1391 Dependent = true;
1392 else
1393 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1394 << BaseType << Context.getTypeDeclType(ClassDecl)
1395 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1396 }
1397 }
1398
1399 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001400 // Can't check initialization for a base of dependent type or when
1401 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001402 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001403 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1404 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001405
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001406 // Erase any temporaries within this evaluation context; we're not
1407 // going to track them in the AST, since we'll be rebuilding the
1408 // ASTs during template instantiation.
1409 ExprTemporaries.erase(
1410 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1411 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001413 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001414 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001415 LParenLoc,
1416 BaseInit.takeAs<Expr>(),
1417 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001418 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001419
1420 // C++ [base.class.init]p2:
1421 // If a mem-initializer-id is ambiguous because it designates both
1422 // a direct non-virtual base class and an inherited virtual base
1423 // class, the mem-initializer is ill-formed.
1424 if (DirectBaseSpec && VirtualBaseSpec)
1425 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001426 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001427
1428 CXXBaseSpecifier *BaseSpec
1429 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1430 if (!BaseSpec)
1431 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1432
1433 // Initialize the base.
1434 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001435 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001436 InitializationKind Kind =
1437 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1438
1439 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1440
John McCall60d7b3a2010-08-24 06:29:42 +00001441 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001442 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001443 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001444 if (BaseInit.isInvalid())
1445 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001446
1447 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001448
1449 // C++0x [class.base.init]p7:
1450 // The initialization of each base and member constitutes a
1451 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001452 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001453 if (BaseInit.isInvalid())
1454 return true;
1455
1456 // If we are in a dependent context, template instantiation will
1457 // perform this type-checking again. Just save the arguments that we
1458 // received in a ParenListExpr.
1459 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1460 // of the information that we have about the base
1461 // initializer. However, deconstructing the ASTs is a dicey process,
1462 // and this approach is far more likely to get the corner cases right.
1463 if (CurContext->isDependentContext()) {
1464 // Bump the reference count of all of the arguments.
1465 for (unsigned I = 0; I != NumArgs; ++I)
1466 Args[I]->Retain();
1467
John McCall60d7b3a2010-08-24 06:29:42 +00001468 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001469 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1470 RParenLoc));
1471 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001472 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001473 LParenLoc,
1474 Init.takeAs<Expr>(),
1475 RParenLoc);
1476 }
1477
1478 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001479 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001480 LParenLoc,
1481 BaseInit.takeAs<Expr>(),
1482 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001483}
1484
Anders Carlssone5ef7402010-04-23 03:10:23 +00001485/// ImplicitInitializerKind - How an implicit base or member initializer should
1486/// initialize its base or member.
1487enum ImplicitInitializerKind {
1488 IIK_Default,
1489 IIK_Copy,
1490 IIK_Move
1491};
1492
Anders Carlssondefefd22010-04-23 02:00:02 +00001493static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001494BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001495 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001496 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001497 bool IsInheritedVirtualBase,
1498 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001499 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001500 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1501 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001502
John McCall60d7b3a2010-08-24 06:29:42 +00001503 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001504
1505 switch (ImplicitInitKind) {
1506 case IIK_Default: {
1507 InitializationKind InitKind
1508 = InitializationKind::CreateDefault(Constructor->getLocation());
1509 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1510 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001511 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001512 break;
1513 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001514
Anders Carlssone5ef7402010-04-23 03:10:23 +00001515 case IIK_Copy: {
1516 ParmVarDecl *Param = Constructor->getParamDecl(0);
1517 QualType ParamType = Param->getType().getNonReferenceType();
1518
1519 Expr *CopyCtorArg =
1520 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001521 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001522
Anders Carlssonc7957502010-04-24 22:02:54 +00001523 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001524 QualType ArgTy =
1525 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1526 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001527
1528 CXXCastPath BasePath;
1529 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001530 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001531 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001532 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001533
Anders Carlssone5ef7402010-04-23 03:10:23 +00001534 InitializationKind InitKind
1535 = InitializationKind::CreateDirect(Constructor->getLocation(),
1536 SourceLocation(), SourceLocation());
1537 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1538 &CopyCtorArg, 1);
1539 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001540 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001541 break;
1542 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001543
Anders Carlssone5ef7402010-04-23 03:10:23 +00001544 case IIK_Move:
1545 assert(false && "Unhandled initializer kind!");
1546 }
John McCall9ae2f072010-08-23 23:25:46 +00001547
1548 if (BaseInit.isInvalid())
1549 return true;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001550
John McCall9ae2f072010-08-23 23:25:46 +00001551 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlsson84688f22010-04-20 23:11:20 +00001552 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001553 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001554
Anders Carlssondefefd22010-04-23 02:00:02 +00001555 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001556 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1557 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1558 SourceLocation()),
1559 BaseSpec->isVirtual(),
1560 SourceLocation(),
1561 BaseInit.takeAs<Expr>(),
1562 SourceLocation());
1563
Anders Carlssondefefd22010-04-23 02:00:02 +00001564 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001565}
1566
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001567static bool
1568BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001569 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001570 FieldDecl *Field,
1571 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001572 if (Field->isInvalidDecl())
1573 return true;
1574
Chandler Carruthf186b542010-06-29 23:50:44 +00001575 SourceLocation Loc = Constructor->getLocation();
1576
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001577 if (ImplicitInitKind == IIK_Copy) {
1578 ParmVarDecl *Param = Constructor->getParamDecl(0);
1579 QualType ParamType = Param->getType().getNonReferenceType();
1580
1581 Expr *MemberExprBase =
1582 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001583 Loc, ParamType, 0);
1584
1585 // Build a reference to this field within the parameter.
1586 CXXScopeSpec SS;
1587 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1588 Sema::LookupMemberName);
1589 MemberLookup.addDecl(Field, AS_public);
1590 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001591 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001592 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001593 ParamType, Loc,
1594 /*IsArrow=*/false,
1595 SS,
1596 /*FirstQualifierInScope=*/0,
1597 MemberLookup,
1598 /*TemplateArgs=*/0);
1599 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001600 return true;
1601
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001602 // When the field we are copying is an array, create index variables for
1603 // each dimension of the array. We use these index variables to subscript
1604 // the source array, and other clients (e.g., CodeGen) will perform the
1605 // necessary iteration with these index variables.
1606 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1607 QualType BaseType = Field->getType();
1608 QualType SizeType = SemaRef.Context.getSizeType();
1609 while (const ConstantArrayType *Array
1610 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1611 // Create the iteration variable for this array index.
1612 IdentifierInfo *IterationVarName = 0;
1613 {
1614 llvm::SmallString<8> Str;
1615 llvm::raw_svector_ostream OS(Str);
1616 OS << "__i" << IndexVariables.size();
1617 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1618 }
1619 VarDecl *IterationVar
1620 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1621 IterationVarName, SizeType,
1622 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001623 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001624 IndexVariables.push_back(IterationVar);
1625
1626 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001627 ExprResult IterationVarRef
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001628 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1629 assert(!IterationVarRef.isInvalid() &&
1630 "Reference to invented variable cannot fail!");
1631
1632 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001633 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001634 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001635 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001636 Loc);
1637 if (CopyCtorArg.isInvalid())
1638 return true;
1639
1640 BaseType = Array->getElementType();
1641 }
1642
1643 // Construct the entity that we will be initializing. For an array, this
1644 // will be first element in the array, which may require several levels
1645 // of array-subscript entities.
1646 llvm::SmallVector<InitializedEntity, 4> Entities;
1647 Entities.reserve(1 + IndexVariables.size());
1648 Entities.push_back(InitializedEntity::InitializeMember(Field));
1649 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1650 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1651 0,
1652 Entities.back()));
1653
1654 // Direct-initialize to use the copy constructor.
1655 InitializationKind InitKind =
1656 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1657
1658 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1659 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1660 &CopyCtorArgE, 1);
1661
John McCall60d7b3a2010-08-24 06:29:42 +00001662 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001663 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001664 MultiExprArg(&CopyCtorArgE, 1));
John McCall9ae2f072010-08-23 23:25:46 +00001665 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001666 if (MemberInit.isInvalid())
1667 return true;
1668
1669 CXXMemberInit
1670 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1671 MemberInit.takeAs<Expr>(), Loc,
1672 IndexVariables.data(),
1673 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001674 return false;
1675 }
1676
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001677 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1678
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001679 QualType FieldBaseElementType =
1680 SemaRef.Context.getBaseElementType(Field->getType());
1681
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001682 if (FieldBaseElementType->isRecordType()) {
1683 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001684 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001685 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001686
1687 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001688 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001689 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001690 if (MemberInit.isInvalid())
1691 return true;
1692
1693 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001694 if (MemberInit.isInvalid())
1695 return true;
1696
1697 CXXMemberInit =
1698 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001699 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001700 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001701 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001702 return false;
1703 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001704
1705 if (FieldBaseElementType->isReferenceType()) {
1706 SemaRef.Diag(Constructor->getLocation(),
1707 diag::err_uninitialized_member_in_ctor)
1708 << (int)Constructor->isImplicit()
1709 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1710 << 0 << Field->getDeclName();
1711 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1712 return true;
1713 }
1714
1715 if (FieldBaseElementType.isConstQualified()) {
1716 SemaRef.Diag(Constructor->getLocation(),
1717 diag::err_uninitialized_member_in_ctor)
1718 << (int)Constructor->isImplicit()
1719 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1720 << 1 << Field->getDeclName();
1721 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1722 return true;
1723 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001724
1725 // Nothing to initialize.
1726 CXXMemberInit = 0;
1727 return false;
1728}
John McCallf1860e52010-05-20 23:23:51 +00001729
1730namespace {
1731struct BaseAndFieldInfo {
1732 Sema &S;
1733 CXXConstructorDecl *Ctor;
1734 bool AnyErrorsInInits;
1735 ImplicitInitializerKind IIK;
1736 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1737 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1738
1739 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1740 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1741 // FIXME: Handle implicit move constructors.
1742 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1743 IIK = IIK_Copy;
1744 else
1745 IIK = IIK_Default;
1746 }
1747};
1748}
1749
Chandler Carruthe861c602010-06-30 02:59:29 +00001750static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1751 FieldDecl *Top, FieldDecl *Field,
1752 CXXBaseOrMemberInitializer *Init) {
1753 // If the member doesn't need to be initialized, Init will still be null.
1754 if (!Init)
1755 return;
1756
1757 Info.AllToInit.push_back(Init);
1758 if (Field != Top) {
1759 Init->setMember(Top);
1760 Init->setAnonUnionMember(Field);
1761 }
1762}
1763
John McCallf1860e52010-05-20 23:23:51 +00001764static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1765 FieldDecl *Top, FieldDecl *Field) {
1766
Chandler Carruthe861c602010-06-30 02:59:29 +00001767 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001768 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruthe861c602010-06-30 02:59:29 +00001769 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001770 return false;
1771 }
1772
1773 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1774 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1775 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001776 CXXRecordDecl *FieldClassDecl
1777 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001778
1779 // Even though union members never have non-trivial default
1780 // constructions in C++03, we still build member initializers for aggregate
1781 // record types which can be union members, and C++0x allows non-trivial
1782 // default constructors for union members, so we ensure that only one
1783 // member is initialized for these.
1784 if (FieldClassDecl->isUnion()) {
1785 // First check for an explicit initializer for one field.
1786 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1787 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1788 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1789 RecordFieldInitializer(Info, Top, *FA, Init);
1790
1791 // Once we've initialized a field of an anonymous union, the union
1792 // field in the class is also initialized, so exit immediately.
1793 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001794 } else if ((*FA)->isAnonymousStructOrUnion()) {
1795 if (CollectFieldInitializer(Info, Top, *FA))
1796 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001797 }
1798 }
1799
1800 // Fallthrough and construct a default initializer for the union as
1801 // a whole, which can call its default constructor if such a thing exists
1802 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1803 // behavior going forward with C++0x, when anonymous unions there are
1804 // finalized, we should revisit this.
1805 } else {
1806 // For structs, we simply descend through to initialize all members where
1807 // necessary.
1808 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1809 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1810 if (CollectFieldInitializer(Info, Top, *FA))
1811 return true;
1812 }
1813 }
John McCallf1860e52010-05-20 23:23:51 +00001814 }
1815
1816 // Don't try to build an implicit initializer if there were semantic
1817 // errors in any of the initializers (and therefore we might be
1818 // missing some that the user actually wrote).
1819 if (Info.AnyErrorsInInits)
1820 return false;
1821
1822 CXXBaseOrMemberInitializer *Init = 0;
1823 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1824 return true;
John McCallf1860e52010-05-20 23:23:51 +00001825
Chandler Carruthe861c602010-06-30 02:59:29 +00001826 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001827 return false;
1828}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001829
Eli Friedman80c30da2009-11-09 19:20:36 +00001830bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001831Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001832 CXXBaseOrMemberInitializer **Initializers,
1833 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001834 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001835 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001836 // Just store the initializers as written, they will be checked during
1837 // instantiation.
1838 if (NumInitializers > 0) {
1839 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1840 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1841 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1842 memcpy(baseOrMemberInitializers, Initializers,
1843 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1844 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1845 }
1846
1847 return false;
1848 }
1849
John McCallf1860e52010-05-20 23:23:51 +00001850 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001851
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001852 // We need to build the initializer AST according to order of construction
1853 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001854 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001855 if (!ClassDecl)
1856 return true;
1857
Eli Friedman80c30da2009-11-09 19:20:36 +00001858 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001860 for (unsigned i = 0; i < NumInitializers; i++) {
1861 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001862
1863 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001864 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001865 else
John McCallf1860e52010-05-20 23:23:51 +00001866 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001867 }
1868
Anders Carlsson711f34a2010-04-21 19:52:01 +00001869 // Keep track of the direct virtual bases.
1870 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1871 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1872 E = ClassDecl->bases_end(); I != E; ++I) {
1873 if (I->isVirtual())
1874 DirectVBases.insert(I);
1875 }
1876
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001877 // Push virtual bases before others.
1878 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1879 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1880
1881 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001882 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1883 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001884 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001885 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001886 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001887 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001888 VBase, IsInheritedVirtualBase,
1889 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001890 HadError = true;
1891 continue;
1892 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001893
John McCallf1860e52010-05-20 23:23:51 +00001894 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001895 }
1896 }
Mike Stump1eb44332009-09-09 15:08:12 +00001897
John McCallf1860e52010-05-20 23:23:51 +00001898 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001899 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1900 E = ClassDecl->bases_end(); Base != E; ++Base) {
1901 // Virtuals are in the virtual base list and already constructed.
1902 if (Base->isVirtual())
1903 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001905 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001906 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1907 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001908 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001909 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001910 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001911 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001912 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001913 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001914 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001915 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001916
John McCallf1860e52010-05-20 23:23:51 +00001917 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001918 }
1919 }
Mike Stump1eb44332009-09-09 15:08:12 +00001920
John McCallf1860e52010-05-20 23:23:51 +00001921 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001922 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001923 E = ClassDecl->field_end(); Field != E; ++Field) {
1924 if ((*Field)->getType()->isIncompleteArrayType()) {
1925 assert(ClassDecl->hasFlexibleArrayMember() &&
1926 "Incomplete array type is not valid");
1927 continue;
1928 }
John McCallf1860e52010-05-20 23:23:51 +00001929 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001930 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001931 }
Mike Stump1eb44332009-09-09 15:08:12 +00001932
John McCallf1860e52010-05-20 23:23:51 +00001933 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001934 if (NumInitializers > 0) {
1935 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1936 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1937 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001938 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001939 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001940 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001941
John McCallef027fe2010-03-16 21:39:52 +00001942 // Constructors implicitly reference the base and member
1943 // destructors.
1944 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1945 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001946 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001947
1948 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001949}
1950
Eli Friedman6347f422009-07-21 19:28:10 +00001951static void *GetKeyForTopLevelField(FieldDecl *Field) {
1952 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001953 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001954 if (RT->getDecl()->isAnonymousStructOrUnion())
1955 return static_cast<void *>(RT->getDecl());
1956 }
1957 return static_cast<void *>(Field);
1958}
1959
Anders Carlssonea356fb2010-04-02 05:42:15 +00001960static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1961 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001962}
1963
Anders Carlssonea356fb2010-04-02 05:42:15 +00001964static void *GetKeyForMember(ASTContext &Context,
1965 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001966 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001967 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001968 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001969
Eli Friedman6347f422009-07-21 19:28:10 +00001970 // For fields injected into the class via declaration of an anonymous union,
1971 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001972 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001974 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1975 // data member of the class. Data member used in the initializer list is
1976 // in AnonUnionMember field.
1977 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1978 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001979
John McCall3c3ccdb2010-04-10 09:28:51 +00001980 // If the field is a member of an anonymous struct or union, our key
1981 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001982 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001983 if (RD->isAnonymousStructOrUnion()) {
1984 while (true) {
1985 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1986 if (Parent->isAnonymousStructOrUnion())
1987 RD = Parent;
1988 else
1989 break;
1990 }
1991
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001992 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001993 }
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001995 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001996}
1997
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001998static void
1999DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002000 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00002001 CXXBaseOrMemberInitializer **Inits,
2002 unsigned NumInits) {
2003 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002004 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
John McCalld6ca8da2010-04-10 07:37:23 +00002006 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2007 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002008 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002009
John McCalld6ca8da2010-04-10 07:37:23 +00002010 // Build the list of bases and members in the order that they'll
2011 // actually be initialized. The explicit initializers should be in
2012 // this same order but may be missing things.
2013 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Anders Carlsson071d6102010-04-02 03:38:04 +00002015 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2016
John McCalld6ca8da2010-04-10 07:37:23 +00002017 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002018 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002019 ClassDecl->vbases_begin(),
2020 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002021 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002022
John McCalld6ca8da2010-04-10 07:37:23 +00002023 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002024 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002025 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002026 if (Base->isVirtual())
2027 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002028 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCalld6ca8da2010-04-10 07:37:23 +00002031 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002032 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2033 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002034 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002035
John McCalld6ca8da2010-04-10 07:37:23 +00002036 unsigned NumIdealInits = IdealInitKeys.size();
2037 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002038
John McCalld6ca8da2010-04-10 07:37:23 +00002039 CXXBaseOrMemberInitializer *PrevInit = 0;
2040 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2041 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2042 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2043
2044 // Scan forward to try to find this initializer in the idealized
2045 // initializers list.
2046 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2047 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002048 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002049
2050 // If we didn't find this initializer, it must be because we
2051 // scanned past it on a previous iteration. That can only
2052 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002053 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002054 Sema::SemaDiagnosticBuilder D =
2055 SemaRef.Diag(PrevInit->getSourceLocation(),
2056 diag::warn_initializer_out_of_order);
2057
2058 if (PrevInit->isMemberInitializer())
2059 D << 0 << PrevInit->getMember()->getDeclName();
2060 else
2061 D << 1 << PrevInit->getBaseClassInfo()->getType();
2062
2063 if (Init->isMemberInitializer())
2064 D << 0 << Init->getMember()->getDeclName();
2065 else
2066 D << 1 << Init->getBaseClassInfo()->getType();
2067
2068 // Move back to the initializer's location in the ideal list.
2069 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2070 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002071 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002072
2073 assert(IdealIndex != NumIdealInits &&
2074 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002075 }
John McCalld6ca8da2010-04-10 07:37:23 +00002076
2077 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002078 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002079}
2080
John McCall3c3ccdb2010-04-10 09:28:51 +00002081namespace {
2082bool CheckRedundantInit(Sema &S,
2083 CXXBaseOrMemberInitializer *Init,
2084 CXXBaseOrMemberInitializer *&PrevInit) {
2085 if (!PrevInit) {
2086 PrevInit = Init;
2087 return false;
2088 }
2089
2090 if (FieldDecl *Field = Init->getMember())
2091 S.Diag(Init->getSourceLocation(),
2092 diag::err_multiple_mem_initialization)
2093 << Field->getDeclName()
2094 << Init->getSourceRange();
2095 else {
2096 Type *BaseClass = Init->getBaseClass();
2097 assert(BaseClass && "neither field nor base");
2098 S.Diag(Init->getSourceLocation(),
2099 diag::err_multiple_base_initialization)
2100 << QualType(BaseClass, 0)
2101 << Init->getSourceRange();
2102 }
2103 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2104 << 0 << PrevInit->getSourceRange();
2105
2106 return true;
2107}
2108
2109typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2110typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2111
2112bool CheckRedundantUnionInit(Sema &S,
2113 CXXBaseOrMemberInitializer *Init,
2114 RedundantUnionMap &Unions) {
2115 FieldDecl *Field = Init->getMember();
2116 RecordDecl *Parent = Field->getParent();
2117 if (!Parent->isAnonymousStructOrUnion())
2118 return false;
2119
2120 NamedDecl *Child = Field;
2121 do {
2122 if (Parent->isUnion()) {
2123 UnionEntry &En = Unions[Parent];
2124 if (En.first && En.first != Child) {
2125 S.Diag(Init->getSourceLocation(),
2126 diag::err_multiple_mem_union_initialization)
2127 << Field->getDeclName()
2128 << Init->getSourceRange();
2129 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2130 << 0 << En.second->getSourceRange();
2131 return true;
2132 } else if (!En.first) {
2133 En.first = Child;
2134 En.second = Init;
2135 }
2136 }
2137
2138 Child = Parent;
2139 Parent = cast<RecordDecl>(Parent->getDeclContext());
2140 } while (Parent->isAnonymousStructOrUnion());
2141
2142 return false;
2143}
2144}
2145
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002146/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002147void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002148 SourceLocation ColonLoc,
2149 MemInitTy **meminits, unsigned NumMemInits,
2150 bool AnyErrors) {
2151 if (!ConstructorDecl)
2152 return;
2153
2154 AdjustDeclIfTemplate(ConstructorDecl);
2155
2156 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002157 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002158
2159 if (!Constructor) {
2160 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2161 return;
2162 }
2163
2164 CXXBaseOrMemberInitializer **MemInits =
2165 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002166
2167 // Mapping for the duplicate initializers check.
2168 // For member initializers, this is keyed with a FieldDecl*.
2169 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002170 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002171
2172 // Mapping for the inconsistent anonymous-union initializers check.
2173 RedundantUnionMap MemberUnions;
2174
Anders Carlssonea356fb2010-04-02 05:42:15 +00002175 bool HadError = false;
2176 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002177 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002178
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002179 // Set the source order index.
2180 Init->setSourceOrder(i);
2181
John McCall3c3ccdb2010-04-10 09:28:51 +00002182 if (Init->isMemberInitializer()) {
2183 FieldDecl *Field = Init->getMember();
2184 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2185 CheckRedundantUnionInit(*this, Init, MemberUnions))
2186 HadError = true;
2187 } else {
2188 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2189 if (CheckRedundantInit(*this, Init, Members[Key]))
2190 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002191 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002192 }
2193
Anders Carlssonea356fb2010-04-02 05:42:15 +00002194 if (HadError)
2195 return;
2196
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002197 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002198
2199 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002200}
2201
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002202void
John McCallef027fe2010-03-16 21:39:52 +00002203Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2204 CXXRecordDecl *ClassDecl) {
2205 // Ignore dependent contexts.
2206 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002207 return;
John McCall58e6f342010-03-16 05:22:47 +00002208
2209 // FIXME: all the access-control diagnostics are positioned on the
2210 // field/base declaration. That's probably good; that said, the
2211 // user might reasonably want to know why the destructor is being
2212 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002213
Anders Carlsson9f853df2009-11-17 04:44:12 +00002214 // Non-static data members.
2215 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2216 E = ClassDecl->field_end(); I != E; ++I) {
2217 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002218 if (Field->isInvalidDecl())
2219 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002220 QualType FieldType = Context.getBaseElementType(Field->getType());
2221
2222 const RecordType* RT = FieldType->getAs<RecordType>();
2223 if (!RT)
2224 continue;
2225
2226 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2227 if (FieldClassDecl->hasTrivialDestructor())
2228 continue;
2229
Douglas Gregordb89f282010-07-01 22:47:18 +00002230 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002231 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002232 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002233 << Field->getDeclName()
2234 << FieldType);
2235
John McCallef027fe2010-03-16 21:39:52 +00002236 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002237 }
2238
John McCall58e6f342010-03-16 05:22:47 +00002239 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2240
Anders Carlsson9f853df2009-11-17 04:44:12 +00002241 // Bases.
2242 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2243 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002244 // Bases are always records in a well-formed non-dependent class.
2245 const RecordType *RT = Base->getType()->getAs<RecordType>();
2246
2247 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002248 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002249 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002250
2251 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002252 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002253 if (BaseClassDecl->hasTrivialDestructor())
2254 continue;
John McCall58e6f342010-03-16 05:22:47 +00002255
Douglas Gregordb89f282010-07-01 22:47:18 +00002256 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002257
2258 // FIXME: caret should be on the start of the class name
2259 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002260 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002261 << Base->getType()
2262 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002263
John McCallef027fe2010-03-16 21:39:52 +00002264 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002265 }
2266
2267 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002268 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2269 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002270
2271 // Bases are always records in a well-formed non-dependent class.
2272 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2273
2274 // Ignore direct virtual bases.
2275 if (DirectVirtualBases.count(RT))
2276 continue;
2277
Anders Carlsson9f853df2009-11-17 04:44:12 +00002278 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002279 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002280 if (BaseClassDecl->hasTrivialDestructor())
2281 continue;
John McCall58e6f342010-03-16 05:22:47 +00002282
Douglas Gregordb89f282010-07-01 22:47:18 +00002283 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002284 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002285 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002286 << VBase->getType());
2287
John McCallef027fe2010-03-16 21:39:52 +00002288 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002289 }
2290}
2291
John McCalld226f652010-08-21 09:40:31 +00002292void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002293 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002294 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Mike Stump1eb44332009-09-09 15:08:12 +00002296 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002297 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002298 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002299}
2300
Mike Stump1eb44332009-09-09 15:08:12 +00002301bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002302 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002303 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002304 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002305 else
John McCall94c3b562010-08-18 09:41:07 +00002306 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002307}
2308
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002309bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002310 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002311 if (!getLangOptions().CPlusPlus)
2312 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Anders Carlsson11f21a02009-03-23 19:10:31 +00002314 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002315 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Ted Kremenek6217b802009-07-29 21:53:49 +00002317 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002318 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002319 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002320 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002322 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002323 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002324 }
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Ted Kremenek6217b802009-07-29 21:53:49 +00002326 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002327 if (!RT)
2328 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002329
John McCall86ff3082010-02-04 22:26:26 +00002330 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002331
John McCall94c3b562010-08-18 09:41:07 +00002332 // We can't answer whether something is abstract until it has a
2333 // definition. If it's currently being defined, we'll walk back
2334 // over all the declarations when we have a full definition.
2335 const CXXRecordDecl *Def = RD->getDefinition();
2336 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002337 return false;
2338
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002339 if (!RD->isAbstract())
2340 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002342 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002343 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002344
John McCall94c3b562010-08-18 09:41:07 +00002345 return true;
2346}
2347
2348void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2349 // Check if we've already emitted the list of pure virtual functions
2350 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002351 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002352 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002354 CXXFinalOverriderMap FinalOverriders;
2355 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002357 // Keep a set of seen pure methods so we won't diagnose the same method
2358 // more than once.
2359 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2360
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002361 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2362 MEnd = FinalOverriders.end();
2363 M != MEnd;
2364 ++M) {
2365 for (OverridingMethods::iterator SO = M->second.begin(),
2366 SOEnd = M->second.end();
2367 SO != SOEnd; ++SO) {
2368 // C++ [class.abstract]p4:
2369 // A class is abstract if it contains or inherits at least one
2370 // pure virtual function for which the final overrider is pure
2371 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002373 //
2374 if (SO->second.size() != 1)
2375 continue;
2376
2377 if (!SO->second.front().Method->isPure())
2378 continue;
2379
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002380 if (!SeenPureMethods.insert(SO->second.front().Method))
2381 continue;
2382
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002383 Diag(SO->second.front().Method->getLocation(),
2384 diag::note_pure_virtual_function)
2385 << SO->second.front().Method->getDeclName();
2386 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002387 }
2388
2389 if (!PureVirtualClassDiagSet)
2390 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2391 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002392}
2393
Anders Carlsson8211eff2009-03-24 01:19:16 +00002394namespace {
John McCall94c3b562010-08-18 09:41:07 +00002395struct AbstractUsageInfo {
2396 Sema &S;
2397 CXXRecordDecl *Record;
2398 CanQualType AbstractType;
2399 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002400
John McCall94c3b562010-08-18 09:41:07 +00002401 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2402 : S(S), Record(Record),
2403 AbstractType(S.Context.getCanonicalType(
2404 S.Context.getTypeDeclType(Record))),
2405 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002406
John McCall94c3b562010-08-18 09:41:07 +00002407 void DiagnoseAbstractType() {
2408 if (Invalid) return;
2409 S.DiagnoseAbstractType(Record);
2410 Invalid = true;
2411 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002412
John McCall94c3b562010-08-18 09:41:07 +00002413 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2414};
2415
2416struct CheckAbstractUsage {
2417 AbstractUsageInfo &Info;
2418 const NamedDecl *Ctx;
2419
2420 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2421 : Info(Info), Ctx(Ctx) {}
2422
2423 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2424 switch (TL.getTypeLocClass()) {
2425#define ABSTRACT_TYPELOC(CLASS, PARENT)
2426#define TYPELOC(CLASS, PARENT) \
2427 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2428#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002429 }
John McCall94c3b562010-08-18 09:41:07 +00002430 }
Mike Stump1eb44332009-09-09 15:08:12 +00002431
John McCall94c3b562010-08-18 09:41:07 +00002432 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2433 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2434 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2435 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2436 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002437 }
John McCall94c3b562010-08-18 09:41:07 +00002438 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002439
John McCall94c3b562010-08-18 09:41:07 +00002440 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2441 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
John McCall94c3b562010-08-18 09:41:07 +00002444 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2445 // Visit the type parameters from a permissive context.
2446 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2447 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2448 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2449 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2450 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2451 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002452 }
John McCall94c3b562010-08-18 09:41:07 +00002453 }
Mike Stump1eb44332009-09-09 15:08:12 +00002454
John McCall94c3b562010-08-18 09:41:07 +00002455 // Visit pointee types from a permissive context.
2456#define CheckPolymorphic(Type) \
2457 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2458 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2459 }
2460 CheckPolymorphic(PointerTypeLoc)
2461 CheckPolymorphic(ReferenceTypeLoc)
2462 CheckPolymorphic(MemberPointerTypeLoc)
2463 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002464
John McCall94c3b562010-08-18 09:41:07 +00002465 /// Handle all the types we haven't given a more specific
2466 /// implementation for above.
2467 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2468 // Every other kind of type that we haven't called out already
2469 // that has an inner type is either (1) sugar or (2) contains that
2470 // inner type in some way as a subobject.
2471 if (TypeLoc Next = TL.getNextTypeLoc())
2472 return Visit(Next, Sel);
2473
2474 // If there's no inner type and we're in a permissive context,
2475 // don't diagnose.
2476 if (Sel == Sema::AbstractNone) return;
2477
2478 // Check whether the type matches the abstract type.
2479 QualType T = TL.getType();
2480 if (T->isArrayType()) {
2481 Sel = Sema::AbstractArrayType;
2482 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002483 }
John McCall94c3b562010-08-18 09:41:07 +00002484 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2485 if (CT != Info.AbstractType) return;
2486
2487 // It matched; do some magic.
2488 if (Sel == Sema::AbstractArrayType) {
2489 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2490 << T << TL.getSourceRange();
2491 } else {
2492 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2493 << Sel << T << TL.getSourceRange();
2494 }
2495 Info.DiagnoseAbstractType();
2496 }
2497};
2498
2499void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2500 Sema::AbstractDiagSelID Sel) {
2501 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2502}
2503
2504}
2505
2506/// Check for invalid uses of an abstract type in a method declaration.
2507static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2508 CXXMethodDecl *MD) {
2509 // No need to do the check on definitions, which require that
2510 // the return/param types be complete.
2511 if (MD->isThisDeclarationADefinition())
2512 return;
2513
2514 // For safety's sake, just ignore it if we don't have type source
2515 // information. This should never happen for non-implicit methods,
2516 // but...
2517 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2518 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2519}
2520
2521/// Check for invalid uses of an abstract type within a class definition.
2522static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2523 CXXRecordDecl *RD) {
2524 for (CXXRecordDecl::decl_iterator
2525 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2526 Decl *D = *I;
2527 if (D->isImplicit()) continue;
2528
2529 // Methods and method templates.
2530 if (isa<CXXMethodDecl>(D)) {
2531 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2532 } else if (isa<FunctionTemplateDecl>(D)) {
2533 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2534 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2535
2536 // Fields and static variables.
2537 } else if (isa<FieldDecl>(D)) {
2538 FieldDecl *FD = cast<FieldDecl>(D);
2539 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2540 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2541 } else if (isa<VarDecl>(D)) {
2542 VarDecl *VD = cast<VarDecl>(D);
2543 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2544 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2545
2546 // Nested classes and class templates.
2547 } else if (isa<CXXRecordDecl>(D)) {
2548 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2549 } else if (isa<ClassTemplateDecl>(D)) {
2550 CheckAbstractClassUsage(Info,
2551 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2552 }
2553 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002554}
2555
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002556/// \brief Perform semantic checks on a class definition that has been
2557/// completing, introducing implicitly-declared members, checking for
2558/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002559void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002560 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002561 return;
2562
John McCall94c3b562010-08-18 09:41:07 +00002563 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2564 AbstractUsageInfo Info(*this, Record);
2565 CheckAbstractClassUsage(Info, Record);
2566 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002567
2568 // If this is not an aggregate type and has no user-declared constructor,
2569 // complain about any non-static data members of reference or const scalar
2570 // type, since they will never get initializers.
2571 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2572 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2573 bool Complained = false;
2574 for (RecordDecl::field_iterator F = Record->field_begin(),
2575 FEnd = Record->field_end();
2576 F != FEnd; ++F) {
2577 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002578 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002579 if (!Complained) {
2580 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2581 << Record->getTagKind() << Record;
2582 Complained = true;
2583 }
2584
2585 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2586 << F->getType()->isReferenceType()
2587 << F->getDeclName();
2588 }
2589 }
2590 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002591
2592 if (Record->isDynamicClass())
2593 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002594
2595 if (Record->getIdentifier()) {
2596 // C++ [class.mem]p13:
2597 // If T is the name of a class, then each of the following shall have a
2598 // name different from T:
2599 // - every member of every anonymous union that is a member of class T.
2600 //
2601 // C++ [class.mem]p14:
2602 // In addition, if class T has a user-declared constructor (12.1), every
2603 // non-static data member of class T shall have a name different from T.
2604 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
2605 R.first != R.second; ++R.first)
2606 if (FieldDecl *Field = dyn_cast<FieldDecl>(*R.first)) {
2607 if (Record->hasUserDeclaredConstructor() ||
2608 !Field->getDeclContext()->Equals(Record)) {
2609 Diag(Field->getLocation(), diag::err_member_name_of_class)
2610 << Field->getDeclName();
2611 break;
2612 }
2613 }
2614 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002615}
2616
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002617void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002618 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002619 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002620 SourceLocation RBrac,
2621 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002622 if (!TagDecl)
2623 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor42af25f2009-05-11 19:58:34 +00002625 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002626
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002627 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002628 // strict aliasing violation!
2629 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002630 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002631
Douglas Gregor23c94db2010-07-02 17:43:08 +00002632 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002633 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002634}
2635
Douglas Gregord92ec472010-07-01 05:10:53 +00002636namespace {
2637 /// \brief Helper class that collects exception specifications for
2638 /// implicitly-declared special member functions.
2639 class ImplicitExceptionSpecification {
2640 ASTContext &Context;
2641 bool AllowsAllExceptions;
2642 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2643 llvm::SmallVector<QualType, 4> Exceptions;
2644
2645 public:
2646 explicit ImplicitExceptionSpecification(ASTContext &Context)
2647 : Context(Context), AllowsAllExceptions(false) { }
2648
2649 /// \brief Whether the special member function should have any
2650 /// exception specification at all.
2651 bool hasExceptionSpecification() const {
2652 return !AllowsAllExceptions;
2653 }
2654
2655 /// \brief Whether the special member function should have a
2656 /// throw(...) exception specification (a Microsoft extension).
2657 bool hasAnyExceptionSpecification() const {
2658 return false;
2659 }
2660
2661 /// \brief The number of exceptions in the exception specification.
2662 unsigned size() const { return Exceptions.size(); }
2663
2664 /// \brief The set of exceptions in the exception specification.
2665 const QualType *data() const { return Exceptions.data(); }
2666
2667 /// \brief Note that
2668 void CalledDecl(CXXMethodDecl *Method) {
2669 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002670 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002671 return;
2672
2673 const FunctionProtoType *Proto
2674 = Method->getType()->getAs<FunctionProtoType>();
2675
2676 // If this function can throw any exceptions, make a note of that.
2677 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2678 AllowsAllExceptions = true;
2679 ExceptionsSeen.clear();
2680 Exceptions.clear();
2681 return;
2682 }
2683
2684 // Record the exceptions in this function's exception specification.
2685 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2686 EEnd = Proto->exception_end();
2687 E != EEnd; ++E)
2688 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2689 Exceptions.push_back(*E);
2690 }
2691 };
2692}
2693
2694
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002695/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2696/// special functions, such as the default constructor, copy
2697/// constructor, or destructor, to the given C++ class (C++
2698/// [special]p1). This routine can only be executed just before the
2699/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002700void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002701 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002702 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002703
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002704 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002705 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002706
Douglas Gregora376d102010-07-02 21:50:04 +00002707 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2708 ++ASTContext::NumImplicitCopyAssignmentOperators;
2709
2710 // If we have a dynamic class, then the copy assignment operator may be
2711 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2712 // it shows up in the right place in the vtable and that we diagnose
2713 // problems with the implicit exception specification.
2714 if (ClassDecl->isDynamicClass())
2715 DeclareImplicitCopyAssignment(ClassDecl);
2716 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002717
Douglas Gregor4923aa22010-07-02 20:37:36 +00002718 if (!ClassDecl->hasUserDeclaredDestructor()) {
2719 ++ASTContext::NumImplicitDestructors;
2720
2721 // If we have a dynamic class, then the destructor may be virtual, so we
2722 // have to declare the destructor immediately. This ensures that, e.g., it
2723 // shows up in the right place in the vtable and that we diagnose problems
2724 // with the implicit exception specification.
2725 if (ClassDecl->isDynamicClass())
2726 DeclareImplicitDestructor(ClassDecl);
2727 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002728}
2729
John McCalld226f652010-08-21 09:40:31 +00002730void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002731 if (!D)
2732 return;
2733
2734 TemplateParameterList *Params = 0;
2735 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2736 Params = Template->getTemplateParameters();
2737 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2738 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2739 Params = PartialSpec->getTemplateParameters();
2740 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002741 return;
2742
Douglas Gregor6569d682009-05-27 23:11:45 +00002743 for (TemplateParameterList::iterator Param = Params->begin(),
2744 ParamEnd = Params->end();
2745 Param != ParamEnd; ++Param) {
2746 NamedDecl *Named = cast<NamedDecl>(*Param);
2747 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002748 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002749 IdResolver.AddDecl(Named);
2750 }
2751 }
2752}
2753
John McCalld226f652010-08-21 09:40:31 +00002754void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002755 if (!RecordD) return;
2756 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002757 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002758 PushDeclContext(S, Record);
2759}
2760
John McCalld226f652010-08-21 09:40:31 +00002761void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002762 if (!RecordD) return;
2763 PopDeclContext();
2764}
2765
Douglas Gregor72b505b2008-12-16 21:30:33 +00002766/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2767/// parsing a top-level (non-nested) C++ class, and we are now
2768/// parsing those parts of the given Method declaration that could
2769/// not be parsed earlier (C++ [class.mem]p2), such as default
2770/// arguments. This action should enter the scope of the given
2771/// Method declaration as if we had just parsed the qualified method
2772/// name. However, it should not bring the parameters into scope;
2773/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002774void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002775}
2776
2777/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2778/// C++ method declaration. We're (re-)introducing the given
2779/// function parameter into scope for use in parsing later parts of
2780/// the method declaration. For example, we could see an
2781/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002782void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002783 if (!ParamD)
2784 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002785
John McCalld226f652010-08-21 09:40:31 +00002786 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002787
2788 // If this parameter has an unparsed default argument, clear it out
2789 // to make way for the parsed default argument.
2790 if (Param->hasUnparsedDefaultArg())
2791 Param->setDefaultArg(0);
2792
John McCalld226f652010-08-21 09:40:31 +00002793 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002794 if (Param->getDeclName())
2795 IdResolver.AddDecl(Param);
2796}
2797
2798/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2799/// processing the delayed method declaration for Method. The method
2800/// declaration is now considered finished. There may be a separate
2801/// ActOnStartOfFunctionDef action later (not necessarily
2802/// immediately!) for this method, if it was also defined inside the
2803/// class body.
John McCalld226f652010-08-21 09:40:31 +00002804void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002805 if (!MethodD)
2806 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002808 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002809
John McCalld226f652010-08-21 09:40:31 +00002810 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002811
2812 // Now that we have our default arguments, check the constructor
2813 // again. It could produce additional diagnostics or affect whether
2814 // the class has implicitly-declared destructors, among other
2815 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002816 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2817 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002818
2819 // Check the default arguments, which we may have added.
2820 if (!Method->isInvalidDecl())
2821 CheckCXXDefaultArguments(Method);
2822}
2823
Douglas Gregor42a552f2008-11-05 20:51:48 +00002824/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002825/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002826/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002827/// emit diagnostics and set the invalid bit to true. In any case, the type
2828/// will be updated to reflect a well-formed type for the constructor and
2829/// returned.
2830QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002831 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002832 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002833
2834 // C++ [class.ctor]p3:
2835 // A constructor shall not be virtual (10.3) or static (9.4). A
2836 // constructor can be invoked for a const, volatile or const
2837 // volatile object. A constructor shall not be declared const,
2838 // volatile, or const volatile (9.3.2).
2839 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002840 if (!D.isInvalidType())
2841 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2842 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2843 << SourceRange(D.getIdentifierLoc());
2844 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002845 }
John McCalld931b082010-08-26 03:08:43 +00002846 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002847 if (!D.isInvalidType())
2848 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2849 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2850 << SourceRange(D.getIdentifierLoc());
2851 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002852 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002853 }
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Chris Lattner65401802009-04-25 08:28:21 +00002855 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2856 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002857 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002858 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2859 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002860 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002861 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2862 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002863 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002864 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2865 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002866 }
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Douglas Gregor42a552f2008-11-05 20:51:48 +00002868 // Rebuild the function type "R" without any type qualifiers (in
2869 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002870 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002871 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002872 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2873 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002874 Proto->isVariadic(), 0,
2875 Proto->hasExceptionSpec(),
2876 Proto->hasAnyExceptionSpec(),
2877 Proto->getNumExceptions(),
2878 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002879 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002880}
2881
Douglas Gregor72b505b2008-12-16 21:30:33 +00002882/// CheckConstructor - Checks a fully-formed constructor for
2883/// well-formedness, issuing any diagnostics required. Returns true if
2884/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002885void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002886 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002887 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2888 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002889 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002890
2891 // C++ [class.copy]p3:
2892 // A declaration of a constructor for a class X is ill-formed if
2893 // its first parameter is of type (optionally cv-qualified) X and
2894 // either there are no other parameters or else all other
2895 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002896 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002897 ((Constructor->getNumParams() == 1) ||
2898 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002899 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2900 Constructor->getTemplateSpecializationKind()
2901 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002902 QualType ParamType = Constructor->getParamDecl(0)->getType();
2903 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2904 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002905 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002906 const char *ConstRef
2907 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2908 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002909 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002910 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002911
2912 // FIXME: Rather that making the constructor invalid, we should endeavor
2913 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002914 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002915 }
2916 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002917}
2918
John McCall15442822010-08-04 01:04:25 +00002919/// CheckDestructor - Checks a fully-formed destructor definition for
2920/// well-formedness, issuing any diagnostics required. Returns true
2921/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002922bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002923 CXXRecordDecl *RD = Destructor->getParent();
2924
2925 if (Destructor->isVirtual()) {
2926 SourceLocation Loc;
2927
2928 if (!Destructor->isImplicit())
2929 Loc = Destructor->getLocation();
2930 else
2931 Loc = RD->getLocation();
2932
2933 // If we have a virtual destructor, look up the deallocation function
2934 FunctionDecl *OperatorDelete = 0;
2935 DeclarationName Name =
2936 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002937 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002938 return true;
John McCall5efd91a2010-07-03 18:33:00 +00002939
2940 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00002941
2942 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002943 }
Anders Carlsson37909802009-11-30 21:24:50 +00002944
2945 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002946}
2947
Mike Stump1eb44332009-09-09 15:08:12 +00002948static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002949FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2950 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2951 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00002952 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002953}
2954
Douglas Gregor42a552f2008-11-05 20:51:48 +00002955/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2956/// the well-formednes of the destructor declarator @p D with type @p
2957/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002958/// emit diagnostics and set the declarator to invalid. Even if this happens,
2959/// will be updated to reflect a well-formed type for the destructor and
2960/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00002961QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002962 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002963 // C++ [class.dtor]p1:
2964 // [...] A typedef-name that names a class is a class-name
2965 // (7.1.3); however, a typedef-name that names a class shall not
2966 // be used as the identifier in the declarator for a destructor
2967 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002968 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00002969 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00002970 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002971 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002972
2973 // C++ [class.dtor]p2:
2974 // A destructor is used to destroy objects of its class type. A
2975 // destructor takes no parameters, and no return type can be
2976 // specified for it (not even void). The address of a destructor
2977 // shall not be taken. A destructor shall not be static. A
2978 // destructor can be invoked for a const, volatile or const
2979 // volatile object. A destructor shall not be declared const,
2980 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00002981 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002982 if (!D.isInvalidType())
2983 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2984 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00002985 << SourceRange(D.getIdentifierLoc())
2986 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2987
John McCalld931b082010-08-26 03:08:43 +00002988 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002989 }
Chris Lattner65401802009-04-25 08:28:21 +00002990 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002991 // Destructors don't have return types, but the parser will
2992 // happily parse something like:
2993 //
2994 // class X {
2995 // float ~X();
2996 // };
2997 //
2998 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002999 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3000 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3001 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003002 }
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Chris Lattner65401802009-04-25 08:28:21 +00003004 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3005 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003006 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003007 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3008 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003009 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003010 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3011 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003012 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003013 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3014 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003015 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003016 }
3017
3018 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003019 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003020 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3021
3022 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003023 FTI.freeArgs();
3024 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003025 }
3026
Mike Stump1eb44332009-09-09 15:08:12 +00003027 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003028 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003029 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003030 D.setInvalidType();
3031 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003032
3033 // Rebuild the function type "R" without any type qualifiers or
3034 // parameters (in case any of the errors above fired) and with
3035 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003036 // types.
3037 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3038 if (!Proto)
3039 return QualType();
3040
Douglas Gregorce056bc2010-02-21 22:15:06 +00003041 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003042 Proto->hasExceptionSpec(),
3043 Proto->hasAnyExceptionSpec(),
3044 Proto->getNumExceptions(),
3045 Proto->exception_begin(),
3046 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003047}
3048
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003049/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3050/// well-formednes of the conversion function declarator @p D with
3051/// type @p R. If there are any errors in the declarator, this routine
3052/// will emit diagnostics and return true. Otherwise, it will return
3053/// false. Either way, the type @p R will be updated to reflect a
3054/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003055void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003056 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003057 // C++ [class.conv.fct]p1:
3058 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003059 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003060 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003061 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003062 if (!D.isInvalidType())
3063 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3064 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3065 << SourceRange(D.getIdentifierLoc());
3066 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003067 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003068 }
John McCalla3f81372010-04-13 00:04:31 +00003069
3070 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3071
Chris Lattner6e475012009-04-25 08:35:12 +00003072 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003073 // Conversion functions don't have return types, but the parser will
3074 // happily parse something like:
3075 //
3076 // class X {
3077 // float operator bool();
3078 // };
3079 //
3080 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003081 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3082 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3083 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003084 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003085 }
3086
John McCalla3f81372010-04-13 00:04:31 +00003087 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3088
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003089 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003090 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003091 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3092
3093 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003094 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003095 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003096 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003097 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003098 D.setInvalidType();
3099 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003100
John McCalla3f81372010-04-13 00:04:31 +00003101 // Diagnose "&operator bool()" and other such nonsense. This
3102 // is actually a gcc extension which we don't support.
3103 if (Proto->getResultType() != ConvType) {
3104 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3105 << Proto->getResultType();
3106 D.setInvalidType();
3107 ConvType = Proto->getResultType();
3108 }
3109
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003110 // C++ [class.conv.fct]p4:
3111 // The conversion-type-id shall not represent a function type nor
3112 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003113 if (ConvType->isArrayType()) {
3114 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3115 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003116 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003117 } else if (ConvType->isFunctionType()) {
3118 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3119 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003120 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003121 }
3122
3123 // Rebuild the function type "R" without any parameters (in case any
3124 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003125 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003126 if (D.isInvalidType()) {
3127 R = Context.getFunctionType(ConvType, 0, 0, false,
3128 Proto->getTypeQuals(),
3129 Proto->hasExceptionSpec(),
3130 Proto->hasAnyExceptionSpec(),
3131 Proto->getNumExceptions(),
3132 Proto->exception_begin(),
3133 Proto->getExtInfo());
3134 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003135
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003136 // C++0x explicit conversion operators.
3137 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003138 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003139 diag::warn_explicit_conversion_functions)
3140 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003141}
3142
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003143/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3144/// the declaration of the given C++ conversion function. This routine
3145/// is responsible for recording the conversion function in the C++
3146/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003147Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003148 assert(Conversion && "Expected to receive a conversion function declaration");
3149
Douglas Gregor9d350972008-12-12 08:25:50 +00003150 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003151
3152 // Make sure we aren't redeclaring the conversion function.
3153 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003154
3155 // C++ [class.conv.fct]p1:
3156 // [...] A conversion function is never used to convert a
3157 // (possibly cv-qualified) object to the (possibly cv-qualified)
3158 // same object type (or a reference to it), to a (possibly
3159 // cv-qualified) base class of that type (or a reference to it),
3160 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003161 // FIXME: Suppress this warning if the conversion function ends up being a
3162 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003163 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003164 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003165 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003166 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003167 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3168 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003169 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003170 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003171 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3172 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003173 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003174 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003175 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003176 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003177 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003178 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003179 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003180 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003181 }
3182
Douglas Gregore80622f2010-09-29 04:25:11 +00003183 if (FunctionTemplateDecl *ConversionTemplate
3184 = Conversion->getDescribedFunctionTemplate())
3185 return ConversionTemplate;
3186
John McCalld226f652010-08-21 09:40:31 +00003187 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003188}
3189
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003190//===----------------------------------------------------------------------===//
3191// Namespace Handling
3192//===----------------------------------------------------------------------===//
3193
John McCallea318642010-08-26 09:15:37 +00003194
3195
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003196/// ActOnStartNamespaceDef - This is called at the start of a namespace
3197/// definition.
John McCalld226f652010-08-21 09:40:31 +00003198Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003199 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003200 SourceLocation IdentLoc,
3201 IdentifierInfo *II,
3202 SourceLocation LBrace,
3203 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003204 // anonymous namespace starts at its left brace
3205 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3206 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003207 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003208 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003209
3210 Scope *DeclRegionScope = NamespcScope->getParent();
3211
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003212 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3213
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003214 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallea318642010-08-26 09:15:37 +00003215 PushVisibilityAttr(attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003216
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003217 if (II) {
3218 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003219 // The identifier in an original-namespace-definition shall not
3220 // have been previously defined in the declarative region in
3221 // which the original-namespace-definition appears. The
3222 // identifier in an original-namespace-definition is the name of
3223 // the namespace. Subsequently in that declarative region, it is
3224 // treated as an original-namespace-name.
3225 //
3226 // Since namespace names are unique in their scope, and we don't
3227 // look through using directives, just
3228 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3229 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Douglas Gregor44b43212008-12-11 16:49:14 +00003231 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3232 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003233 if (Namespc->isInline() != OrigNS->isInline()) {
3234 // inline-ness must match
3235 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3236 << Namespc->isInline();
3237 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3238 Namespc->setInvalidDecl();
3239 // Recover by ignoring the new namespace's inline status.
3240 Namespc->setInline(OrigNS->isInline());
3241 }
3242
Douglas Gregor44b43212008-12-11 16:49:14 +00003243 // Attach this namespace decl to the chain of extended namespace
3244 // definitions.
3245 OrigNS->setNextNamespace(Namespc);
3246 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003247
Mike Stump1eb44332009-09-09 15:08:12 +00003248 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003249 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003250 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003251 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003252 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003253 } else if (PrevDecl) {
3254 // This is an invalid name redefinition.
3255 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3256 << Namespc->getDeclName();
3257 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3258 Namespc->setInvalidDecl();
3259 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003260 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003261 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003262 // This is the first "real" definition of the namespace "std", so update
3263 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003264 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003265 // We had already defined a dummy namespace "std". Link this new
3266 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003267 StdNS->setNextNamespace(Namespc);
3268 StdNS->setLocation(IdentLoc);
3269 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003270 }
3271
3272 // Make our StdNamespace cache point at the first real definition of the
3273 // "std" namespace.
3274 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003275 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003276
3277 PushOnScopeChains(Namespc, DeclRegionScope);
3278 } else {
John McCall9aeed322009-10-01 00:25:31 +00003279 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003280 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003281
3282 // Link the anonymous namespace into its parent.
3283 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003284 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003285 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3286 PrevDecl = TU->getAnonymousNamespace();
3287 TU->setAnonymousNamespace(Namespc);
3288 } else {
3289 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3290 PrevDecl = ND->getAnonymousNamespace();
3291 ND->setAnonymousNamespace(Namespc);
3292 }
3293
3294 // Link the anonymous namespace with its previous declaration.
3295 if (PrevDecl) {
3296 assert(PrevDecl->isAnonymousNamespace());
3297 assert(!PrevDecl->getNextNamespace());
3298 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3299 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003300
3301 if (Namespc->isInline() != PrevDecl->isInline()) {
3302 // inline-ness must match
3303 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3304 << Namespc->isInline();
3305 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3306 Namespc->setInvalidDecl();
3307 // Recover by ignoring the new namespace's inline status.
3308 Namespc->setInline(PrevDecl->isInline());
3309 }
John McCall5fdd7642009-12-16 02:06:49 +00003310 }
John McCall9aeed322009-10-01 00:25:31 +00003311
Douglas Gregora4181472010-03-24 00:46:35 +00003312 CurContext->addDecl(Namespc);
3313
John McCall9aeed322009-10-01 00:25:31 +00003314 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3315 // behaves as if it were replaced by
3316 // namespace unique { /* empty body */ }
3317 // using namespace unique;
3318 // namespace unique { namespace-body }
3319 // where all occurrences of 'unique' in a translation unit are
3320 // replaced by the same identifier and this identifier differs
3321 // from all other identifiers in the entire program.
3322
3323 // We just create the namespace with an empty name and then add an
3324 // implicit using declaration, just like the standard suggests.
3325 //
3326 // CodeGen enforces the "universally unique" aspect by giving all
3327 // declarations semantically contained within an anonymous
3328 // namespace internal linkage.
3329
John McCall5fdd7642009-12-16 02:06:49 +00003330 if (!PrevDecl) {
3331 UsingDirectiveDecl* UD
3332 = UsingDirectiveDecl::Create(Context, CurContext,
3333 /* 'using' */ LBrace,
3334 /* 'namespace' */ SourceLocation(),
3335 /* qualifier */ SourceRange(),
3336 /* NNS */ NULL,
3337 /* identifier */ SourceLocation(),
3338 Namespc,
3339 /* Ancestor */ CurContext);
3340 UD->setImplicit();
3341 CurContext->addDecl(UD);
3342 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003343 }
3344
3345 // Although we could have an invalid decl (i.e. the namespace name is a
3346 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003347 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3348 // for the namespace has the declarations that showed up in that particular
3349 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003350 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003351 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003352}
3353
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003354/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3355/// is a namespace alias, returns the namespace it points to.
3356static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3357 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3358 return AD->getNamespace();
3359 return dyn_cast_or_null<NamespaceDecl>(D);
3360}
3361
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003362/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3363/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003364void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003365 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3366 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3367 Namespc->setRBracLoc(RBrace);
3368 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003369 if (Namespc->hasAttr<VisibilityAttr>())
3370 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003371}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003372
John McCall384aff82010-08-25 07:42:41 +00003373CXXRecordDecl *Sema::getStdBadAlloc() const {
3374 return cast_or_null<CXXRecordDecl>(
3375 StdBadAlloc.get(Context.getExternalSource()));
3376}
3377
3378NamespaceDecl *Sema::getStdNamespace() const {
3379 return cast_or_null<NamespaceDecl>(
3380 StdNamespace.get(Context.getExternalSource()));
3381}
3382
Douglas Gregor66992202010-06-29 17:53:46 +00003383/// \brief Retrieve the special "std" namespace, which may require us to
3384/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003385NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003386 if (!StdNamespace) {
3387 // The "std" namespace has not yet been defined, so build one implicitly.
3388 StdNamespace = NamespaceDecl::Create(Context,
3389 Context.getTranslationUnitDecl(),
3390 SourceLocation(),
3391 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003392 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003393 }
3394
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003395 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003396}
3397
John McCalld226f652010-08-21 09:40:31 +00003398Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003399 SourceLocation UsingLoc,
3400 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003401 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003402 SourceLocation IdentLoc,
3403 IdentifierInfo *NamespcName,
3404 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003405 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3406 assert(NamespcName && "Invalid NamespcName.");
3407 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003408 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003409
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003410 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003411 NestedNameSpecifier *Qualifier = 0;
3412 if (SS.isSet())
3413 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3414
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003415 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003416 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3417 LookupParsedName(R, S, &SS);
3418 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003419 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003420
Douglas Gregor66992202010-06-29 17:53:46 +00003421 if (R.empty()) {
3422 // Allow "using namespace std;" or "using namespace ::std;" even if
3423 // "std" hasn't been defined yet, for GCC compatibility.
3424 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3425 NamespcName->isStr("std")) {
3426 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003427 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003428 R.resolveKind();
3429 }
3430 // Otherwise, attempt typo correction.
3431 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3432 CTC_NoKeywords, 0)) {
3433 if (R.getAsSingle<NamespaceDecl>() ||
3434 R.getAsSingle<NamespaceAliasDecl>()) {
3435 if (DeclContext *DC = computeDeclContext(SS, false))
3436 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3437 << NamespcName << DC << Corrected << SS.getRange()
3438 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3439 else
3440 Diag(IdentLoc, diag::err_using_directive_suggest)
3441 << NamespcName << Corrected
3442 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3443 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3444 << Corrected;
3445
3446 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003447 } else {
3448 R.clear();
3449 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003450 }
3451 }
3452 }
3453
John McCallf36e02d2009-10-09 21:13:30 +00003454 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003455 NamedDecl *Named = R.getFoundDecl();
3456 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3457 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003458 // C++ [namespace.udir]p1:
3459 // A using-directive specifies that the names in the nominated
3460 // namespace can be used in the scope in which the
3461 // using-directive appears after the using-directive. During
3462 // unqualified name lookup (3.4.1), the names appear as if they
3463 // were declared in the nearest enclosing namespace which
3464 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003465 // namespace. [Note: in this context, "contains" means "contains
3466 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003467
3468 // Find enclosing context containing both using-directive and
3469 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003470 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003471 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3472 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3473 CommonAncestor = CommonAncestor->getParent();
3474
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003475 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003476 SS.getRange(),
3477 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003478 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003479 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003480 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003481 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003482 }
3483
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003484 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003485 delete AttrList;
John McCalld226f652010-08-21 09:40:31 +00003486 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003487}
3488
3489void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3490 // If scope has associated entity, then using directive is at namespace
3491 // or translation unit scope. We add UsingDirectiveDecls, into
3492 // it's lookup structure.
3493 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003494 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003495 else
3496 // Otherwise it is block-sope. using-directives will affect lookup
3497 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003498 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003499}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003500
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003501
John McCalld226f652010-08-21 09:40:31 +00003502Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003503 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003504 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003505 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003506 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003507 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003508 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003509 bool IsTypeName,
3510 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003511 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Douglas Gregor12c118a2009-11-04 16:30:06 +00003513 switch (Name.getKind()) {
3514 case UnqualifiedId::IK_Identifier:
3515 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003516 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003517 case UnqualifiedId::IK_ConversionFunctionId:
3518 break;
3519
3520 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003521 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003522 // C++0x inherited constructors.
3523 if (getLangOptions().CPlusPlus0x) break;
3524
Douglas Gregor12c118a2009-11-04 16:30:06 +00003525 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3526 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003527 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003528
3529 case UnqualifiedId::IK_DestructorName:
3530 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3531 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003532 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003533
3534 case UnqualifiedId::IK_TemplateId:
3535 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3536 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003537 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003538 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003539
3540 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3541 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003542 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003543 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003544
John McCall60fa3cf2009-12-11 02:10:03 +00003545 // Warn about using declarations.
3546 // TODO: store that the declaration was written without 'using' and
3547 // talk about access decls instead of using decls in the
3548 // diagnostics.
3549 if (!HasUsingKeyword) {
3550 UsingLoc = Name.getSourceRange().getBegin();
3551
3552 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003553 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003554 }
3555
John McCall9488ea12009-11-17 05:59:44 +00003556 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003557 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003558 /* IsInstantiation */ false,
3559 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003560 if (UD)
3561 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003562
John McCalld226f652010-08-21 09:40:31 +00003563 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003564}
3565
Douglas Gregor09acc982010-07-07 23:08:52 +00003566/// \brief Determine whether a using declaration considers the given
3567/// declarations as "equivalent", e.g., if they are redeclarations of
3568/// the same entity or are both typedefs of the same type.
3569static bool
3570IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3571 bool &SuppressRedeclaration) {
3572 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3573 SuppressRedeclaration = false;
3574 return true;
3575 }
3576
3577 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3578 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3579 SuppressRedeclaration = true;
3580 return Context.hasSameType(TD1->getUnderlyingType(),
3581 TD2->getUnderlyingType());
3582 }
3583
3584 return false;
3585}
3586
3587
John McCall9f54ad42009-12-10 09:41:52 +00003588/// Determines whether to create a using shadow decl for a particular
3589/// decl, given the set of decls existing prior to this using lookup.
3590bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3591 const LookupResult &Previous) {
3592 // Diagnose finding a decl which is not from a base class of the
3593 // current class. We do this now because there are cases where this
3594 // function will silently decide not to build a shadow decl, which
3595 // will pre-empt further diagnostics.
3596 //
3597 // We don't need to do this in C++0x because we do the check once on
3598 // the qualifier.
3599 //
3600 // FIXME: diagnose the following if we care enough:
3601 // struct A { int foo; };
3602 // struct B : A { using A::foo; };
3603 // template <class T> struct C : A {};
3604 // template <class T> struct D : C<T> { using B::foo; } // <---
3605 // This is invalid (during instantiation) in C++03 because B::foo
3606 // resolves to the using decl in B, which is not a base class of D<T>.
3607 // We can't diagnose it immediately because C<T> is an unknown
3608 // specialization. The UsingShadowDecl in D<T> then points directly
3609 // to A::foo, which will look well-formed when we instantiate.
3610 // The right solution is to not collapse the shadow-decl chain.
3611 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3612 DeclContext *OrigDC = Orig->getDeclContext();
3613
3614 // Handle enums and anonymous structs.
3615 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3616 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3617 while (OrigRec->isAnonymousStructOrUnion())
3618 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3619
3620 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3621 if (OrigDC == CurContext) {
3622 Diag(Using->getLocation(),
3623 diag::err_using_decl_nested_name_specifier_is_current_class)
3624 << Using->getNestedNameRange();
3625 Diag(Orig->getLocation(), diag::note_using_decl_target);
3626 return true;
3627 }
3628
3629 Diag(Using->getNestedNameRange().getBegin(),
3630 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3631 << Using->getTargetNestedNameDecl()
3632 << cast<CXXRecordDecl>(CurContext)
3633 << Using->getNestedNameRange();
3634 Diag(Orig->getLocation(), diag::note_using_decl_target);
3635 return true;
3636 }
3637 }
3638
3639 if (Previous.empty()) return false;
3640
3641 NamedDecl *Target = Orig;
3642 if (isa<UsingShadowDecl>(Target))
3643 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3644
John McCalld7533ec2009-12-11 02:33:26 +00003645 // If the target happens to be one of the previous declarations, we
3646 // don't have a conflict.
3647 //
3648 // FIXME: but we might be increasing its access, in which case we
3649 // should redeclare it.
3650 NamedDecl *NonTag = 0, *Tag = 0;
3651 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3652 I != E; ++I) {
3653 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003654 bool Result;
3655 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3656 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003657
3658 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3659 }
3660
John McCall9f54ad42009-12-10 09:41:52 +00003661 if (Target->isFunctionOrFunctionTemplate()) {
3662 FunctionDecl *FD;
3663 if (isa<FunctionTemplateDecl>(Target))
3664 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3665 else
3666 FD = cast<FunctionDecl>(Target);
3667
3668 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003669 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003670 case Ovl_Overload:
3671 return false;
3672
3673 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003674 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003675 break;
3676
3677 // We found a decl with the exact signature.
3678 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003679 // If we're in a record, we want to hide the target, so we
3680 // return true (without a diagnostic) to tell the caller not to
3681 // build a shadow decl.
3682 if (CurContext->isRecord())
3683 return true;
3684
3685 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003686 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003687 break;
3688 }
3689
3690 Diag(Target->getLocation(), diag::note_using_decl_target);
3691 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3692 return true;
3693 }
3694
3695 // Target is not a function.
3696
John McCall9f54ad42009-12-10 09:41:52 +00003697 if (isa<TagDecl>(Target)) {
3698 // No conflict between a tag and a non-tag.
3699 if (!Tag) return false;
3700
John McCall41ce66f2009-12-10 19:51:03 +00003701 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003702 Diag(Target->getLocation(), diag::note_using_decl_target);
3703 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3704 return true;
3705 }
3706
3707 // No conflict between a tag and a non-tag.
3708 if (!NonTag) return false;
3709
John McCall41ce66f2009-12-10 19:51:03 +00003710 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003711 Diag(Target->getLocation(), diag::note_using_decl_target);
3712 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3713 return true;
3714}
3715
John McCall9488ea12009-11-17 05:59:44 +00003716/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003717UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003718 UsingDecl *UD,
3719 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003720
3721 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003722 NamedDecl *Target = Orig;
3723 if (isa<UsingShadowDecl>(Target)) {
3724 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3725 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003726 }
3727
3728 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003729 = UsingShadowDecl::Create(Context, CurContext,
3730 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003731 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003732
3733 Shadow->setAccess(UD->getAccess());
3734 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3735 Shadow->setInvalidDecl();
3736
John McCall9488ea12009-11-17 05:59:44 +00003737 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003738 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003739 else
John McCall604e7f12009-12-08 07:46:18 +00003740 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003741
John McCall604e7f12009-12-08 07:46:18 +00003742
John McCall9f54ad42009-12-10 09:41:52 +00003743 return Shadow;
3744}
John McCall604e7f12009-12-08 07:46:18 +00003745
John McCall9f54ad42009-12-10 09:41:52 +00003746/// Hides a using shadow declaration. This is required by the current
3747/// using-decl implementation when a resolvable using declaration in a
3748/// class is followed by a declaration which would hide or override
3749/// one or more of the using decl's targets; for example:
3750///
3751/// struct Base { void foo(int); };
3752/// struct Derived : Base {
3753/// using Base::foo;
3754/// void foo(int);
3755/// };
3756///
3757/// The governing language is C++03 [namespace.udecl]p12:
3758///
3759/// When a using-declaration brings names from a base class into a
3760/// derived class scope, member functions in the derived class
3761/// override and/or hide member functions with the same name and
3762/// parameter types in a base class (rather than conflicting).
3763///
3764/// There are two ways to implement this:
3765/// (1) optimistically create shadow decls when they're not hidden
3766/// by existing declarations, or
3767/// (2) don't create any shadow decls (or at least don't make them
3768/// visible) until we've fully parsed/instantiated the class.
3769/// The problem with (1) is that we might have to retroactively remove
3770/// a shadow decl, which requires several O(n) operations because the
3771/// decl structures are (very reasonably) not designed for removal.
3772/// (2) avoids this but is very fiddly and phase-dependent.
3773void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003774 if (Shadow->getDeclName().getNameKind() ==
3775 DeclarationName::CXXConversionFunctionName)
3776 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3777
John McCall9f54ad42009-12-10 09:41:52 +00003778 // Remove it from the DeclContext...
3779 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003780
John McCall9f54ad42009-12-10 09:41:52 +00003781 // ...and the scope, if applicable...
3782 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003783 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003784 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003785 }
3786
John McCall9f54ad42009-12-10 09:41:52 +00003787 // ...and the using decl.
3788 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3789
3790 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003791 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003792}
3793
John McCall7ba107a2009-11-18 02:36:19 +00003794/// Builds a using declaration.
3795///
3796/// \param IsInstantiation - Whether this call arises from an
3797/// instantiation of an unresolved using declaration. We treat
3798/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003799NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3800 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003801 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003802 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003803 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003804 bool IsInstantiation,
3805 bool IsTypeName,
3806 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003807 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003808 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003809 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003810
Anders Carlsson550b14b2009-08-28 05:49:21 +00003811 // FIXME: We ignore attributes for now.
3812 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003814 if (SS.isEmpty()) {
3815 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003816 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003817 }
Mike Stump1eb44332009-09-09 15:08:12 +00003818
John McCall9f54ad42009-12-10 09:41:52 +00003819 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003820 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003821 ForRedeclaration);
3822 Previous.setHideTags(false);
3823 if (S) {
3824 LookupName(Previous, S);
3825
3826 // It is really dumb that we have to do this.
3827 LookupResult::Filter F = Previous.makeFilter();
3828 while (F.hasNext()) {
3829 NamedDecl *D = F.next();
3830 if (!isDeclInScope(D, CurContext, S))
3831 F.erase();
3832 }
3833 F.done();
3834 } else {
3835 assert(IsInstantiation && "no scope in non-instantiation");
3836 assert(CurContext->isRecord() && "scope not record in instantiation");
3837 LookupQualifiedName(Previous, CurContext);
3838 }
3839
Mike Stump1eb44332009-09-09 15:08:12 +00003840 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003841 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3842
John McCall9f54ad42009-12-10 09:41:52 +00003843 // Check for invalid redeclarations.
3844 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3845 return 0;
3846
3847 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003848 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3849 return 0;
3850
John McCallaf8e6ed2009-11-12 03:15:40 +00003851 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003852 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003853 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003854 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003855 // FIXME: not all declaration name kinds are legal here
3856 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3857 UsingLoc, TypenameLoc,
3858 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003859 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003860 } else {
3861 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003862 UsingLoc, SS.getRange(),
3863 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003864 }
John McCalled976492009-12-04 22:46:56 +00003865 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003866 D = UsingDecl::Create(Context, CurContext,
3867 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003868 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003869 }
John McCalled976492009-12-04 22:46:56 +00003870 D->setAccess(AS);
3871 CurContext->addDecl(D);
3872
3873 if (!LookupContext) return D;
3874 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003875
John McCall77bb1aa2010-05-01 00:40:08 +00003876 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003877 UD->setInvalidDecl();
3878 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003879 }
3880
John McCall604e7f12009-12-08 07:46:18 +00003881 // Look up the target name.
3882
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003883 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003884
John McCall604e7f12009-12-08 07:46:18 +00003885 // Unlike most lookups, we don't always want to hide tag
3886 // declarations: tag names are visible through the using declaration
3887 // even if hidden by ordinary names, *except* in a dependent context
3888 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003889 if (!IsInstantiation)
3890 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003891
John McCalla24dc2e2009-11-17 02:14:36 +00003892 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003893
John McCallf36e02d2009-10-09 21:13:30 +00003894 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003895 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003896 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003897 UD->setInvalidDecl();
3898 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003899 }
3900
John McCalled976492009-12-04 22:46:56 +00003901 if (R.isAmbiguous()) {
3902 UD->setInvalidDecl();
3903 return UD;
3904 }
Mike Stump1eb44332009-09-09 15:08:12 +00003905
John McCall7ba107a2009-11-18 02:36:19 +00003906 if (IsTypeName) {
3907 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003908 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003909 Diag(IdentLoc, diag::err_using_typename_non_type);
3910 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3911 Diag((*I)->getUnderlyingDecl()->getLocation(),
3912 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003913 UD->setInvalidDecl();
3914 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003915 }
3916 } else {
3917 // If we asked for a non-typename and we got a type, error out,
3918 // but only if this is an instantiation of an unresolved using
3919 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003920 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003921 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3922 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003923 UD->setInvalidDecl();
3924 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003925 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003926 }
3927
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003928 // C++0x N2914 [namespace.udecl]p6:
3929 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003930 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003931 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3932 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003933 UD->setInvalidDecl();
3934 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003935 }
Mike Stump1eb44332009-09-09 15:08:12 +00003936
John McCall9f54ad42009-12-10 09:41:52 +00003937 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3938 if (!CheckUsingShadowDecl(UD, *I, Previous))
3939 BuildUsingShadowDecl(S, UD, *I);
3940 }
John McCall9488ea12009-11-17 05:59:44 +00003941
3942 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003943}
3944
John McCall9f54ad42009-12-10 09:41:52 +00003945/// Checks that the given using declaration is not an invalid
3946/// redeclaration. Note that this is checking only for the using decl
3947/// itself, not for any ill-formedness among the UsingShadowDecls.
3948bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3949 bool isTypeName,
3950 const CXXScopeSpec &SS,
3951 SourceLocation NameLoc,
3952 const LookupResult &Prev) {
3953 // C++03 [namespace.udecl]p8:
3954 // C++0x [namespace.udecl]p10:
3955 // A using-declaration is a declaration and can therefore be used
3956 // repeatedly where (and only where) multiple declarations are
3957 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00003958 //
3959 // That's in non-member contexts.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003960 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00003961 return false;
3962
3963 NestedNameSpecifier *Qual
3964 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3965
3966 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3967 NamedDecl *D = *I;
3968
3969 bool DTypename;
3970 NestedNameSpecifier *DQual;
3971 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3972 DTypename = UD->isTypeName();
3973 DQual = UD->getTargetNestedNameDecl();
3974 } else if (UnresolvedUsingValueDecl *UD
3975 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3976 DTypename = false;
3977 DQual = UD->getTargetNestedNameSpecifier();
3978 } else if (UnresolvedUsingTypenameDecl *UD
3979 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3980 DTypename = true;
3981 DQual = UD->getTargetNestedNameSpecifier();
3982 } else continue;
3983
3984 // using decls differ if one says 'typename' and the other doesn't.
3985 // FIXME: non-dependent using decls?
3986 if (isTypeName != DTypename) continue;
3987
3988 // using decls differ if they name different scopes (but note that
3989 // template instantiation can cause this check to trigger when it
3990 // didn't before instantiation).
3991 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3992 Context.getCanonicalNestedNameSpecifier(DQual))
3993 continue;
3994
3995 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003996 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003997 return true;
3998 }
3999
4000 return false;
4001}
4002
John McCall604e7f12009-12-08 07:46:18 +00004003
John McCalled976492009-12-04 22:46:56 +00004004/// Checks that the given nested-name qualifier used in a using decl
4005/// in the current context is appropriately related to the current
4006/// scope. If an error is found, diagnoses it and returns true.
4007bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4008 const CXXScopeSpec &SS,
4009 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004010 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004011
John McCall604e7f12009-12-08 07:46:18 +00004012 if (!CurContext->isRecord()) {
4013 // C++03 [namespace.udecl]p3:
4014 // C++0x [namespace.udecl]p8:
4015 // A using-declaration for a class member shall be a member-declaration.
4016
4017 // If we weren't able to compute a valid scope, it must be a
4018 // dependent class scope.
4019 if (!NamedContext || NamedContext->isRecord()) {
4020 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4021 << SS.getRange();
4022 return true;
4023 }
4024
4025 // Otherwise, everything is known to be fine.
4026 return false;
4027 }
4028
4029 // The current scope is a record.
4030
4031 // If the named context is dependent, we can't decide much.
4032 if (!NamedContext) {
4033 // FIXME: in C++0x, we can diagnose if we can prove that the
4034 // nested-name-specifier does not refer to a base class, which is
4035 // still possible in some cases.
4036
4037 // Otherwise we have to conservatively report that things might be
4038 // okay.
4039 return false;
4040 }
4041
4042 if (!NamedContext->isRecord()) {
4043 // Ideally this would point at the last name in the specifier,
4044 // but we don't have that level of source info.
4045 Diag(SS.getRange().getBegin(),
4046 diag::err_using_decl_nested_name_specifier_is_not_class)
4047 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4048 return true;
4049 }
4050
4051 if (getLangOptions().CPlusPlus0x) {
4052 // C++0x [namespace.udecl]p3:
4053 // In a using-declaration used as a member-declaration, the
4054 // nested-name-specifier shall name a base class of the class
4055 // being defined.
4056
4057 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4058 cast<CXXRecordDecl>(NamedContext))) {
4059 if (CurContext == NamedContext) {
4060 Diag(NameLoc,
4061 diag::err_using_decl_nested_name_specifier_is_current_class)
4062 << SS.getRange();
4063 return true;
4064 }
4065
4066 Diag(SS.getRange().getBegin(),
4067 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4068 << (NestedNameSpecifier*) SS.getScopeRep()
4069 << cast<CXXRecordDecl>(CurContext)
4070 << SS.getRange();
4071 return true;
4072 }
4073
4074 return false;
4075 }
4076
4077 // C++03 [namespace.udecl]p4:
4078 // A using-declaration used as a member-declaration shall refer
4079 // to a member of a base class of the class being defined [etc.].
4080
4081 // Salient point: SS doesn't have to name a base class as long as
4082 // lookup only finds members from base classes. Therefore we can
4083 // diagnose here only if we can prove that that can't happen,
4084 // i.e. if the class hierarchies provably don't intersect.
4085
4086 // TODO: it would be nice if "definitely valid" results were cached
4087 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4088 // need to be repeated.
4089
4090 struct UserData {
4091 llvm::DenseSet<const CXXRecordDecl*> Bases;
4092
4093 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4094 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4095 Data->Bases.insert(Base);
4096 return true;
4097 }
4098
4099 bool hasDependentBases(const CXXRecordDecl *Class) {
4100 return !Class->forallBases(collect, this);
4101 }
4102
4103 /// Returns true if the base is dependent or is one of the
4104 /// accumulated base classes.
4105 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4106 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4107 return !Data->Bases.count(Base);
4108 }
4109
4110 bool mightShareBases(const CXXRecordDecl *Class) {
4111 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4112 }
4113 };
4114
4115 UserData Data;
4116
4117 // Returns false if we find a dependent base.
4118 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4119 return false;
4120
4121 // Returns false if the class has a dependent base or if it or one
4122 // of its bases is present in the base set of the current context.
4123 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4124 return false;
4125
4126 Diag(SS.getRange().getBegin(),
4127 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4128 << (NestedNameSpecifier*) SS.getScopeRep()
4129 << cast<CXXRecordDecl>(CurContext)
4130 << SS.getRange();
4131
4132 return true;
John McCalled976492009-12-04 22:46:56 +00004133}
4134
John McCalld226f652010-08-21 09:40:31 +00004135Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004136 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004137 SourceLocation AliasLoc,
4138 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004139 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004140 SourceLocation IdentLoc,
4141 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Anders Carlsson81c85c42009-03-28 23:53:49 +00004143 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004144 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4145 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004146
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004147 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004148 NamedDecl *PrevDecl
4149 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4150 ForRedeclaration);
4151 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4152 PrevDecl = 0;
4153
4154 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004155 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004156 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004157 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004158 // FIXME: At some point, we'll want to create the (redundant)
4159 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004160 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004161 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004162 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004163 }
Mike Stump1eb44332009-09-09 15:08:12 +00004164
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004165 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4166 diag::err_redefinition_different_kind;
4167 Diag(AliasLoc, DiagID) << Alias;
4168 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004169 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004170 }
4171
John McCalla24dc2e2009-11-17 02:14:36 +00004172 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004173 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004174
John McCallf36e02d2009-10-09 21:13:30 +00004175 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004176 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4177 CTC_NoKeywords, 0)) {
4178 if (R.getAsSingle<NamespaceDecl>() ||
4179 R.getAsSingle<NamespaceAliasDecl>()) {
4180 if (DeclContext *DC = computeDeclContext(SS, false))
4181 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4182 << Ident << DC << Corrected << SS.getRange()
4183 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4184 else
4185 Diag(IdentLoc, diag::err_using_directive_suggest)
4186 << Ident << Corrected
4187 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4188
4189 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4190 << Corrected;
4191
4192 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004193 } else {
4194 R.clear();
4195 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004196 }
4197 }
4198
4199 if (R.empty()) {
4200 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004201 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004202 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004203 }
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004205 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004206 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4207 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004208 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004209 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004210
John McCall3dbd3d52010-02-16 06:53:13 +00004211 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004212 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004213}
4214
Douglas Gregor39957dc2010-05-01 15:04:51 +00004215namespace {
4216 /// \brief Scoped object used to handle the state changes required in Sema
4217 /// to implicitly define the body of a C++ member function;
4218 class ImplicitlyDefinedFunctionScope {
4219 Sema &S;
4220 DeclContext *PreviousContext;
4221
4222 public:
4223 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4224 : S(S), PreviousContext(S.CurContext)
4225 {
4226 S.CurContext = Method;
4227 S.PushFunctionScope();
4228 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4229 }
4230
4231 ~ImplicitlyDefinedFunctionScope() {
4232 S.PopExpressionEvaluationContext();
4233 S.PopFunctionOrBlockScope();
4234 S.CurContext = PreviousContext;
4235 }
4236 };
4237}
4238
Sebastian Redl751025d2010-09-13 22:02:47 +00004239static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4240 CXXRecordDecl *D) {
4241 ASTContext &Context = Self.Context;
4242 QualType ClassType = Context.getTypeDeclType(D);
4243 DeclarationName ConstructorName
4244 = Context.DeclarationNames.getCXXConstructorName(
4245 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4246
4247 DeclContext::lookup_const_iterator Con, ConEnd;
4248 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4249 Con != ConEnd; ++Con) {
4250 // FIXME: In C++0x, a constructor template can be a default constructor.
4251 if (isa<FunctionTemplateDecl>(*Con))
4252 continue;
4253
4254 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4255 if (Constructor->isDefaultConstructor())
4256 return Constructor;
4257 }
4258 return 0;
4259}
4260
Douglas Gregor23c94db2010-07-02 17:43:08 +00004261CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4262 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004263 // C++ [class.ctor]p5:
4264 // A default constructor for a class X is a constructor of class X
4265 // that can be called without an argument. If there is no
4266 // user-declared constructor for class X, a default constructor is
4267 // implicitly declared. An implicitly-declared default constructor
4268 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004269 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4270 "Should not build implicit default constructor!");
4271
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004272 // C++ [except.spec]p14:
4273 // An implicitly declared special member function (Clause 12) shall have an
4274 // exception-specification. [...]
4275 ImplicitExceptionSpecification ExceptSpec(Context);
4276
4277 // Direct base-class destructors.
4278 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4279 BEnd = ClassDecl->bases_end();
4280 B != BEnd; ++B) {
4281 if (B->isVirtual()) // Handled below.
4282 continue;
4283
Douglas Gregor18274032010-07-03 00:47:00 +00004284 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4285 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4286 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4287 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004288 else if (CXXConstructorDecl *Constructor
4289 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004290 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004291 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004292 }
4293
4294 // Virtual base-class destructors.
4295 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4296 BEnd = ClassDecl->vbases_end();
4297 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004298 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4299 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4300 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4301 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4302 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004303 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004304 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004305 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004306 }
4307
4308 // Field destructors.
4309 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4310 FEnd = ClassDecl->field_end();
4311 F != FEnd; ++F) {
4312 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004313 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4314 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4315 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4316 ExceptSpec.CalledDecl(
4317 DeclareImplicitDefaultConstructor(FieldClassDecl));
4318 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004319 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004320 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004321 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004322 }
4323
4324
4325 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004326 CanQualType ClassType
4327 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4328 DeclarationName Name
4329 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004330 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004331 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004332 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004333 Context.getFunctionType(Context.VoidTy,
4334 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004335 ExceptSpec.hasExceptionSpecification(),
4336 ExceptSpec.hasAnyExceptionSpecification(),
4337 ExceptSpec.size(),
4338 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004339 FunctionType::ExtInfo()),
4340 /*TInfo=*/0,
4341 /*isExplicit=*/false,
4342 /*isInline=*/true,
4343 /*isImplicitlyDeclared=*/true);
4344 DefaultCon->setAccess(AS_public);
4345 DefaultCon->setImplicit();
4346 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004347
4348 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004349 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4350
Douglas Gregor23c94db2010-07-02 17:43:08 +00004351 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004352 PushOnScopeChains(DefaultCon, S, false);
4353 ClassDecl->addDecl(DefaultCon);
4354
Douglas Gregor32df23e2010-07-01 22:02:46 +00004355 return DefaultCon;
4356}
4357
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004358void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4359 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004360 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004361 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004362 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004363
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004364 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004365 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004366
Douglas Gregor39957dc2010-05-01 15:04:51 +00004367 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004368 ErrorTrap Trap(*this);
4369 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4370 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004371 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004372 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004373 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004374 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004375 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004376
4377 SourceLocation Loc = Constructor->getLocation();
4378 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4379
4380 Constructor->setUsed();
4381 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004382}
4383
Douglas Gregor23c94db2010-07-02 17:43:08 +00004384CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004385 // C++ [class.dtor]p2:
4386 // If a class has no user-declared destructor, a destructor is
4387 // declared implicitly. An implicitly-declared destructor is an
4388 // inline public member of its class.
4389
4390 // C++ [except.spec]p14:
4391 // An implicitly declared special member function (Clause 12) shall have
4392 // an exception-specification.
4393 ImplicitExceptionSpecification ExceptSpec(Context);
4394
4395 // Direct base-class destructors.
4396 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4397 BEnd = ClassDecl->bases_end();
4398 B != BEnd; ++B) {
4399 if (B->isVirtual()) // Handled below.
4400 continue;
4401
4402 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4403 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004404 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004405 }
4406
4407 // Virtual base-class destructors.
4408 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4409 BEnd = ClassDecl->vbases_end();
4410 B != BEnd; ++B) {
4411 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4412 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004413 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004414 }
4415
4416 // Field destructors.
4417 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4418 FEnd = ClassDecl->field_end();
4419 F != FEnd; ++F) {
4420 if (const RecordType *RecordTy
4421 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4422 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004423 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004424 }
4425
Douglas Gregor4923aa22010-07-02 20:37:36 +00004426 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004427 QualType Ty = Context.getFunctionType(Context.VoidTy,
4428 0, 0, false, 0,
4429 ExceptSpec.hasExceptionSpecification(),
4430 ExceptSpec.hasAnyExceptionSpecification(),
4431 ExceptSpec.size(),
4432 ExceptSpec.data(),
4433 FunctionType::ExtInfo());
4434
4435 CanQualType ClassType
4436 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4437 DeclarationName Name
4438 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004439 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004440 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004441 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004442 /*isInline=*/true,
4443 /*isImplicitlyDeclared=*/true);
4444 Destructor->setAccess(AS_public);
4445 Destructor->setImplicit();
4446 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004447
4448 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004449 ++ASTContext::NumImplicitDestructorsDeclared;
4450
4451 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004452 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004453 PushOnScopeChains(Destructor, S, false);
4454 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004455
4456 // This could be uniqued if it ever proves significant.
4457 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4458
4459 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004460
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004461 return Destructor;
4462}
4463
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004464void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004465 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004466 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004467 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004468 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004469 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004470
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004471 if (Destructor->isInvalidDecl())
4472 return;
4473
Douglas Gregor39957dc2010-05-01 15:04:51 +00004474 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004475
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004476 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004477 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4478 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004479
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004480 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004481 Diag(CurrentLocation, diag::note_member_synthesized_at)
4482 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4483
4484 Destructor->setInvalidDecl();
4485 return;
4486 }
4487
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004488 SourceLocation Loc = Destructor->getLocation();
4489 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4490
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004491 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004492 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004493}
4494
Douglas Gregor06a9f362010-05-01 20:49:11 +00004495/// \brief Builds a statement that copies the given entity from \p From to
4496/// \c To.
4497///
4498/// This routine is used to copy the members of a class with an
4499/// implicitly-declared copy assignment operator. When the entities being
4500/// copied are arrays, this routine builds for loops to copy them.
4501///
4502/// \param S The Sema object used for type-checking.
4503///
4504/// \param Loc The location where the implicit copy is being generated.
4505///
4506/// \param T The type of the expressions being copied. Both expressions must
4507/// have this type.
4508///
4509/// \param To The expression we are copying to.
4510///
4511/// \param From The expression we are copying from.
4512///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004513/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4514/// Otherwise, it's a non-static member subobject.
4515///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004516/// \param Depth Internal parameter recording the depth of the recursion.
4517///
4518/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004519static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004520BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004521 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004522 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004523 // C++0x [class.copy]p30:
4524 // Each subobject is assigned in the manner appropriate to its type:
4525 //
4526 // - if the subobject is of class type, the copy assignment operator
4527 // for the class is used (as if by explicit qualification; that is,
4528 // ignoring any possible virtual overriding functions in more derived
4529 // classes);
4530 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4531 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4532
4533 // Look for operator=.
4534 DeclarationName Name
4535 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4536 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4537 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4538
4539 // Filter out any result that isn't a copy-assignment operator.
4540 LookupResult::Filter F = OpLookup.makeFilter();
4541 while (F.hasNext()) {
4542 NamedDecl *D = F.next();
4543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4544 if (Method->isCopyAssignmentOperator())
4545 continue;
4546
4547 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004548 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004549 F.done();
4550
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004551 // Suppress the protected check (C++ [class.protected]) for each of the
4552 // assignment operators we found. This strange dance is required when
4553 // we're assigning via a base classes's copy-assignment operator. To
4554 // ensure that we're getting the right base class subobject (without
4555 // ambiguities), we need to cast "this" to that subobject type; to
4556 // ensure that we don't go through the virtual call mechanism, we need
4557 // to qualify the operator= name with the base class (see below). However,
4558 // this means that if the base class has a protected copy assignment
4559 // operator, the protected member access check will fail. So, we
4560 // rewrite "protected" access to "public" access in this case, since we
4561 // know by construction that we're calling from a derived class.
4562 if (CopyingBaseSubobject) {
4563 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4564 L != LEnd; ++L) {
4565 if (L.getAccess() == AS_protected)
4566 L.setAccess(AS_public);
4567 }
4568 }
4569
Douglas Gregor06a9f362010-05-01 20:49:11 +00004570 // Create the nested-name-specifier that will be used to qualify the
4571 // reference to operator=; this is required to suppress the virtual
4572 // call mechanism.
4573 CXXScopeSpec SS;
4574 SS.setRange(Loc);
4575 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4576 T.getTypePtr()));
4577
4578 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004579 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004580 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004581 /*FirstQualifierInScope=*/0, OpLookup,
4582 /*TemplateArgs=*/0,
4583 /*SuppressQualifierCheck=*/true);
4584 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004585 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004586
4587 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004588
John McCall60d7b3a2010-08-24 06:29:42 +00004589 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004590 OpEqualRef.takeAs<Expr>(),
4591 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004592 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004593 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004594
4595 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004596 }
John McCallb0207482010-03-16 06:11:48 +00004597
Douglas Gregor06a9f362010-05-01 20:49:11 +00004598 // - if the subobject is of scalar type, the built-in assignment
4599 // operator is used.
4600 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4601 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004602 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004603 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004604 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004605
4606 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004607 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004608
4609 // - if the subobject is an array, each element is assigned, in the
4610 // manner appropriate to the element type;
4611
4612 // Construct a loop over the array bounds, e.g.,
4613 //
4614 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4615 //
4616 // that will copy each of the array elements.
4617 QualType SizeType = S.Context.getSizeType();
4618
4619 // Create the iteration variable.
4620 IdentifierInfo *IterationVarName = 0;
4621 {
4622 llvm::SmallString<8> Str;
4623 llvm::raw_svector_ostream OS(Str);
4624 OS << "__i" << Depth;
4625 IterationVarName = &S.Context.Idents.get(OS.str());
4626 }
4627 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4628 IterationVarName, SizeType,
4629 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004630 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004631
4632 // Initialize the iteration variable to zero.
4633 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004634 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004635
4636 // Create a reference to the iteration variable; we'll use this several
4637 // times throughout.
4638 Expr *IterationVarRef
4639 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4640 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4641
4642 // Create the DeclStmt that holds the iteration variable.
4643 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4644
4645 // Create the comparison against the array bound.
4646 llvm::APInt Upper = ArrayTy->getSize();
4647 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004648 Expr *Comparison
4649 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004650 IntegerLiteral::Create(S.Context,
4651 Upper, SizeType, Loc),
4652 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004653
4654 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004655 Expr *Increment
4656 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCall2de56d12010-08-25 11:45:40 +00004657 UO_PreInc,
John McCall9ae2f072010-08-23 23:25:46 +00004658 SizeType, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004659
4660 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004661 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4662 IterationVarRef, Loc));
4663 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4664 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004665
4666 // Build the copy for an individual element of the array.
John McCall60d7b3a2010-08-24 06:29:42 +00004667 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004668 ArrayTy->getElementType(),
John McCall9ae2f072010-08-23 23:25:46 +00004669 To, From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004670 CopyingBaseSubobject, Depth+1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004671 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004672 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004673
4674 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004675 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004676 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004677 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004678 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004679}
4680
Douglas Gregora376d102010-07-02 21:50:04 +00004681/// \brief Determine whether the given class has a copy assignment operator
4682/// that accepts a const-qualified argument.
4683static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4684 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4685
4686 if (!Class->hasDeclaredCopyAssignment())
4687 S.DeclareImplicitCopyAssignment(Class);
4688
4689 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4690 DeclarationName OpName
4691 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4692
4693 DeclContext::lookup_const_iterator Op, OpEnd;
4694 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4695 // C++ [class.copy]p9:
4696 // A user-declared copy assignment operator is a non-static non-template
4697 // member function of class X with exactly one parameter of type X, X&,
4698 // const X&, volatile X& or const volatile X&.
4699 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4700 if (!Method)
4701 continue;
4702
4703 if (Method->isStatic())
4704 continue;
4705 if (Method->getPrimaryTemplate())
4706 continue;
4707 const FunctionProtoType *FnType =
4708 Method->getType()->getAs<FunctionProtoType>();
4709 assert(FnType && "Overloaded operator has no prototype.");
4710 // Don't assert on this; an invalid decl might have been left in the AST.
4711 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4712 continue;
4713 bool AcceptsConst = true;
4714 QualType ArgType = FnType->getArgType(0);
4715 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4716 ArgType = Ref->getPointeeType();
4717 // Is it a non-const lvalue reference?
4718 if (!ArgType.isConstQualified())
4719 AcceptsConst = false;
4720 }
4721 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4722 continue;
4723
4724 // We have a single argument of type cv X or cv X&, i.e. we've found the
4725 // copy assignment operator. Return whether it accepts const arguments.
4726 return AcceptsConst;
4727 }
4728 assert(Class->isInvalidDecl() &&
4729 "No copy assignment operator declared in valid code.");
4730 return false;
4731}
4732
Douglas Gregor23c94db2010-07-02 17:43:08 +00004733CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004734 // Note: The following rules are largely analoguous to the copy
4735 // constructor rules. Note that virtual bases are not taken into account
4736 // for determining the argument type of the operator. Note also that
4737 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004738
4739
Douglas Gregord3c35902010-07-01 16:36:15 +00004740 // C++ [class.copy]p10:
4741 // If the class definition does not explicitly declare a copy
4742 // assignment operator, one is declared implicitly.
4743 // The implicitly-defined copy assignment operator for a class X
4744 // will have the form
4745 //
4746 // X& X::operator=(const X&)
4747 //
4748 // if
4749 bool HasConstCopyAssignment = true;
4750
4751 // -- each direct base class B of X has a copy assignment operator
4752 // whose parameter is of type const B&, const volatile B& or B,
4753 // and
4754 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4755 BaseEnd = ClassDecl->bases_end();
4756 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4757 assert(!Base->getType()->isDependentType() &&
4758 "Cannot generate implicit members for class with dependent bases.");
4759 const CXXRecordDecl *BaseClassDecl
4760 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004761 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004762 }
4763
4764 // -- for all the nonstatic data members of X that are of a class
4765 // type M (or array thereof), each such class type has a copy
4766 // assignment operator whose parameter is of type const M&,
4767 // const volatile M& or M.
4768 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4769 FieldEnd = ClassDecl->field_end();
4770 HasConstCopyAssignment && Field != FieldEnd;
4771 ++Field) {
4772 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4773 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4774 const CXXRecordDecl *FieldClassDecl
4775 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004776 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004777 }
4778 }
4779
4780 // Otherwise, the implicitly declared copy assignment operator will
4781 // have the form
4782 //
4783 // X& X::operator=(X&)
4784 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4785 QualType RetType = Context.getLValueReferenceType(ArgType);
4786 if (HasConstCopyAssignment)
4787 ArgType = ArgType.withConst();
4788 ArgType = Context.getLValueReferenceType(ArgType);
4789
Douglas Gregorb87786f2010-07-01 17:48:08 +00004790 // C++ [except.spec]p14:
4791 // An implicitly declared special member function (Clause 12) shall have an
4792 // exception-specification. [...]
4793 ImplicitExceptionSpecification ExceptSpec(Context);
4794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4795 BaseEnd = ClassDecl->bases_end();
4796 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004797 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004798 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004799
4800 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4801 DeclareImplicitCopyAssignment(BaseClassDecl);
4802
Douglas Gregorb87786f2010-07-01 17:48:08 +00004803 if (CXXMethodDecl *CopyAssign
4804 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4805 ExceptSpec.CalledDecl(CopyAssign);
4806 }
4807 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4808 FieldEnd = ClassDecl->field_end();
4809 Field != FieldEnd;
4810 ++Field) {
4811 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4812 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004813 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004814 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004815
4816 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4817 DeclareImplicitCopyAssignment(FieldClassDecl);
4818
Douglas Gregorb87786f2010-07-01 17:48:08 +00004819 if (CXXMethodDecl *CopyAssign
4820 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4821 ExceptSpec.CalledDecl(CopyAssign);
4822 }
4823 }
4824
Douglas Gregord3c35902010-07-01 16:36:15 +00004825 // An implicitly-declared copy assignment operator is an inline public
4826 // member of its class.
4827 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004828 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004829 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004830 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004831 Context.getFunctionType(RetType, &ArgType, 1,
4832 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004833 ExceptSpec.hasExceptionSpecification(),
4834 ExceptSpec.hasAnyExceptionSpecification(),
4835 ExceptSpec.size(),
4836 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004837 FunctionType::ExtInfo()),
4838 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004839 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004840 /*isInline=*/true);
4841 CopyAssignment->setAccess(AS_public);
4842 CopyAssignment->setImplicit();
4843 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004844
4845 // Add the parameter to the operator.
4846 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4847 ClassDecl->getLocation(),
4848 /*Id=*/0,
4849 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004850 SC_None,
4851 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004852 CopyAssignment->setParams(&FromParam, 1);
4853
Douglas Gregora376d102010-07-02 21:50:04 +00004854 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004855 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4856
Douglas Gregor23c94db2010-07-02 17:43:08 +00004857 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004858 PushOnScopeChains(CopyAssignment, S, false);
4859 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004860
4861 AddOverriddenMethods(ClassDecl, CopyAssignment);
4862 return CopyAssignment;
4863}
4864
Douglas Gregor06a9f362010-05-01 20:49:11 +00004865void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4866 CXXMethodDecl *CopyAssignOperator) {
4867 assert((CopyAssignOperator->isImplicit() &&
4868 CopyAssignOperator->isOverloadedOperator() &&
4869 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004870 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004871 "DefineImplicitCopyAssignment called for wrong function");
4872
4873 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4874
4875 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4876 CopyAssignOperator->setInvalidDecl();
4877 return;
4878 }
4879
4880 CopyAssignOperator->setUsed();
4881
4882 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004883 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004884
4885 // C++0x [class.copy]p30:
4886 // The implicitly-defined or explicitly-defaulted copy assignment operator
4887 // for a non-union class X performs memberwise copy assignment of its
4888 // subobjects. The direct base classes of X are assigned first, in the
4889 // order of their declaration in the base-specifier-list, and then the
4890 // immediate non-static data members of X are assigned, in the order in
4891 // which they were declared in the class definition.
4892
4893 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004894 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004895
4896 // The parameter for the "other" object, which we are copying from.
4897 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4898 Qualifiers OtherQuals = Other->getType().getQualifiers();
4899 QualType OtherRefType = Other->getType();
4900 if (const LValueReferenceType *OtherRef
4901 = OtherRefType->getAs<LValueReferenceType>()) {
4902 OtherRefType = OtherRef->getPointeeType();
4903 OtherQuals = OtherRefType.getQualifiers();
4904 }
4905
4906 // Our location for everything implicitly-generated.
4907 SourceLocation Loc = CopyAssignOperator->getLocation();
4908
4909 // Construct a reference to the "other" object. We'll be using this
4910 // throughout the generated ASTs.
4911 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4912 assert(OtherRef && "Reference to parameter cannot fail!");
4913
4914 // Construct the "this" pointer. We'll be using this throughout the generated
4915 // ASTs.
4916 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4917 assert(This && "Reference to this cannot fail!");
4918
4919 // Assign base classes.
4920 bool Invalid = false;
4921 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4922 E = ClassDecl->bases_end(); Base != E; ++Base) {
4923 // Form the assignment:
4924 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4925 QualType BaseType = Base->getType().getUnqualifiedType();
4926 CXXRecordDecl *BaseClassDecl = 0;
4927 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4928 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4929 else {
4930 Invalid = true;
4931 continue;
4932 }
4933
John McCallf871d0c2010-08-07 06:22:56 +00004934 CXXCastPath BasePath;
4935 BasePath.push_back(Base);
4936
Douglas Gregor06a9f362010-05-01 20:49:11 +00004937 // Construct the "from" expression, which is an implicit cast to the
4938 // appropriately-qualified base type.
4939 Expr *From = OtherRef->Retain();
4940 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004941 CK_UncheckedDerivedToBase,
4942 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004943
4944 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004945 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004946
4947 // Implicitly cast "this" to the appropriately-qualified base type.
4948 Expr *ToE = To.takeAs<Expr>();
4949 ImpCastExprToType(ToE,
4950 Context.getCVRQualifiedType(BaseType,
4951 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004952 CK_UncheckedDerivedToBase,
4953 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004954 To = Owned(ToE);
4955
4956 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004957 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004958 To.get(), From,
4959 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004960 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004961 Diag(CurrentLocation, diag::note_member_synthesized_at)
4962 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4963 CopyAssignOperator->setInvalidDecl();
4964 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004965 }
4966
4967 // Success! Record the copy.
4968 Statements.push_back(Copy.takeAs<Expr>());
4969 }
4970
4971 // \brief Reference to the __builtin_memcpy function.
4972 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00004973 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00004974 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004975
4976 // Assign non-static members.
4977 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4978 FieldEnd = ClassDecl->field_end();
4979 Field != FieldEnd; ++Field) {
4980 // Check for members of reference type; we can't copy those.
4981 if (Field->getType()->isReferenceType()) {
4982 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4983 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4984 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004985 Diag(CurrentLocation, diag::note_member_synthesized_at)
4986 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004987 Invalid = true;
4988 continue;
4989 }
4990
4991 // Check for members of const-qualified, non-class type.
4992 QualType BaseType = Context.getBaseElementType(Field->getType());
4993 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4994 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4995 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4996 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004997 Diag(CurrentLocation, diag::note_member_synthesized_at)
4998 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004999 Invalid = true;
5000 continue;
5001 }
5002
5003 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005004 if (FieldType->isIncompleteArrayType()) {
5005 assert(ClassDecl->hasFlexibleArrayMember() &&
5006 "Incomplete array type is not valid");
5007 continue;
5008 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005009
5010 // Build references to the field in the object we're copying from and to.
5011 CXXScopeSpec SS; // Intentionally empty
5012 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5013 LookupMemberName);
5014 MemberLookup.addDecl(*Field);
5015 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005016 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005017 Loc, /*IsArrow=*/false,
5018 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005019 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005020 Loc, /*IsArrow=*/true,
5021 SS, 0, MemberLookup, 0);
5022 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5023 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5024
5025 // If the field should be copied with __builtin_memcpy rather than via
5026 // explicit assignments, do so. This optimization only applies for arrays
5027 // of scalars and arrays of class type with trivial copy-assignment
5028 // operators.
5029 if (FieldType->isArrayType() &&
5030 (!BaseType->isRecordType() ||
5031 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5032 ->hasTrivialCopyAssignment())) {
5033 // Compute the size of the memory buffer to be copied.
5034 QualType SizeType = Context.getSizeType();
5035 llvm::APInt Size(Context.getTypeSize(SizeType),
5036 Context.getTypeSizeInChars(BaseType).getQuantity());
5037 for (const ConstantArrayType *Array
5038 = Context.getAsConstantArrayType(FieldType);
5039 Array;
5040 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5041 llvm::APInt ArraySize = Array->getSize();
5042 ArraySize.zextOrTrunc(Size.getBitWidth());
5043 Size *= ArraySize;
5044 }
5045
5046 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005047 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5048 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005049
5050 bool NeedsCollectableMemCpy =
5051 (BaseType->isRecordType() &&
5052 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5053
5054 if (NeedsCollectableMemCpy) {
5055 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005056 // Create a reference to the __builtin_objc_memmove_collectable function.
5057 LookupResult R(*this,
5058 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005059 Loc, LookupOrdinaryName);
5060 LookupName(R, TUScope, true);
5061
5062 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5063 if (!CollectableMemCpy) {
5064 // Something went horribly wrong earlier, and we will have
5065 // complained about it.
5066 Invalid = true;
5067 continue;
5068 }
5069
5070 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5071 CollectableMemCpy->getType(),
5072 Loc, 0).takeAs<Expr>();
5073 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5074 }
5075 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005076 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005077 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005078 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5079 LookupOrdinaryName);
5080 LookupName(R, TUScope, true);
5081
5082 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5083 if (!BuiltinMemCpy) {
5084 // Something went horribly wrong earlier, and we will have complained
5085 // about it.
5086 Invalid = true;
5087 continue;
5088 }
5089
5090 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5091 BuiltinMemCpy->getType(),
5092 Loc, 0).takeAs<Expr>();
5093 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5094 }
5095
John McCallca0408f2010-08-23 06:44:23 +00005096 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005097 CallArgs.push_back(To.takeAs<Expr>());
5098 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005099 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005100 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005101 if (NeedsCollectableMemCpy)
5102 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005103 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005104 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005105 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005106 else
5107 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005108 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005109 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005110 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005111
Douglas Gregor06a9f362010-05-01 20:49:11 +00005112 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5113 Statements.push_back(Call.takeAs<Expr>());
5114 continue;
5115 }
5116
5117 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005118 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005119 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005120 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005121 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005122 Diag(CurrentLocation, diag::note_member_synthesized_at)
5123 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5124 CopyAssignOperator->setInvalidDecl();
5125 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005126 }
5127
5128 // Success! Record the copy.
5129 Statements.push_back(Copy.takeAs<Stmt>());
5130 }
5131
5132 if (!Invalid) {
5133 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005134 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005135
John McCall60d7b3a2010-08-24 06:29:42 +00005136 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005137 if (Return.isInvalid())
5138 Invalid = true;
5139 else {
5140 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005141
5142 if (Trap.hasErrorOccurred()) {
5143 Diag(CurrentLocation, diag::note_member_synthesized_at)
5144 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5145 Invalid = true;
5146 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005147 }
5148 }
5149
5150 if (Invalid) {
5151 CopyAssignOperator->setInvalidDecl();
5152 return;
5153 }
5154
John McCall60d7b3a2010-08-24 06:29:42 +00005155 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005156 /*isStmtExpr=*/false);
5157 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5158 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005159}
5160
Douglas Gregor23c94db2010-07-02 17:43:08 +00005161CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5162 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005163 // C++ [class.copy]p4:
5164 // If the class definition does not explicitly declare a copy
5165 // constructor, one is declared implicitly.
5166
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005167 // C++ [class.copy]p5:
5168 // The implicitly-declared copy constructor for a class X will
5169 // have the form
5170 //
5171 // X::X(const X&)
5172 //
5173 // if
5174 bool HasConstCopyConstructor = true;
5175
5176 // -- each direct or virtual base class B of X has a copy
5177 // constructor whose first parameter is of type const B& or
5178 // const volatile B&, and
5179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5180 BaseEnd = ClassDecl->bases_end();
5181 HasConstCopyConstructor && Base != BaseEnd;
5182 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005183 // Virtual bases are handled below.
5184 if (Base->isVirtual())
5185 continue;
5186
Douglas Gregor22584312010-07-02 23:41:54 +00005187 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005188 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005189 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5190 DeclareImplicitCopyConstructor(BaseClassDecl);
5191
Douglas Gregor598a8542010-07-01 18:27:03 +00005192 HasConstCopyConstructor
5193 = BaseClassDecl->hasConstCopyConstructor(Context);
5194 }
5195
5196 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5197 BaseEnd = ClassDecl->vbases_end();
5198 HasConstCopyConstructor && Base != BaseEnd;
5199 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005200 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005201 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005202 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5203 DeclareImplicitCopyConstructor(BaseClassDecl);
5204
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005205 HasConstCopyConstructor
5206 = BaseClassDecl->hasConstCopyConstructor(Context);
5207 }
5208
5209 // -- for all the nonstatic data members of X that are of a
5210 // class type M (or array thereof), each such class type
5211 // has a copy constructor whose first parameter is of type
5212 // const M& or const volatile M&.
5213 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5214 FieldEnd = ClassDecl->field_end();
5215 HasConstCopyConstructor && Field != FieldEnd;
5216 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005217 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005218 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005219 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005220 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005221 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5222 DeclareImplicitCopyConstructor(FieldClassDecl);
5223
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005224 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005225 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005226 }
5227 }
5228
5229 // Otherwise, the implicitly declared copy constructor will have
5230 // the form
5231 //
5232 // X::X(X&)
5233 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5234 QualType ArgType = ClassType;
5235 if (HasConstCopyConstructor)
5236 ArgType = ArgType.withConst();
5237 ArgType = Context.getLValueReferenceType(ArgType);
5238
Douglas Gregor0d405db2010-07-01 20:59:04 +00005239 // C++ [except.spec]p14:
5240 // An implicitly declared special member function (Clause 12) shall have an
5241 // exception-specification. [...]
5242 ImplicitExceptionSpecification ExceptSpec(Context);
5243 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5244 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5245 BaseEnd = ClassDecl->bases_end();
5246 Base != BaseEnd;
5247 ++Base) {
5248 // Virtual bases are handled below.
5249 if (Base->isVirtual())
5250 continue;
5251
Douglas Gregor22584312010-07-02 23:41:54 +00005252 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005253 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005254 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5255 DeclareImplicitCopyConstructor(BaseClassDecl);
5256
Douglas Gregor0d405db2010-07-01 20:59:04 +00005257 if (CXXConstructorDecl *CopyConstructor
5258 = BaseClassDecl->getCopyConstructor(Context, Quals))
5259 ExceptSpec.CalledDecl(CopyConstructor);
5260 }
5261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5262 BaseEnd = ClassDecl->vbases_end();
5263 Base != BaseEnd;
5264 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005265 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005266 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005267 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5268 DeclareImplicitCopyConstructor(BaseClassDecl);
5269
Douglas Gregor0d405db2010-07-01 20:59:04 +00005270 if (CXXConstructorDecl *CopyConstructor
5271 = BaseClassDecl->getCopyConstructor(Context, Quals))
5272 ExceptSpec.CalledDecl(CopyConstructor);
5273 }
5274 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5275 FieldEnd = ClassDecl->field_end();
5276 Field != FieldEnd;
5277 ++Field) {
5278 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5279 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005280 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005281 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005282 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5283 DeclareImplicitCopyConstructor(FieldClassDecl);
5284
Douglas Gregor0d405db2010-07-01 20:59:04 +00005285 if (CXXConstructorDecl *CopyConstructor
5286 = FieldClassDecl->getCopyConstructor(Context, Quals))
5287 ExceptSpec.CalledDecl(CopyConstructor);
5288 }
5289 }
5290
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005291 // An implicitly-declared copy constructor is an inline public
5292 // member of its class.
5293 DeclarationName Name
5294 = Context.DeclarationNames.getCXXConstructorName(
5295 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005296 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005297 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005298 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005299 Context.getFunctionType(Context.VoidTy,
5300 &ArgType, 1,
5301 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005302 ExceptSpec.hasExceptionSpecification(),
5303 ExceptSpec.hasAnyExceptionSpecification(),
5304 ExceptSpec.size(),
5305 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005306 FunctionType::ExtInfo()),
5307 /*TInfo=*/0,
5308 /*isExplicit=*/false,
5309 /*isInline=*/true,
5310 /*isImplicitlyDeclared=*/true);
5311 CopyConstructor->setAccess(AS_public);
5312 CopyConstructor->setImplicit();
5313 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5314
Douglas Gregor22584312010-07-02 23:41:54 +00005315 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005316 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5317
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005318 // Add the parameter to the constructor.
5319 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5320 ClassDecl->getLocation(),
5321 /*IdentifierInfo=*/0,
5322 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005323 SC_None,
5324 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005325 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005326 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005327 PushOnScopeChains(CopyConstructor, S, false);
5328 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005329
5330 return CopyConstructor;
5331}
5332
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005333void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5334 CXXConstructorDecl *CopyConstructor,
5335 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005336 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005337 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005338 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005339 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005340
Anders Carlsson63010a72010-04-23 16:24:12 +00005341 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005342 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005343
Douglas Gregor39957dc2010-05-01 15:04:51 +00005344 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005345 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005346
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005347 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5348 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005349 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005350 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005351 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005352 } else {
5353 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5354 CopyConstructor->getLocation(),
5355 MultiStmtArg(*this, 0, 0),
5356 /*isStmtExpr=*/false)
5357 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005358 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005359
5360 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005361}
5362
John McCall60d7b3a2010-08-24 06:29:42 +00005363ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005364Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005365 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005366 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005367 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005368 unsigned ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005369 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Douglas Gregor2f599792010-04-02 18:24:57 +00005371 // C++0x [class.copy]p34:
5372 // When certain criteria are met, an implementation is allowed to
5373 // omit the copy/move construction of a class object, even if the
5374 // copy/move constructor and/or destructor for the object have
5375 // side effects. [...]
5376 // - when a temporary class object that has not been bound to a
5377 // reference (12.2) would be copied/moved to a class object
5378 // with the same cv-unqualified type, the copy/move operation
5379 // can be omitted by constructing the temporary object
5380 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005381 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5382 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005383 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005384 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005385 }
Mike Stump1eb44332009-09-09 15:08:12 +00005386
5387 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005388 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005389 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005390}
5391
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005392/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5393/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005394ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005395Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5396 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005397 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005398 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005399 unsigned ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005400 unsigned NumExprs = ExprArgs.size();
5401 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005402
Douglas Gregor7edfb692009-11-23 12:27:39 +00005403 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005404 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005405 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005406 RequiresZeroInit,
5407 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005408}
5409
Mike Stump1eb44332009-09-09 15:08:12 +00005410bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005411 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005412 MultiExprArg Exprs) {
John McCall60d7b3a2010-08-24 06:29:42 +00005413 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005414 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005415 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonfe2de492009-08-25 05:18:00 +00005416 if (TempResult.isInvalid())
5417 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005418
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005419 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005420 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005421 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00005422 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005423 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Anders Carlssonfe2de492009-08-25 05:18:00 +00005425 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005426}
5427
John McCall68c6c9a2010-02-02 09:10:11 +00005428void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5429 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005430 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005431 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005432 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005433 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005434 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005435 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005436 << VD->getDeclName()
5437 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005438
John McCallae792222010-09-18 05:25:11 +00005439 // TODO: this should be re-enabled for static locals by !CXAAtExit
5440 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005441 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005442 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005443}
5444
Mike Stump1eb44332009-09-09 15:08:12 +00005445/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005446/// ActOnDeclarator, when a C++ direct initializer is present.
5447/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005448void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005449 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005450 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005451 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005452 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005453
5454 // If there is no declaration, there was an error parsing it. Just ignore
5455 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005456 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005457 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005458
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005459 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5460 if (!VDecl) {
5461 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5462 RealDecl->setInvalidDecl();
5463 return;
5464 }
5465
Douglas Gregor83ddad32009-08-26 21:14:46 +00005466 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005467 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005468 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5469 //
5470 // Clients that want to distinguish between the two forms, can check for
5471 // direct initializer using VarDecl::hasCXXDirectInitializer().
5472 // A major benefit is that clients that don't particularly care about which
5473 // exactly form was it (like the CodeGen) can handle both cases without
5474 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005475
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005476 // C++ 8.5p11:
5477 // The form of initialization (using parentheses or '=') is generally
5478 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005479 // class type.
5480
Douglas Gregor4dffad62010-02-11 22:55:30 +00005481 if (!VDecl->getType()->isDependentType() &&
5482 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005483 diag::err_typecheck_decl_incomplete_type)) {
5484 VDecl->setInvalidDecl();
5485 return;
5486 }
5487
Douglas Gregor90f93822009-12-22 22:17:25 +00005488 // The variable can not have an abstract class type.
5489 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5490 diag::err_abstract_type_in_decl,
5491 AbstractVariableType))
5492 VDecl->setInvalidDecl();
5493
Sebastian Redl31310a22010-02-01 20:16:42 +00005494 const VarDecl *Def;
5495 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005496 Diag(VDecl->getLocation(), diag::err_redefinition)
5497 << VDecl->getDeclName();
5498 Diag(Def->getLocation(), diag::note_previous_definition);
5499 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005500 return;
5501 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005502
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005503 // C++ [class.static.data]p4
5504 // If a static data member is of const integral or const
5505 // enumeration type, its declaration in the class definition can
5506 // specify a constant-initializer which shall be an integral
5507 // constant expression (5.19). In that case, the member can appear
5508 // in integral constant expressions. The member shall still be
5509 // defined in a namespace scope if it is used in the program and the
5510 // namespace scope definition shall not contain an initializer.
5511 //
5512 // We already performed a redefinition check above, but for static
5513 // data members we also need to check whether there was an in-class
5514 // declaration with an initializer.
5515 const VarDecl* PrevInit = 0;
5516 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5517 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5518 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5519 return;
5520 }
5521
Douglas Gregor4dffad62010-02-11 22:55:30 +00005522 // If either the declaration has a dependent type or if any of the
5523 // expressions is type-dependent, we represent the initialization
5524 // via a ParenListExpr for later use during template instantiation.
5525 if (VDecl->getType()->isDependentType() ||
5526 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5527 // Let clients know that initialization was done with a direct initializer.
5528 VDecl->setCXXDirectInitializer(true);
5529
5530 // Store the initialization expressions as a ParenListExpr.
5531 unsigned NumExprs = Exprs.size();
5532 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5533 (Expr **)Exprs.release(),
5534 NumExprs, RParenLoc));
5535 return;
5536 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005537
5538 // Capture the variable that is being initialized and the style of
5539 // initialization.
5540 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5541
5542 // FIXME: Poor source location information.
5543 InitializationKind Kind
5544 = InitializationKind::CreateDirect(VDecl->getLocation(),
5545 LParenLoc, RParenLoc);
5546
5547 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005548 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005549 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005550 if (Result.isInvalid()) {
5551 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005552 return;
5553 }
John McCallb4eb64d2010-10-08 02:01:28 +00005554
5555 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005556
John McCall9ae2f072010-08-23 23:25:46 +00005557 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregor838db382010-02-11 01:19:42 +00005558 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005559 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005560
John McCall4204f072010-08-02 21:13:48 +00005561 if (!VDecl->isInvalidDecl() &&
5562 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005563 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005564 !VDecl->getInit()->isConstantInitializer(Context,
5565 VDecl->getType()->isReferenceType()))
5566 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5567 << VDecl->getInit()->getSourceRange();
5568
John McCall68c6c9a2010-02-02 09:10:11 +00005569 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5570 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005571}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005572
Douglas Gregor39da0b82009-09-09 23:08:42 +00005573/// \brief Given a constructor and the set of arguments provided for the
5574/// constructor, convert the arguments and add any required default arguments
5575/// to form a proper call to this constructor.
5576///
5577/// \returns true if an error occurred, false otherwise.
5578bool
5579Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5580 MultiExprArg ArgsPtr,
5581 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005582 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005583 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5584 unsigned NumArgs = ArgsPtr.size();
5585 Expr **Args = (Expr **)ArgsPtr.get();
5586
5587 const FunctionProtoType *Proto
5588 = Constructor->getType()->getAs<FunctionProtoType>();
5589 assert(Proto && "Constructor without a prototype?");
5590 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005591
5592 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005593 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005594 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005595 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005596 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005597
5598 VariadicCallType CallType =
5599 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5600 llvm::SmallVector<Expr *, 8> AllArgs;
5601 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5602 Proto, 0, Args, NumArgs, AllArgs,
5603 CallType);
5604 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5605 ConvertedArgs.push_back(AllArgs[i]);
5606 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005607}
5608
Anders Carlsson20d45d22009-12-12 00:32:00 +00005609static inline bool
5610CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5611 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005612 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005613 if (isa<NamespaceDecl>(DC)) {
5614 return SemaRef.Diag(FnDecl->getLocation(),
5615 diag::err_operator_new_delete_declared_in_namespace)
5616 << FnDecl->getDeclName();
5617 }
5618
5619 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005620 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005621 return SemaRef.Diag(FnDecl->getLocation(),
5622 diag::err_operator_new_delete_declared_static)
5623 << FnDecl->getDeclName();
5624 }
5625
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005626 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005627}
5628
Anders Carlsson156c78e2009-12-13 17:53:43 +00005629static inline bool
5630CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5631 CanQualType ExpectedResultType,
5632 CanQualType ExpectedFirstParamType,
5633 unsigned DependentParamTypeDiag,
5634 unsigned InvalidParamTypeDiag) {
5635 QualType ResultType =
5636 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5637
5638 // Check that the result type is not dependent.
5639 if (ResultType->isDependentType())
5640 return SemaRef.Diag(FnDecl->getLocation(),
5641 diag::err_operator_new_delete_dependent_result_type)
5642 << FnDecl->getDeclName() << ExpectedResultType;
5643
5644 // Check that the result type is what we expect.
5645 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5646 return SemaRef.Diag(FnDecl->getLocation(),
5647 diag::err_operator_new_delete_invalid_result_type)
5648 << FnDecl->getDeclName() << ExpectedResultType;
5649
5650 // A function template must have at least 2 parameters.
5651 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5652 return SemaRef.Diag(FnDecl->getLocation(),
5653 diag::err_operator_new_delete_template_too_few_parameters)
5654 << FnDecl->getDeclName();
5655
5656 // The function decl must have at least 1 parameter.
5657 if (FnDecl->getNumParams() == 0)
5658 return SemaRef.Diag(FnDecl->getLocation(),
5659 diag::err_operator_new_delete_too_few_parameters)
5660 << FnDecl->getDeclName();
5661
5662 // Check the the first parameter type is not dependent.
5663 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5664 if (FirstParamType->isDependentType())
5665 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5666 << FnDecl->getDeclName() << ExpectedFirstParamType;
5667
5668 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005669 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005670 ExpectedFirstParamType)
5671 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5672 << FnDecl->getDeclName() << ExpectedFirstParamType;
5673
5674 return false;
5675}
5676
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005677static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005678CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005679 // C++ [basic.stc.dynamic.allocation]p1:
5680 // A program is ill-formed if an allocation function is declared in a
5681 // namespace scope other than global scope or declared static in global
5682 // scope.
5683 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5684 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005685
5686 CanQualType SizeTy =
5687 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5688
5689 // C++ [basic.stc.dynamic.allocation]p1:
5690 // The return type shall be void*. The first parameter shall have type
5691 // std::size_t.
5692 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5693 SizeTy,
5694 diag::err_operator_new_dependent_param_type,
5695 diag::err_operator_new_param_type))
5696 return true;
5697
5698 // C++ [basic.stc.dynamic.allocation]p1:
5699 // The first parameter shall not have an associated default argument.
5700 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005701 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005702 diag::err_operator_new_default_arg)
5703 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5704
5705 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005706}
5707
5708static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005709CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5710 // C++ [basic.stc.dynamic.deallocation]p1:
5711 // A program is ill-formed if deallocation functions are declared in a
5712 // namespace scope other than global scope or declared static in global
5713 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005714 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5715 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005716
5717 // C++ [basic.stc.dynamic.deallocation]p2:
5718 // Each deallocation function shall return void and its first parameter
5719 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005720 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5721 SemaRef.Context.VoidPtrTy,
5722 diag::err_operator_delete_dependent_param_type,
5723 diag::err_operator_delete_param_type))
5724 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005725
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005726 return false;
5727}
5728
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005729/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5730/// of this overloaded operator is well-formed. If so, returns false;
5731/// otherwise, emits appropriate diagnostics and returns true.
5732bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005733 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005734 "Expected an overloaded operator declaration");
5735
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005736 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5737
Mike Stump1eb44332009-09-09 15:08:12 +00005738 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005739 // The allocation and deallocation functions, operator new,
5740 // operator new[], operator delete and operator delete[], are
5741 // described completely in 3.7.3. The attributes and restrictions
5742 // found in the rest of this subclause do not apply to them unless
5743 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005744 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005745 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005746
Anders Carlssona3ccda52009-12-12 00:26:23 +00005747 if (Op == OO_New || Op == OO_Array_New)
5748 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005749
5750 // C++ [over.oper]p6:
5751 // An operator function shall either be a non-static member
5752 // function or be a non-member function and have at least one
5753 // parameter whose type is a class, a reference to a class, an
5754 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005755 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5756 if (MethodDecl->isStatic())
5757 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005758 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005759 } else {
5760 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005761 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5762 ParamEnd = FnDecl->param_end();
5763 Param != ParamEnd; ++Param) {
5764 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005765 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5766 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005767 ClassOrEnumParam = true;
5768 break;
5769 }
5770 }
5771
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005772 if (!ClassOrEnumParam)
5773 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005774 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005775 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005776 }
5777
5778 // C++ [over.oper]p8:
5779 // An operator function cannot have default arguments (8.3.6),
5780 // except where explicitly stated below.
5781 //
Mike Stump1eb44332009-09-09 15:08:12 +00005782 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005783 // (C++ [over.call]p1).
5784 if (Op != OO_Call) {
5785 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5786 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005787 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005788 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005789 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005790 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005791 }
5792 }
5793
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005794 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5795 { false, false, false }
5796#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5797 , { Unary, Binary, MemberOnly }
5798#include "clang/Basic/OperatorKinds.def"
5799 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005800
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005801 bool CanBeUnaryOperator = OperatorUses[Op][0];
5802 bool CanBeBinaryOperator = OperatorUses[Op][1];
5803 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005804
5805 // C++ [over.oper]p8:
5806 // [...] Operator functions cannot have more or fewer parameters
5807 // than the number required for the corresponding operator, as
5808 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005809 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005810 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005811 if (Op != OO_Call &&
5812 ((NumParams == 1 && !CanBeUnaryOperator) ||
5813 (NumParams == 2 && !CanBeBinaryOperator) ||
5814 (NumParams < 1) || (NumParams > 2))) {
5815 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005816 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005817 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005818 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005819 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005820 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005821 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005822 assert(CanBeBinaryOperator &&
5823 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005824 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005825 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005826
Chris Lattner416e46f2008-11-21 07:57:12 +00005827 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005828 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005829 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005830
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005831 // Overloaded operators other than operator() cannot be variadic.
5832 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005833 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005834 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005835 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005836 }
5837
5838 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005839 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5840 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005841 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005842 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005843 }
5844
5845 // C++ [over.inc]p1:
5846 // The user-defined function called operator++ implements the
5847 // prefix and postfix ++ operator. If this function is a member
5848 // function with no parameters, or a non-member function with one
5849 // parameter of class or enumeration type, it defines the prefix
5850 // increment operator ++ for objects of that type. If the function
5851 // is a member function with one parameter (which shall be of type
5852 // int) or a non-member function with two parameters (the second
5853 // of which shall be of type int), it defines the postfix
5854 // increment operator ++ for objects of that type.
5855 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5856 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5857 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005858 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005859 ParamIsInt = BT->getKind() == BuiltinType::Int;
5860
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005861 if (!ParamIsInt)
5862 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005863 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005864 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005865 }
5866
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005867 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005868}
Chris Lattner5a003a42008-12-17 07:09:26 +00005869
Sean Hunta6c058d2010-01-13 09:01:02 +00005870/// CheckLiteralOperatorDeclaration - Check whether the declaration
5871/// of this literal operator function is well-formed. If so, returns
5872/// false; otherwise, emits appropriate diagnostics and returns true.
5873bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5874 DeclContext *DC = FnDecl->getDeclContext();
5875 Decl::Kind Kind = DC->getDeclKind();
5876 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5877 Kind != Decl::LinkageSpec) {
5878 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5879 << FnDecl->getDeclName();
5880 return true;
5881 }
5882
5883 bool Valid = false;
5884
Sean Hunt216c2782010-04-07 23:11:06 +00005885 // template <char...> type operator "" name() is the only valid template
5886 // signature, and the only valid signature with no parameters.
5887 if (FnDecl->param_size() == 0) {
5888 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5889 // Must have only one template parameter
5890 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5891 if (Params->size() == 1) {
5892 NonTypeTemplateParmDecl *PmDecl =
5893 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005894
Sean Hunt216c2782010-04-07 23:11:06 +00005895 // The template parameter must be a char parameter pack.
5896 // FIXME: This test will always fail because non-type parameter packs
5897 // have not been implemented.
5898 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5899 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5900 Valid = true;
5901 }
5902 }
5903 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005904 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005905 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5906
Sean Hunta6c058d2010-01-13 09:01:02 +00005907 QualType T = (*Param)->getType();
5908
Sean Hunt30019c02010-04-07 22:57:35 +00005909 // unsigned long long int, long double, and any character type are allowed
5910 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005911 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5912 Context.hasSameType(T, Context.LongDoubleTy) ||
5913 Context.hasSameType(T, Context.CharTy) ||
5914 Context.hasSameType(T, Context.WCharTy) ||
5915 Context.hasSameType(T, Context.Char16Ty) ||
5916 Context.hasSameType(T, Context.Char32Ty)) {
5917 if (++Param == FnDecl->param_end())
5918 Valid = true;
5919 goto FinishedParams;
5920 }
5921
Sean Hunt30019c02010-04-07 22:57:35 +00005922 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005923 const PointerType *PT = T->getAs<PointerType>();
5924 if (!PT)
5925 goto FinishedParams;
5926 T = PT->getPointeeType();
5927 if (!T.isConstQualified())
5928 goto FinishedParams;
5929 T = T.getUnqualifiedType();
5930
5931 // Move on to the second parameter;
5932 ++Param;
5933
5934 // If there is no second parameter, the first must be a const char *
5935 if (Param == FnDecl->param_end()) {
5936 if (Context.hasSameType(T, Context.CharTy))
5937 Valid = true;
5938 goto FinishedParams;
5939 }
5940
5941 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5942 // are allowed as the first parameter to a two-parameter function
5943 if (!(Context.hasSameType(T, Context.CharTy) ||
5944 Context.hasSameType(T, Context.WCharTy) ||
5945 Context.hasSameType(T, Context.Char16Ty) ||
5946 Context.hasSameType(T, Context.Char32Ty)))
5947 goto FinishedParams;
5948
5949 // The second and final parameter must be an std::size_t
5950 T = (*Param)->getType().getUnqualifiedType();
5951 if (Context.hasSameType(T, Context.getSizeType()) &&
5952 ++Param == FnDecl->param_end())
5953 Valid = true;
5954 }
5955
5956 // FIXME: This diagnostic is absolutely terrible.
5957FinishedParams:
5958 if (!Valid) {
5959 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5960 << FnDecl->getDeclName();
5961 return true;
5962 }
5963
5964 return false;
5965}
5966
Douglas Gregor074149e2009-01-05 19:45:36 +00005967/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5968/// linkage specification, including the language and (if present)
5969/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5970/// the location of the language string literal, which is provided
5971/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5972/// the '{' brace. Otherwise, this linkage specification does not
5973/// have any braces.
John McCalld226f652010-08-21 09:40:31 +00005974Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005975 SourceLocation ExternLoc,
5976 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00005977 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005978 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005979 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005980 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005981 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005982 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005983 Language = LinkageSpecDecl::lang_cxx;
5984 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005985 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00005986 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005987 }
Mike Stump1eb44332009-09-09 15:08:12 +00005988
Chris Lattnercc98eac2008-12-17 07:13:27 +00005989 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005990
Douglas Gregor074149e2009-01-05 19:45:36 +00005991 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005992 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005993 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005994 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005995 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00005996 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005997}
5998
Abramo Bagnara35f9a192010-07-30 16:47:02 +00005999/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006000/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6001/// valid, it's the position of the closing '}' brace in a linkage
6002/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006003Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6004 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006005 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006006 if (LinkageSpec)
6007 PopDeclContext();
6008 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006009}
6010
Douglas Gregord308e622009-05-18 20:51:54 +00006011/// \brief Perform semantic analysis for the variable declaration that
6012/// occurs within a C++ catch clause, returning the newly-created
6013/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006014VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006015 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006016 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006017 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006018 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006019 QualType ExDeclType = TInfo->getType();
6020
Sebastian Redl4b07b292008-12-22 19:15:10 +00006021 // Arrays and functions decay.
6022 if (ExDeclType->isArrayType())
6023 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6024 else if (ExDeclType->isFunctionType())
6025 ExDeclType = Context.getPointerType(ExDeclType);
6026
6027 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6028 // The exception-declaration shall not denote a pointer or reference to an
6029 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006030 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006031 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006032 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006033 Invalid = true;
6034 }
Douglas Gregord308e622009-05-18 20:51:54 +00006035
Douglas Gregora2762912010-03-08 01:47:36 +00006036 // GCC allows catching pointers and references to incomplete types
6037 // as an extension; so do we, but we warn by default.
6038
Sebastian Redl4b07b292008-12-22 19:15:10 +00006039 QualType BaseType = ExDeclType;
6040 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006041 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006042 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006043 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006044 BaseType = Ptr->getPointeeType();
6045 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006046 DK = diag::ext_catch_incomplete_ptr;
6047 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006048 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006049 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006050 BaseType = Ref->getPointeeType();
6051 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006052 DK = diag::ext_catch_incomplete_ref;
6053 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006054 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006055 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006056 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6057 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006058 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006059
Mike Stump1eb44332009-09-09 15:08:12 +00006060 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006061 RequireNonAbstractType(Loc, ExDeclType,
6062 diag::err_abstract_type_in_decl,
6063 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006064 Invalid = true;
6065
John McCall5a180392010-07-24 00:37:23 +00006066 // Only the non-fragile NeXT runtime currently supports C++ catches
6067 // of ObjC types, and no runtime supports catching ObjC types by value.
6068 if (!Invalid && getLangOptions().ObjC1) {
6069 QualType T = ExDeclType;
6070 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6071 T = RT->getPointeeType();
6072
6073 if (T->isObjCObjectType()) {
6074 Diag(Loc, diag::err_objc_object_catch);
6075 Invalid = true;
6076 } else if (T->isObjCObjectPointerType()) {
6077 if (!getLangOptions().NeXTRuntime) {
6078 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6079 Invalid = true;
6080 } else if (!getLangOptions().ObjCNonFragileABI) {
6081 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6082 Invalid = true;
6083 }
6084 }
6085 }
6086
Mike Stump1eb44332009-09-09 15:08:12 +00006087 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006088 Name, ExDeclType, TInfo, SC_None,
6089 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006090 ExDecl->setExceptionVariable(true);
6091
Douglas Gregor6d182892010-03-05 23:38:39 +00006092 if (!Invalid) {
6093 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6094 // C++ [except.handle]p16:
6095 // The object declared in an exception-declaration or, if the
6096 // exception-declaration does not specify a name, a temporary (12.2) is
6097 // copy-initialized (8.5) from the exception object. [...]
6098 // The object is destroyed when the handler exits, after the destruction
6099 // of any automatic objects initialized within the handler.
6100 //
6101 // We just pretend to initialize the object with itself, then make sure
6102 // it can be destroyed later.
6103 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6104 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6105 Loc, ExDeclType, 0);
6106 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6107 SourceLocation());
6108 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006109 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006110 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006111 if (Result.isInvalid())
6112 Invalid = true;
6113 else
6114 FinalizeVarWithDestructor(ExDecl, RecordTy);
6115 }
6116 }
6117
Douglas Gregord308e622009-05-18 20:51:54 +00006118 if (Invalid)
6119 ExDecl->setInvalidDecl();
6120
6121 return ExDecl;
6122}
6123
6124/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6125/// handler.
John McCalld226f652010-08-21 09:40:31 +00006126Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006127 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6128 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006129
6130 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006131 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006132 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006133 LookupOrdinaryName,
6134 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006135 // The scope should be freshly made just for us. There is just no way
6136 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006137 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006138 if (PrevDecl->isTemplateParameter()) {
6139 // Maybe we will complain about the shadowed template parameter.
6140 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006141 }
6142 }
6143
Chris Lattnereaaebc72009-04-25 08:06:05 +00006144 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006145 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6146 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006147 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006148 }
6149
Douglas Gregor83cb9422010-09-09 17:09:21 +00006150 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006151 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006152 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006153
Chris Lattnereaaebc72009-04-25 08:06:05 +00006154 if (Invalid)
6155 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006156
Sebastian Redl4b07b292008-12-22 19:15:10 +00006157 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006158 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006159 PushOnScopeChains(ExDecl, S);
6160 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006161 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006162
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006163 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006164 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006165}
Anders Carlssonfb311762009-03-14 00:25:26 +00006166
John McCalld226f652010-08-21 09:40:31 +00006167Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006168 Expr *AssertExpr,
6169 Expr *AssertMessageExpr_) {
6170 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006171
Anders Carlssonc3082412009-03-14 00:33:21 +00006172 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6173 llvm::APSInt Value(32);
6174 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6175 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6176 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006177 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006178 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006179
Anders Carlssonc3082412009-03-14 00:33:21 +00006180 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006181 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006182 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006183 }
6184 }
Mike Stump1eb44332009-09-09 15:08:12 +00006185
Mike Stump1eb44332009-09-09 15:08:12 +00006186 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006187 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006188
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006189 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006190 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006191}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006192
Douglas Gregor1d869352010-04-07 16:53:43 +00006193/// \brief Perform semantic analysis of the given friend type declaration.
6194///
6195/// \returns A friend declaration that.
6196FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6197 TypeSourceInfo *TSInfo) {
6198 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6199
6200 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006201 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006202
Douglas Gregor06245bf2010-04-07 17:57:12 +00006203 if (!getLangOptions().CPlusPlus0x) {
6204 // C++03 [class.friend]p2:
6205 // An elaborated-type-specifier shall be used in a friend declaration
6206 // for a class.*
6207 //
6208 // * The class-key of the elaborated-type-specifier is required.
6209 if (!ActiveTemplateInstantiations.empty()) {
6210 // Do not complain about the form of friend template types during
6211 // template instantiation; we will already have complained when the
6212 // template was declared.
6213 } else if (!T->isElaboratedTypeSpecifier()) {
6214 // If we evaluated the type to a record type, suggest putting
6215 // a tag in front.
6216 if (const RecordType *RT = T->getAs<RecordType>()) {
6217 RecordDecl *RD = RT->getDecl();
6218
6219 std::string InsertionText = std::string(" ") + RD->getKindName();
6220
6221 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6222 << (unsigned) RD->getTagKind()
6223 << T
6224 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6225 InsertionText);
6226 } else {
6227 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6228 << T
6229 << SourceRange(FriendLoc, TypeRange.getEnd());
6230 }
6231 } else if (T->getAs<EnumType>()) {
6232 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006233 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006234 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006235 }
6236 }
6237
Douglas Gregor06245bf2010-04-07 17:57:12 +00006238 // C++0x [class.friend]p3:
6239 // If the type specifier in a friend declaration designates a (possibly
6240 // cv-qualified) class type, that class is declared as a friend; otherwise,
6241 // the friend declaration is ignored.
6242
6243 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6244 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006245
6246 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6247}
6248
John McCall9a34edb2010-10-19 01:40:49 +00006249/// Handle a friend tag declaration where the scope specifier was
6250/// templated.
6251Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6252 unsigned TagSpec, SourceLocation TagLoc,
6253 CXXScopeSpec &SS,
6254 IdentifierInfo *Name, SourceLocation NameLoc,
6255 AttributeList *Attr,
6256 MultiTemplateParamsArg TempParamLists) {
6257 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6258
6259 bool isExplicitSpecialization = false;
6260 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6261 bool Invalid = false;
6262
6263 if (TemplateParameterList *TemplateParams
6264 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6265 TempParamLists.get(),
6266 TempParamLists.size(),
6267 /*friend*/ true,
6268 isExplicitSpecialization,
6269 Invalid)) {
6270 --NumMatchedTemplateParamLists;
6271
6272 if (TemplateParams->size() > 0) {
6273 // This is a declaration of a class template.
6274 if (Invalid)
6275 return 0;
6276
6277 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6278 SS, Name, NameLoc, Attr,
6279 TemplateParams, AS_public).take();
6280 } else {
6281 // The "template<>" header is extraneous.
6282 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6283 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6284 isExplicitSpecialization = true;
6285 }
6286 }
6287
6288 if (Invalid) return 0;
6289
6290 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6291
6292 bool isAllExplicitSpecializations = true;
6293 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6294 if (TempParamLists.get()[I]->size()) {
6295 isAllExplicitSpecializations = false;
6296 break;
6297 }
6298 }
6299
6300 // FIXME: don't ignore attributes.
6301
6302 // If it's explicit specializations all the way down, just forget
6303 // about the template header and build an appropriate non-templated
6304 // friend. TODO: for source fidelity, remember the headers.
6305 if (isAllExplicitSpecializations) {
6306 ElaboratedTypeKeyword Keyword
6307 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6308 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6309 TagLoc, SS.getRange(), NameLoc);
6310 if (T.isNull())
6311 return 0;
6312
6313 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6314 if (isa<DependentNameType>(T)) {
6315 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6316 TL.setKeywordLoc(TagLoc);
6317 TL.setQualifierRange(SS.getRange());
6318 TL.setNameLoc(NameLoc);
6319 } else {
6320 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6321 TL.setKeywordLoc(TagLoc);
6322 TL.setQualifierRange(SS.getRange());
6323 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6324 }
6325
6326 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6327 TSI, FriendLoc);
6328 Friend->setAccess(AS_public);
6329 CurContext->addDecl(Friend);
6330 return Friend;
6331 }
6332
6333 // Handle the case of a templated-scope friend class. e.g.
6334 // template <class T> class A<T>::B;
6335 // FIXME: we don't support these right now.
6336 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6337 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6338 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6339 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6340 TL.setKeywordLoc(TagLoc);
6341 TL.setQualifierRange(SS.getRange());
6342 TL.setNameLoc(NameLoc);
6343
6344 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6345 TSI, FriendLoc);
6346 Friend->setAccess(AS_public);
6347 Friend->setUnsupportedFriend(true);
6348 CurContext->addDecl(Friend);
6349 return Friend;
6350}
6351
6352
John McCalldd4a3b02009-09-16 22:47:08 +00006353/// Handle a friend type declaration. This works in tandem with
6354/// ActOnTag.
6355///
6356/// Notes on friend class templates:
6357///
6358/// We generally treat friend class declarations as if they were
6359/// declaring a class. So, for example, the elaborated type specifier
6360/// in a friend declaration is required to obey the restrictions of a
6361/// class-head (i.e. no typedefs in the scope chain), template
6362/// parameters are required to match up with simple template-ids, &c.
6363/// However, unlike when declaring a template specialization, it's
6364/// okay to refer to a template specialization without an empty
6365/// template parameter declaration, e.g.
6366/// friend class A<T>::B<unsigned>;
6367/// We permit this as a special case; if there are any template
6368/// parameters present at all, require proper matching, i.e.
6369/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006370Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006371 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006372 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006373
6374 assert(DS.isFriendSpecified());
6375 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6376
John McCalldd4a3b02009-09-16 22:47:08 +00006377 // Try to convert the decl specifier to a type. This works for
6378 // friend templates because ActOnTag never produces a ClassTemplateDecl
6379 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006380 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006381 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6382 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006383 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006384 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006385
John McCalldd4a3b02009-09-16 22:47:08 +00006386 // This is definitely an error in C++98. It's probably meant to
6387 // be forbidden in C++0x, too, but the specification is just
6388 // poorly written.
6389 //
6390 // The problem is with declarations like the following:
6391 // template <T> friend A<T>::foo;
6392 // where deciding whether a class C is a friend or not now hinges
6393 // on whether there exists an instantiation of A that causes
6394 // 'foo' to equal C. There are restrictions on class-heads
6395 // (which we declare (by fiat) elaborated friend declarations to
6396 // be) that makes this tractable.
6397 //
6398 // FIXME: handle "template <> friend class A<T>;", which
6399 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006400 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006401 Diag(Loc, diag::err_tagless_friend_type_template)
6402 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006403 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006404 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006405
John McCall02cace72009-08-28 07:59:38 +00006406 // C++98 [class.friend]p1: A friend of a class is a function
6407 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006408 // This is fixed in DR77, which just barely didn't make the C++03
6409 // deadline. It's also a very silly restriction that seriously
6410 // affects inner classes and which nobody else seems to implement;
6411 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006412 //
6413 // But note that we could warn about it: it's always useless to
6414 // friend one of your own members (it's not, however, worthless to
6415 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006416
John McCalldd4a3b02009-09-16 22:47:08 +00006417 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006418 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006419 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006420 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006421 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006422 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006423 DS.getFriendSpecLoc());
6424 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006425 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6426
6427 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006428 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006429
John McCalldd4a3b02009-09-16 22:47:08 +00006430 D->setAccess(AS_public);
6431 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006432
John McCalld226f652010-08-21 09:40:31 +00006433 return D;
John McCall02cace72009-08-28 07:59:38 +00006434}
6435
John McCall337ec3d2010-10-12 23:13:28 +00006436Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6437 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006438 const DeclSpec &DS = D.getDeclSpec();
6439
6440 assert(DS.isFriendSpecified());
6441 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6442
6443 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006444 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6445 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006446
6447 // C++ [class.friend]p1
6448 // A friend of a class is a function or class....
6449 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006450 // It *doesn't* see through dependent types, which is correct
6451 // according to [temp.arg.type]p3:
6452 // If a declaration acquires a function type through a
6453 // type dependent on a template-parameter and this causes
6454 // a declaration that does not use the syntactic form of a
6455 // function declarator to have a function type, the program
6456 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006457 if (!T->isFunctionType()) {
6458 Diag(Loc, diag::err_unexpected_friend);
6459
6460 // It might be worthwhile to try to recover by creating an
6461 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006462 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006463 }
6464
6465 // C++ [namespace.memdef]p3
6466 // - If a friend declaration in a non-local class first declares a
6467 // class or function, the friend class or function is a member
6468 // of the innermost enclosing namespace.
6469 // - The name of the friend is not found by simple name lookup
6470 // until a matching declaration is provided in that namespace
6471 // scope (either before or after the class declaration granting
6472 // friendship).
6473 // - If a friend function is called, its name may be found by the
6474 // name lookup that considers functions from namespaces and
6475 // classes associated with the types of the function arguments.
6476 // - When looking for a prior declaration of a class or a function
6477 // declared as a friend, scopes outside the innermost enclosing
6478 // namespace scope are not considered.
6479
John McCall337ec3d2010-10-12 23:13:28 +00006480 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006481 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6482 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006483 assert(Name);
6484
John McCall67d1a672009-08-06 02:15:43 +00006485 // The context we found the declaration in, or in which we should
6486 // create the declaration.
6487 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006488 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006489 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006490 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006491
John McCall337ec3d2010-10-12 23:13:28 +00006492 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006493
John McCall337ec3d2010-10-12 23:13:28 +00006494 // There are four cases here.
6495 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006496 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006497 // there as appropriate.
6498 // Recover from invalid scope qualifiers as if they just weren't there.
6499 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006500 // C++0x [namespace.memdef]p3:
6501 // If the name in a friend declaration is neither qualified nor
6502 // a template-id and the declaration is a function or an
6503 // elaborated-type-specifier, the lookup to determine whether
6504 // the entity has been previously declared shall not consider
6505 // any scopes outside the innermost enclosing namespace.
6506 // C++0x [class.friend]p11:
6507 // If a friend declaration appears in a local class and the name
6508 // specified is an unqualified name, a prior declaration is
6509 // looked up without considering scopes that are outside the
6510 // innermost enclosing non-class scope. For a friend function
6511 // declaration, if there is no prior declaration, the program is
6512 // ill-formed.
6513 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006514 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006515
John McCall29ae6e52010-10-13 05:45:15 +00006516 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006517 DC = CurContext;
6518 while (true) {
6519 // Skip class contexts. If someone can cite chapter and verse
6520 // for this behavior, that would be nice --- it's what GCC and
6521 // EDG do, and it seems like a reasonable intent, but the spec
6522 // really only says that checks for unqualified existing
6523 // declarations should stop at the nearest enclosing namespace,
6524 // not that they should only consider the nearest enclosing
6525 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006526 while (DC->isRecord())
6527 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006528
John McCall68263142009-11-18 22:49:29 +00006529 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006530
6531 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006532 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006533 break;
John McCall29ae6e52010-10-13 05:45:15 +00006534
John McCall8a407372010-10-14 22:22:28 +00006535 if (isTemplateId) {
6536 if (isa<TranslationUnitDecl>(DC)) break;
6537 } else {
6538 if (DC->isFileContext()) break;
6539 }
John McCall67d1a672009-08-06 02:15:43 +00006540 DC = DC->getParent();
6541 }
6542
6543 // C++ [class.friend]p1: A friend of a class is a function or
6544 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006545 // C++0x changes this for both friend types and functions.
6546 // Most C++ 98 compilers do seem to give an error here, so
6547 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006548 if (!Previous.empty() && DC->Equals(CurContext)
6549 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006550 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006551
John McCall380aaa42010-10-13 06:22:15 +00006552 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006553
John McCall337ec3d2010-10-12 23:13:28 +00006554 // - There's a non-dependent scope specifier, in which case we
6555 // compute it and do a previous lookup there for a function
6556 // or function template.
6557 } else if (!SS.getScopeRep()->isDependent()) {
6558 DC = computeDeclContext(SS);
6559 if (!DC) return 0;
6560
6561 if (RequireCompleteDeclContext(SS, DC)) return 0;
6562
6563 LookupQualifiedName(Previous, DC);
6564
6565 // Ignore things found implicitly in the wrong scope.
6566 // TODO: better diagnostics for this case. Suggesting the right
6567 // qualified scope would be nice...
6568 LookupResult::Filter F = Previous.makeFilter();
6569 while (F.hasNext()) {
6570 NamedDecl *D = F.next();
6571 if (!DC->InEnclosingNamespaceSetOf(
6572 D->getDeclContext()->getRedeclContext()))
6573 F.erase();
6574 }
6575 F.done();
6576
6577 if (Previous.empty()) {
6578 D.setInvalidType();
6579 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6580 return 0;
6581 }
6582
6583 // C++ [class.friend]p1: A friend of a class is a function or
6584 // class that is not a member of the class . . .
6585 if (DC->Equals(CurContext))
6586 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6587
6588 // - There's a scope specifier that does not match any template
6589 // parameter lists, in which case we use some arbitrary context,
6590 // create a method or method template, and wait for instantiation.
6591 // - There's a scope specifier that does match some template
6592 // parameter lists, which we don't handle right now.
6593 } else {
6594 DC = CurContext;
6595 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006596 }
6597
John McCall29ae6e52010-10-13 05:45:15 +00006598 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006599 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006600 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6601 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6602 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006603 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006604 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6605 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006606 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006607 }
John McCall67d1a672009-08-06 02:15:43 +00006608 }
6609
Douglas Gregor182ddf02009-09-28 00:08:27 +00006610 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006611 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006612 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006613 IsDefinition,
6614 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006615 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006616
Douglas Gregor182ddf02009-09-28 00:08:27 +00006617 assert(ND->getDeclContext() == DC);
6618 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006619
John McCallab88d972009-08-31 22:39:49 +00006620 // Add the function declaration to the appropriate lookup tables,
6621 // adjusting the redeclarations list as necessary. We don't
6622 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006623 //
John McCallab88d972009-08-31 22:39:49 +00006624 // Also update the scope-based lookup if the target context's
6625 // lookup context is in lexical scope.
6626 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006627 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006628 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006629 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006630 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006631 }
John McCall02cace72009-08-28 07:59:38 +00006632
6633 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006634 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006635 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006636 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006637 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006638
John McCall337ec3d2010-10-12 23:13:28 +00006639 if (ND->isInvalidDecl())
6640 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006641 else {
6642 FunctionDecl *FD;
6643 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6644 FD = FTD->getTemplatedDecl();
6645 else
6646 FD = cast<FunctionDecl>(ND);
6647
6648 // Mark templated-scope function declarations as unsupported.
6649 if (FD->getNumTemplateParameterLists())
6650 FrD->setUnsupportedFriend(true);
6651 }
John McCall337ec3d2010-10-12 23:13:28 +00006652
John McCalld226f652010-08-21 09:40:31 +00006653 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006654}
6655
John McCalld226f652010-08-21 09:40:31 +00006656void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6657 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006658
Sebastian Redl50de12f2009-03-24 22:27:57 +00006659 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6660 if (!Fn) {
6661 Diag(DelLoc, diag::err_deleted_non_function);
6662 return;
6663 }
6664 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6665 Diag(DelLoc, diag::err_deleted_decl_not_first);
6666 Diag(Prev->getLocation(), diag::note_previous_declaration);
6667 // If the declaration wasn't the first, we delete the function anyway for
6668 // recovery.
6669 }
6670 Fn->setDeleted();
6671}
Sebastian Redl13e88542009-04-27 21:33:24 +00006672
6673static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6674 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6675 ++CI) {
6676 Stmt *SubStmt = *CI;
6677 if (!SubStmt)
6678 continue;
6679 if (isa<ReturnStmt>(SubStmt))
6680 Self.Diag(SubStmt->getSourceRange().getBegin(),
6681 diag::err_return_in_constructor_handler);
6682 if (!isa<Expr>(SubStmt))
6683 SearchForReturnInStmt(Self, SubStmt);
6684 }
6685}
6686
6687void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6688 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6689 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6690 SearchForReturnInStmt(*this, Handler);
6691 }
6692}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006693
Mike Stump1eb44332009-09-09 15:08:12 +00006694bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006695 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006696 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6697 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006698
Chandler Carruth73857792010-02-15 11:53:20 +00006699 if (Context.hasSameType(NewTy, OldTy) ||
6700 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006701 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006702
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006703 // Check if the return types are covariant
6704 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006705
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006706 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006707 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6708 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006709 NewClassTy = NewPT->getPointeeType();
6710 OldClassTy = OldPT->getPointeeType();
6711 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006712 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6713 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6714 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6715 NewClassTy = NewRT->getPointeeType();
6716 OldClassTy = OldRT->getPointeeType();
6717 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006718 }
6719 }
Mike Stump1eb44332009-09-09 15:08:12 +00006720
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006721 // The return types aren't either both pointers or references to a class type.
6722 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006723 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006724 diag::err_different_return_type_for_overriding_virtual_function)
6725 << New->getDeclName() << NewTy << OldTy;
6726 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006727
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006728 return true;
6729 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006730
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006731 // C++ [class.virtual]p6:
6732 // If the return type of D::f differs from the return type of B::f, the
6733 // class type in the return type of D::f shall be complete at the point of
6734 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006735 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6736 if (!RT->isBeingDefined() &&
6737 RequireCompleteType(New->getLocation(), NewClassTy,
6738 PDiag(diag::err_covariant_return_incomplete)
6739 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006740 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006741 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006742
Douglas Gregora4923eb2009-11-16 21:35:15 +00006743 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006744 // Check if the new class derives from the old class.
6745 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6746 Diag(New->getLocation(),
6747 diag::err_covariant_return_not_derived)
6748 << New->getDeclName() << NewTy << OldTy;
6749 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6750 return true;
6751 }
Mike Stump1eb44332009-09-09 15:08:12 +00006752
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006753 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006754 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006755 diag::err_covariant_return_inaccessible_base,
6756 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6757 // FIXME: Should this point to the return type?
6758 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006759 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6760 return true;
6761 }
6762 }
Mike Stump1eb44332009-09-09 15:08:12 +00006763
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006764 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006765 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006766 Diag(New->getLocation(),
6767 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006768 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006769 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6770 return true;
6771 };
Mike Stump1eb44332009-09-09 15:08:12 +00006772
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006773
6774 // The new class type must have the same or less qualifiers as the old type.
6775 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6776 Diag(New->getLocation(),
6777 diag::err_covariant_return_type_class_type_more_qualified)
6778 << New->getDeclName() << NewTy << OldTy;
6779 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6780 return true;
6781 };
Mike Stump1eb44332009-09-09 15:08:12 +00006782
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006783 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006784}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006785
Sean Huntbbd37c62009-11-21 08:43:09 +00006786bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6787 const CXXMethodDecl *Old)
6788{
6789 if (Old->hasAttr<FinalAttr>()) {
6790 Diag(New->getLocation(), diag::err_final_function_overridden)
6791 << New->getDeclName();
6792 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6793 return true;
6794 }
6795
6796 return false;
6797}
6798
Douglas Gregor4ba31362009-12-01 17:24:26 +00006799/// \brief Mark the given method pure.
6800///
6801/// \param Method the method to be marked pure.
6802///
6803/// \param InitRange the source range that covers the "0" initializer.
6804bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6805 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6806 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006807 return false;
6808 }
6809
6810 if (!Method->isInvalidDecl())
6811 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6812 << Method->getDeclName() << InitRange;
6813 return true;
6814}
6815
John McCall731ad842009-12-19 09:28:58 +00006816/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6817/// an initializer for the out-of-line declaration 'Dcl'. The scope
6818/// is a fresh scope pushed for just this purpose.
6819///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006820/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6821/// static data member of class X, names should be looked up in the scope of
6822/// class X.
John McCalld226f652010-08-21 09:40:31 +00006823void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006824 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006825 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006826
John McCall731ad842009-12-19 09:28:58 +00006827 // We should only get called for declarations with scope specifiers, like:
6828 // int foo::bar;
6829 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006830 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006831}
6832
6833/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006834/// initializer for the out-of-line declaration 'D'.
6835void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006836 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006837 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006838
John McCall731ad842009-12-19 09:28:58 +00006839 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006840 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006841}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006842
6843/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6844/// C++ if/switch/while/for statement.
6845/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006846DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006847 // C++ 6.4p2:
6848 // The declarator shall not specify a function or an array.
6849 // The type-specifier-seq shall not contain typedef and shall not declare a
6850 // new class or enumeration.
6851 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6852 "Parser allowed 'typedef' as storage class of condition decl.");
6853
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006854 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006855 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6856 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006857
6858 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6859 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6860 // would be created and CXXConditionDeclExpr wants a VarDecl.
6861 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6862 << D.getSourceRange();
6863 return DeclResult();
6864 } else if (OwnedTag && OwnedTag->isDefinition()) {
6865 // The type-specifier-seq shall not declare a new class or enumeration.
6866 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6867 }
6868
John McCalld226f652010-08-21 09:40:31 +00006869 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006870 if (!Dcl)
6871 return DeclResult();
6872
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006873 return Dcl;
6874}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006875
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006876void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6877 bool DefinitionRequired) {
6878 // Ignore any vtable uses in unevaluated operands or for classes that do
6879 // not have a vtable.
6880 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6881 CurContext->isDependentContext() ||
6882 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006883 return;
6884
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006885 // Try to insert this class into the map.
6886 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6887 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6888 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6889 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006890 // If we already had an entry, check to see if we are promoting this vtable
6891 // to required a definition. If so, we need to reappend to the VTableUses
6892 // list, since we may have already processed the first entry.
6893 if (DefinitionRequired && !Pos.first->second) {
6894 Pos.first->second = true;
6895 } else {
6896 // Otherwise, we can early exit.
6897 return;
6898 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006899 }
6900
6901 // Local classes need to have their virtual members marked
6902 // immediately. For all other classes, we mark their virtual members
6903 // at the end of the translation unit.
6904 if (Class->isLocalClass())
6905 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006906 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006907 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006908}
6909
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006910bool Sema::DefineUsedVTables() {
6911 // If any dynamic classes have their key function defined within
6912 // this translation unit, then those vtables are considered "used" and must
6913 // be emitted.
6914 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6915 if (const CXXMethodDecl *KeyFunction
6916 = Context.getKeyFunction(DynamicClasses[I])) {
6917 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006918 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006919 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6920 }
6921 }
6922
6923 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006924 return false;
6925
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006926 // Note: The VTableUses vector could grow as a result of marking
6927 // the members of a class as "used", so we check the size each
6928 // time through the loop and prefer indices (with are stable) to
6929 // iterators (which are not).
6930 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006931 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006932 if (!Class)
6933 continue;
6934
6935 SourceLocation Loc = VTableUses[I].second;
6936
6937 // If this class has a key function, but that key function is
6938 // defined in another translation unit, we don't need to emit the
6939 // vtable even though we're using it.
6940 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006941 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006942 switch (KeyFunction->getTemplateSpecializationKind()) {
6943 case TSK_Undeclared:
6944 case TSK_ExplicitSpecialization:
6945 case TSK_ExplicitInstantiationDeclaration:
6946 // The key function is in another translation unit.
6947 continue;
6948
6949 case TSK_ExplicitInstantiationDefinition:
6950 case TSK_ImplicitInstantiation:
6951 // We will be instantiating the key function.
6952 break;
6953 }
6954 } else if (!KeyFunction) {
6955 // If we have a class with no key function that is the subject
6956 // of an explicit instantiation declaration, suppress the
6957 // vtable; it will live with the explicit instantiation
6958 // definition.
6959 bool IsExplicitInstantiationDeclaration
6960 = Class->getTemplateSpecializationKind()
6961 == TSK_ExplicitInstantiationDeclaration;
6962 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6963 REnd = Class->redecls_end();
6964 R != REnd; ++R) {
6965 TemplateSpecializationKind TSK
6966 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6967 if (TSK == TSK_ExplicitInstantiationDeclaration)
6968 IsExplicitInstantiationDeclaration = true;
6969 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6970 IsExplicitInstantiationDeclaration = false;
6971 break;
6972 }
6973 }
6974
6975 if (IsExplicitInstantiationDeclaration)
6976 continue;
6977 }
6978
6979 // Mark all of the virtual members of this class as referenced, so
6980 // that we can build a vtable. Then, tell the AST consumer that a
6981 // vtable for this class is required.
6982 MarkVirtualMembersReferenced(Loc, Class);
6983 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6984 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6985
6986 // Optionally warn if we're emitting a weak vtable.
6987 if (Class->getLinkage() == ExternalLinkage &&
6988 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006989 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006990 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6991 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006992 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006993 VTableUses.clear();
6994
Anders Carlssond6a637f2009-12-07 08:24:59 +00006995 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006996}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006997
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006998void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6999 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007000 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7001 e = RD->method_end(); i != e; ++i) {
7002 CXXMethodDecl *MD = *i;
7003
7004 // C++ [basic.def.odr]p2:
7005 // [...] A virtual member function is used if it is not pure. [...]
7006 if (MD->isVirtual() && !MD->isPure())
7007 MarkDeclarationReferenced(Loc, MD);
7008 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007009
7010 // Only classes that have virtual bases need a VTT.
7011 if (RD->getNumVBases() == 0)
7012 return;
7013
7014 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7015 e = RD->bases_end(); i != e; ++i) {
7016 const CXXRecordDecl *Base =
7017 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007018 if (Base->getNumVBases() == 0)
7019 continue;
7020 MarkVirtualMembersReferenced(Loc, Base);
7021 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007022}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007023
7024/// SetIvarInitializers - This routine builds initialization ASTs for the
7025/// Objective-C implementation whose ivars need be initialized.
7026void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7027 if (!getLangOptions().CPlusPlus)
7028 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007029 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007030 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7031 CollectIvarsToConstructOrDestruct(OID, ivars);
7032 if (ivars.empty())
7033 return;
7034 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7035 for (unsigned i = 0; i < ivars.size(); i++) {
7036 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007037 if (Field->isInvalidDecl())
7038 continue;
7039
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007040 CXXBaseOrMemberInitializer *Member;
7041 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7042 InitializationKind InitKind =
7043 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7044
7045 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007046 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007047 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00007048 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007049 // Note, MemberInit could actually come back empty if no initialization
7050 // is required (e.g., because it would call a trivial default constructor)
7051 if (!MemberInit.get() || MemberInit.isInvalid())
7052 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007053
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007054 Member =
7055 new (Context) CXXBaseOrMemberInitializer(Context,
7056 Field, SourceLocation(),
7057 SourceLocation(),
7058 MemberInit.takeAs<Expr>(),
7059 SourceLocation());
7060 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007061
7062 // Be sure that the destructor is accessible and is marked as referenced.
7063 if (const RecordType *RecordTy
7064 = Context.getBaseElementType(Field->getType())
7065 ->getAs<RecordType>()) {
7066 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007067 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007068 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7069 CheckDestructorAccess(Field->getLocation(), Destructor,
7070 PDiag(diag::err_access_dtor_ivar)
7071 << Context.getBaseElementType(Field->getType()));
7072 }
7073 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007074 }
7075 ObjCImplementation->setIvarInitializers(Context,
7076 AllToInit.data(), AllToInit.size());
7077 }
7078}