blob: 02688b8f653fd0d5e8146a615a823b79b7b70107 [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,
Nico Weber6bb4dcb2010-11-28 22:53:37 +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);
John McCall4765fa02010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(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()
John McCall4765fa02010-12-06 08:20:24 +0000314 // strips off any top-level ExprWithCleanups.
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();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000846
847 // For anonymous bitfields, the location should point to the type.
848 if (Loc.isInvalid())
849 Loc = D.getSourceRange().getBegin();
850
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000851 Expr *BitWidth = static_cast<Expr*>(BW);
852 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000853
John McCall4bde1e12010-06-04 08:34:12 +0000854 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000855 assert(!DS.isFriendSpecified());
856
John McCall4bde1e12010-06-04 08:34:12 +0000857 bool isFunc = false;
858 if (D.isFunctionDeclarator())
859 isFunc = true;
860 else if (D.getNumTypeObjects() == 0 &&
861 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000862 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000863 isFunc = TDType->isFunctionType();
864 }
865
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000866 // C++ 9.2p6: A member shall not be declared to have automatic storage
867 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000868 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
869 // data members and cannot be applied to names declared const or static,
870 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000871 switch (DS.getStorageClassSpec()) {
872 case DeclSpec::SCS_unspecified:
873 case DeclSpec::SCS_typedef:
874 case DeclSpec::SCS_static:
875 // FALL THROUGH.
876 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000877 case DeclSpec::SCS_mutable:
878 if (isFunc) {
879 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000880 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000881 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000882 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Sebastian Redla11f42f2008-11-17 23:24:37 +0000884 // FIXME: It would be nicer if the keyword was ignored only for this
885 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000886 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000887 }
888 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000889 default:
890 if (DS.getStorageClassSpecLoc().isValid())
891 Diag(DS.getStorageClassSpecLoc(),
892 diag::err_storageclass_invalid_for_member);
893 else
894 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
895 D.getMutableDeclSpec().ClearStorageClassSpecs();
896 }
897
Sebastian Redl669d5d72008-11-14 23:42:31 +0000898 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
899 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000900 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901
902 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000903 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000904 CXXScopeSpec &SS = D.getCXXScopeSpec();
905
906
907 if (SS.isSet() && !SS.isInvalid()) {
908 // The user provided a superfluous scope specifier inside a class
909 // definition:
910 //
911 // class X {
912 // int X::member;
913 // };
914 DeclContext *DC = 0;
915 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
916 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
917 << Name << FixItHint::CreateRemoval(SS.getRange());
918 else
919 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
920 << Name << SS.getRange();
921
922 SS.clear();
923 }
924
Douglas Gregor37b372b2009-08-20 22:52:58 +0000925 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000926 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
927 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000928 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000929 } else {
John McCalld226f652010-08-21 09:40:31 +0000930 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000931 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000932 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000933 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000934
935 // Non-instance-fields can't have a bitfield.
936 if (BitWidth) {
937 if (Member->isInvalidDecl()) {
938 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000939 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000940 // C++ 9.6p3: A bit-field shall not be a static member.
941 // "static member 'A' cannot be a bit-field"
942 Diag(Loc, diag::err_static_not_bitfield)
943 << Name << BitWidth->getSourceRange();
944 } else if (isa<TypedefDecl>(Member)) {
945 // "typedef member 'x' cannot be a bit-field"
946 Diag(Loc, diag::err_typedef_not_bitfield)
947 << Name << BitWidth->getSourceRange();
948 } else {
949 // A function typedef ("typedef int f(); f a;").
950 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
951 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000952 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000953 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner8b963ef2009-03-05 23:01:03 +0000956 BitWidth = 0;
957 Member->setInvalidDecl();
958 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000959
960 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregor37b372b2009-08-20 22:52:58 +0000962 // If we have declared a member function template, set the access of the
963 // templated declaration as well.
964 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
965 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000966 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000967
Douglas Gregor10bd3682008-11-17 22:58:34 +0000968 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000969
Douglas Gregor021c3b32009-03-11 23:00:04 +0000970 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +0000971 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000972 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +0000973 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000974
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000975 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000976 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +0000977 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000978 }
John McCalld226f652010-08-21 09:40:31 +0000979 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000980}
981
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000982/// \brief Find the direct and/or virtual base specifiers that
983/// correspond to the given base type, for use in base initialization
984/// within a constructor.
985static bool FindBaseInitializer(Sema &SemaRef,
986 CXXRecordDecl *ClassDecl,
987 QualType BaseType,
988 const CXXBaseSpecifier *&DirectBaseSpec,
989 const CXXBaseSpecifier *&VirtualBaseSpec) {
990 // First, check for a direct base class.
991 DirectBaseSpec = 0;
992 for (CXXRecordDecl::base_class_const_iterator Base
993 = ClassDecl->bases_begin();
994 Base != ClassDecl->bases_end(); ++Base) {
995 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
996 // We found a direct base of this type. That's what we're
997 // initializing.
998 DirectBaseSpec = &*Base;
999 break;
1000 }
1001 }
1002
1003 // Check for a virtual base class.
1004 // FIXME: We might be able to short-circuit this if we know in advance that
1005 // there are no virtual bases.
1006 VirtualBaseSpec = 0;
1007 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1008 // We haven't found a base yet; search the class hierarchy for a
1009 // virtual base class.
1010 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1011 /*DetectVirtual=*/false);
1012 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1013 BaseType, Paths)) {
1014 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1015 Path != Paths.end(); ++Path) {
1016 if (Path->back().Base->isVirtual()) {
1017 VirtualBaseSpec = Path->back().Base;
1018 break;
1019 }
1020 }
1021 }
1022 }
1023
1024 return DirectBaseSpec || VirtualBaseSpec;
1025}
1026
Douglas Gregor7ad83902008-11-05 04:29:56 +00001027/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001028MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001029Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001030 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001031 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001032 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001033 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001034 SourceLocation IdLoc,
1035 SourceLocation LParenLoc,
1036 ExprTy **Args, unsigned NumArgs,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001037 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001038 if (!ConstructorD)
1039 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001041 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001042
1043 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001044 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001045 if (!Constructor) {
1046 // The user wrote a constructor initializer on a function that is
1047 // not a C++ constructor. Ignore the error for now, because we may
1048 // have more member initializers coming; we'll diagnose it just
1049 // once in ActOnMemInitializers.
1050 return true;
1051 }
1052
1053 CXXRecordDecl *ClassDecl = Constructor->getParent();
1054
1055 // C++ [class.base.init]p2:
1056 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001057 // constructor's class and, if not found in that scope, are looked
1058 // up in the scope containing the constructor's definition.
1059 // [Note: if the constructor's class contains a member with the
1060 // same name as a direct or virtual base class of the class, a
1061 // mem-initializer-id naming the member or base class and composed
1062 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001063 // mem-initializer-id for the hidden base class may be specified
1064 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001065 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001066 // Look for a member, first.
1067 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001068 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001069 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001070 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001071 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001072
Francois Pichet00eb3f92010-12-04 09:14:42 +00001073 if (Member)
1074 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001075 LParenLoc, RParenLoc);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001076 // Handle anonymous union case.
1077 if (IndirectFieldDecl* IndirectField
1078 = dyn_cast<IndirectFieldDecl>(*Result.first))
1079 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1080 NumArgs, IdLoc,
1081 LParenLoc, RParenLoc);
1082 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001083 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001084 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001085 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001086 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001087
1088 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001089 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001090 } else {
1091 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1092 LookupParsedName(R, S, &SS);
1093
1094 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1095 if (!TyD) {
1096 if (R.isAmbiguous()) return true;
1097
John McCallfd225442010-04-09 19:01:14 +00001098 // We don't want access-control diagnostics here.
1099 R.suppressDiagnostics();
1100
Douglas Gregor7a886e12010-01-19 06:46:48 +00001101 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1102 bool NotUnknownSpecialization = false;
1103 DeclContext *DC = computeDeclContext(SS, false);
1104 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1105 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1106
1107 if (!NotUnknownSpecialization) {
1108 // When the scope specifier can refer to a member of an unknown
1109 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001110 BaseType = CheckTypenameType(ETK_None,
1111 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001112 *MemberOrBase, SourceLocation(),
1113 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001114 if (BaseType.isNull())
1115 return true;
1116
Douglas Gregor7a886e12010-01-19 06:46:48 +00001117 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001118 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001119 }
1120 }
1121
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001122 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001123 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001124 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1125 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001126 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001127 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001128 // We have found a non-static data member with a similar
1129 // name to what was typed; complain and initialize that
1130 // member.
1131 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1132 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001133 << FixItHint::CreateReplacement(R.getNameLoc(),
1134 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001135 Diag(Member->getLocation(), diag::note_previous_decl)
1136 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001137
1138 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1139 LParenLoc, RParenLoc);
1140 }
1141 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1142 const CXXBaseSpecifier *DirectBaseSpec;
1143 const CXXBaseSpecifier *VirtualBaseSpec;
1144 if (FindBaseInitializer(*this, ClassDecl,
1145 Context.getTypeDeclType(Type),
1146 DirectBaseSpec, VirtualBaseSpec)) {
1147 // We have found a direct or virtual base class with a
1148 // similar name to what was typed; complain and initialize
1149 // that base class.
1150 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1151 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001152 << FixItHint::CreateReplacement(R.getNameLoc(),
1153 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001154
1155 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1156 : VirtualBaseSpec;
1157 Diag(BaseSpec->getSourceRange().getBegin(),
1158 diag::note_base_class_specified_here)
1159 << BaseSpec->getType()
1160 << BaseSpec->getSourceRange();
1161
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001162 TyD = Type;
1163 }
1164 }
1165 }
1166
Douglas Gregor7a886e12010-01-19 06:46:48 +00001167 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001168 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1169 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1170 return true;
1171 }
John McCall2b194412009-12-21 10:41:20 +00001172 }
1173
Douglas Gregor7a886e12010-01-19 06:46:48 +00001174 if (BaseType.isNull()) {
1175 BaseType = Context.getTypeDeclType(TyD);
1176 if (SS.isSet()) {
1177 NestedNameSpecifier *Qualifier =
1178 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001179
Douglas Gregor7a886e12010-01-19 06:46:48 +00001180 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001181 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001182 }
John McCall2b194412009-12-21 10:41:20 +00001183 }
1184 }
Mike Stump1eb44332009-09-09 15:08:12 +00001185
John McCalla93c9342009-12-07 02:54:59 +00001186 if (!TInfo)
1187 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001188
John McCalla93c9342009-12-07 02:54:59 +00001189 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001190 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001191}
1192
John McCallb4190042009-11-04 23:02:40 +00001193/// Checks an initializer expression for use of uninitialized fields, such as
1194/// containing the field that is being initialized. Returns true if there is an
1195/// uninitialized field was used an updates the SourceLocation parameter; false
1196/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001197static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001198 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001199 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001200 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1201
Nick Lewycky43ad1822010-06-15 07:32:55 +00001202 if (isa<CallExpr>(S)) {
1203 // Do not descend into function calls or constructors, as the use
1204 // of an uninitialized field may be valid. One would have to inspect
1205 // the contents of the function/ctor to determine if it is safe or not.
1206 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1207 // may be safe, depending on what the function/ctor does.
1208 return false;
1209 }
1210 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1211 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001212
1213 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1214 // The member expression points to a static data member.
1215 assert(VD->isStaticDataMember() &&
1216 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001217 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001218 return false;
1219 }
1220
1221 if (isa<EnumConstantDecl>(RhsField)) {
1222 // The member expression points to an enum.
1223 return false;
1224 }
1225
John McCallb4190042009-11-04 23:02:40 +00001226 if (RhsField == LhsField) {
1227 // Initializing a field with itself. Throw a warning.
1228 // But wait; there are exceptions!
1229 // Exception #1: The field may not belong to this record.
1230 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001231 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001232 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1233 // Even though the field matches, it does not belong to this record.
1234 return false;
1235 }
1236 // None of the exceptions triggered; return true to indicate an
1237 // uninitialized field was used.
1238 *L = ME->getMemberLoc();
1239 return true;
1240 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001241 } else if (isa<SizeOfAlignOfExpr>(S)) {
1242 // sizeof/alignof doesn't reference contents, do not warn.
1243 return false;
1244 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1245 // address-of doesn't reference contents (the pointer may be dereferenced
1246 // in the same expression but it would be rare; and weird).
1247 if (UOE->getOpcode() == UO_AddrOf)
1248 return false;
John McCallb4190042009-11-04 23:02:40 +00001249 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001250 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1251 it != e; ++it) {
1252 if (!*it) {
1253 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001254 continue;
1255 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001256 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1257 return true;
John McCallb4190042009-11-04 23:02:40 +00001258 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001259 return false;
John McCallb4190042009-11-04 23:02:40 +00001260}
1261
John McCallf312b1e2010-08-26 23:41:50 +00001262MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001263Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001264 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001265 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001266 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001267 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1268 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1269 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001270 "Member must be a FieldDecl or IndirectFieldDecl");
1271
Douglas Gregor464b2f02010-11-05 22:21:31 +00001272 if (Member->isInvalidDecl())
1273 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001274
John McCallb4190042009-11-04 23:02:40 +00001275 // Diagnose value-uses of fields to initialize themselves, e.g.
1276 // foo(foo)
1277 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001278 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001279 for (unsigned i = 0; i < NumArgs; ++i) {
1280 SourceLocation L;
1281 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1282 // FIXME: Return true in the case when other fields are used before being
1283 // uninitialized. For example, let this field be the i'th field. When
1284 // initializing the i'th field, throw a warning if any of the >= i'th
1285 // fields are used, as they are not yet initialized.
1286 // Right now we are only handling the case where the i'th field uses
1287 // itself in its initializer.
1288 Diag(L, diag::warn_field_is_uninit);
1289 }
1290 }
1291
Eli Friedman59c04372009-07-29 19:44:27 +00001292 bool HasDependentArg = false;
1293 for (unsigned i = 0; i < NumArgs; i++)
1294 HasDependentArg |= Args[i]->isTypeDependent();
1295
Chandler Carruth894aed92010-12-06 09:23:57 +00001296 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001297 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001298 // Can't check initialization for a member of dependent type or when
1299 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001300 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1301 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001302
1303 // Erase any temporaries within this evaluation context; we're not
1304 // going to track them in the AST, since we'll be rebuilding the
1305 // ASTs during template instantiation.
1306 ExprTemporaries.erase(
1307 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1308 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001309 } else {
1310 // Initialize the member.
1311 InitializedEntity MemberEntity =
1312 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1313 : InitializedEntity::InitializeMember(IndirectMember, 0);
1314 InitializationKind Kind =
1315 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001316
Chandler Carruth894aed92010-12-06 09:23:57 +00001317 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1318
1319 ExprResult MemberInit =
1320 InitSeq.Perform(*this, MemberEntity, Kind,
1321 MultiExprArg(*this, Args, NumArgs), 0);
1322 if (MemberInit.isInvalid())
1323 return true;
1324
1325 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1326
1327 // C++0x [class.base.init]p7:
1328 // The initialization of each base and member constitutes a
1329 // full-expression.
1330 MemberInit = MaybeCreateExprWithCleanups(MemberInit.get());
1331 if (MemberInit.isInvalid())
1332 return true;
1333
1334 // If we are in a dependent context, template instantiation will
1335 // perform this type-checking again. Just save the arguments that we
1336 // received in a ParenListExpr.
1337 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1338 // of the information that we have about the member
1339 // initializer. However, deconstructing the ASTs is a dicey process,
1340 // and this approach is far more likely to get the corner cases right.
1341 if (CurContext->isDependentContext())
1342 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1343 RParenLoc);
1344 else
1345 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001346 }
1347
Chandler Carruth894aed92010-12-06 09:23:57 +00001348 if (DirectMember) {
1349 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember,
1350 IdLoc, LParenLoc, Init,
1351 RParenLoc);
1352 } else {
1353 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember,
1354 IdLoc, LParenLoc, Init,
1355 RParenLoc);
1356 }
Eli Friedman59c04372009-07-29 19:44:27 +00001357}
1358
John McCallf312b1e2010-08-26 23:41:50 +00001359MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001360Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001361 Expr **Args, unsigned NumArgs,
1362 SourceLocation LParenLoc, SourceLocation RParenLoc,
1363 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001364 bool HasDependentArg = false;
1365 for (unsigned i = 0; i < NumArgs; i++)
1366 HasDependentArg |= Args[i]->isTypeDependent();
1367
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001368 SourceLocation BaseLoc
1369 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1370
1371 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1372 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1373 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1374
1375 // C++ [class.base.init]p2:
1376 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001377 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001378 // of that class, the mem-initializer is ill-formed. A
1379 // mem-initializer-list can initialize a base class using any
1380 // name that denotes that base class type.
1381 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1382
1383 // Check for direct and virtual base classes.
1384 const CXXBaseSpecifier *DirectBaseSpec = 0;
1385 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1386 if (!Dependent) {
1387 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1388 VirtualBaseSpec);
1389
1390 // C++ [base.class.init]p2:
1391 // Unless the mem-initializer-id names a nonstatic data member of the
1392 // constructor's class or a direct or virtual base of that class, the
1393 // mem-initializer is ill-formed.
1394 if (!DirectBaseSpec && !VirtualBaseSpec) {
1395 // If the class has any dependent bases, then it's possible that
1396 // one of those types will resolve to the same type as
1397 // BaseType. Therefore, just treat this as a dependent base
1398 // class initialization. FIXME: Should we try to check the
1399 // initialization anyway? It seems odd.
1400 if (ClassDecl->hasAnyDependentBases())
1401 Dependent = true;
1402 else
1403 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1404 << BaseType << Context.getTypeDeclType(ClassDecl)
1405 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1406 }
1407 }
1408
1409 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001410 // Can't check initialization for a base of dependent type or when
1411 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001412 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001413 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1414 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001415
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416 // Erase any temporaries within this evaluation context; we're not
1417 // going to track them in the AST, since we'll be rebuilding the
1418 // ASTs during template instantiation.
1419 ExprTemporaries.erase(
1420 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1421 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001423 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001424 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001425 LParenLoc,
1426 BaseInit.takeAs<Expr>(),
1427 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001428 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001429
1430 // C++ [base.class.init]p2:
1431 // If a mem-initializer-id is ambiguous because it designates both
1432 // a direct non-virtual base class and an inherited virtual base
1433 // class, the mem-initializer is ill-formed.
1434 if (DirectBaseSpec && VirtualBaseSpec)
1435 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001436 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001437
1438 CXXBaseSpecifier *BaseSpec
1439 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1440 if (!BaseSpec)
1441 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1442
1443 // Initialize the base.
1444 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001445 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001446 InitializationKind Kind =
1447 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1448
1449 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1450
John McCall60d7b3a2010-08-24 06:29:42 +00001451 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001452 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001453 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001454 if (BaseInit.isInvalid())
1455 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001456
1457 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001458
1459 // C++0x [class.base.init]p7:
1460 // The initialization of each base and member constitutes a
1461 // full-expression.
John McCall4765fa02010-12-06 08:20:24 +00001462 BaseInit = MaybeCreateExprWithCleanups(BaseInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001463 if (BaseInit.isInvalid())
1464 return true;
1465
1466 // If we are in a dependent context, template instantiation will
1467 // perform this type-checking again. Just save the arguments that we
1468 // received in a ParenListExpr.
1469 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1470 // of the information that we have about the base
1471 // initializer. However, deconstructing the ASTs is a dicey process,
1472 // and this approach is far more likely to get the corner cases right.
1473 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001474 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001475 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1476 RParenLoc));
1477 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001478 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001479 LParenLoc,
1480 Init.takeAs<Expr>(),
1481 RParenLoc);
1482 }
1483
1484 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001485 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001486 LParenLoc,
1487 BaseInit.takeAs<Expr>(),
1488 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001489}
1490
Anders Carlssone5ef7402010-04-23 03:10:23 +00001491/// ImplicitInitializerKind - How an implicit base or member initializer should
1492/// initialize its base or member.
1493enum ImplicitInitializerKind {
1494 IIK_Default,
1495 IIK_Copy,
1496 IIK_Move
1497};
1498
Anders Carlssondefefd22010-04-23 02:00:02 +00001499static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001500BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001501 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001502 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001503 bool IsInheritedVirtualBase,
1504 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001505 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001506 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1507 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001508
John McCall60d7b3a2010-08-24 06:29:42 +00001509 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001510
1511 switch (ImplicitInitKind) {
1512 case IIK_Default: {
1513 InitializationKind InitKind
1514 = InitializationKind::CreateDefault(Constructor->getLocation());
1515 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1516 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001517 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001518 break;
1519 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001520
Anders Carlssone5ef7402010-04-23 03:10:23 +00001521 case IIK_Copy: {
1522 ParmVarDecl *Param = Constructor->getParamDecl(0);
1523 QualType ParamType = Param->getType().getNonReferenceType();
1524
1525 Expr *CopyCtorArg =
1526 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001527 Constructor->getLocation(), ParamType,
1528 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001529
Anders Carlssonc7957502010-04-24 22:02:54 +00001530 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001531 QualType ArgTy =
1532 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1533 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001534
1535 CXXCastPath BasePath;
1536 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001537 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001538 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001539 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001540
Anders Carlssone5ef7402010-04-23 03:10:23 +00001541 InitializationKind InitKind
1542 = InitializationKind::CreateDirect(Constructor->getLocation(),
1543 SourceLocation(), SourceLocation());
1544 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1545 &CopyCtorArg, 1);
1546 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001547 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001548 break;
1549 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001550
Anders Carlssone5ef7402010-04-23 03:10:23 +00001551 case IIK_Move:
1552 assert(false && "Unhandled initializer kind!");
1553 }
John McCall9ae2f072010-08-23 23:25:46 +00001554
1555 if (BaseInit.isInvalid())
1556 return true;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001557
John McCall4765fa02010-12-06 08:20:24 +00001558 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit.get());
Anders Carlsson84688f22010-04-20 23:11:20 +00001559 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001560 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001561
Anders Carlssondefefd22010-04-23 02:00:02 +00001562 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001563 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1564 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1565 SourceLocation()),
1566 BaseSpec->isVirtual(),
1567 SourceLocation(),
1568 BaseInit.takeAs<Expr>(),
1569 SourceLocation());
1570
Anders Carlssondefefd22010-04-23 02:00:02 +00001571 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001572}
1573
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001574static bool
1575BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001576 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001577 FieldDecl *Field,
1578 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001579 if (Field->isInvalidDecl())
1580 return true;
1581
Chandler Carruthf186b542010-06-29 23:50:44 +00001582 SourceLocation Loc = Constructor->getLocation();
1583
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001584 if (ImplicitInitKind == IIK_Copy) {
1585 ParmVarDecl *Param = Constructor->getParamDecl(0);
1586 QualType ParamType = Param->getType().getNonReferenceType();
1587
1588 Expr *MemberExprBase =
1589 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001590 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001591
1592 // Build a reference to this field within the parameter.
1593 CXXScopeSpec SS;
1594 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1595 Sema::LookupMemberName);
1596 MemberLookup.addDecl(Field, AS_public);
1597 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001598 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001599 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001600 ParamType, Loc,
1601 /*IsArrow=*/false,
1602 SS,
1603 /*FirstQualifierInScope=*/0,
1604 MemberLookup,
1605 /*TemplateArgs=*/0);
1606 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001607 return true;
1608
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001609 // When the field we are copying is an array, create index variables for
1610 // each dimension of the array. We use these index variables to subscript
1611 // the source array, and other clients (e.g., CodeGen) will perform the
1612 // necessary iteration with these index variables.
1613 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1614 QualType BaseType = Field->getType();
1615 QualType SizeType = SemaRef.Context.getSizeType();
1616 while (const ConstantArrayType *Array
1617 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1618 // Create the iteration variable for this array index.
1619 IdentifierInfo *IterationVarName = 0;
1620 {
1621 llvm::SmallString<8> Str;
1622 llvm::raw_svector_ostream OS(Str);
1623 OS << "__i" << IndexVariables.size();
1624 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1625 }
1626 VarDecl *IterationVar
1627 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1628 IterationVarName, SizeType,
1629 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001630 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001631 IndexVariables.push_back(IterationVar);
1632
1633 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001634 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001635 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001636 assert(!IterationVarRef.isInvalid() &&
1637 "Reference to invented variable cannot fail!");
1638
1639 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001640 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001641 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001642 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001643 Loc);
1644 if (CopyCtorArg.isInvalid())
1645 return true;
1646
1647 BaseType = Array->getElementType();
1648 }
1649
1650 // Construct the entity that we will be initializing. For an array, this
1651 // will be first element in the array, which may require several levels
1652 // of array-subscript entities.
1653 llvm::SmallVector<InitializedEntity, 4> Entities;
1654 Entities.reserve(1 + IndexVariables.size());
1655 Entities.push_back(InitializedEntity::InitializeMember(Field));
1656 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1657 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1658 0,
1659 Entities.back()));
1660
1661 // Direct-initialize to use the copy constructor.
1662 InitializationKind InitKind =
1663 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1664
1665 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1666 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1667 &CopyCtorArgE, 1);
1668
John McCall60d7b3a2010-08-24 06:29:42 +00001669 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001670 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001671 MultiExprArg(&CopyCtorArgE, 1));
John McCall4765fa02010-12-06 08:20:24 +00001672 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit.get());
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001673 if (MemberInit.isInvalid())
1674 return true;
1675
1676 CXXMemberInit
1677 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1678 MemberInit.takeAs<Expr>(), Loc,
1679 IndexVariables.data(),
1680 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001681 return false;
1682 }
1683
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001684 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1685
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001686 QualType FieldBaseElementType =
1687 SemaRef.Context.getBaseElementType(Field->getType());
1688
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001689 if (FieldBaseElementType->isRecordType()) {
1690 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001691 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001692 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001693
1694 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001695 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001696 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001697 if (MemberInit.isInvalid())
1698 return true;
1699
John McCall4765fa02010-12-06 08:20:24 +00001700 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit.get());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001701 if (MemberInit.isInvalid())
1702 return true;
1703
1704 CXXMemberInit =
1705 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001706 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001707 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001708 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001709 return false;
1710 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001711
1712 if (FieldBaseElementType->isReferenceType()) {
1713 SemaRef.Diag(Constructor->getLocation(),
1714 diag::err_uninitialized_member_in_ctor)
1715 << (int)Constructor->isImplicit()
1716 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1717 << 0 << Field->getDeclName();
1718 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1719 return true;
1720 }
1721
1722 if (FieldBaseElementType.isConstQualified()) {
1723 SemaRef.Diag(Constructor->getLocation(),
1724 diag::err_uninitialized_member_in_ctor)
1725 << (int)Constructor->isImplicit()
1726 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1727 << 1 << Field->getDeclName();
1728 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1729 return true;
1730 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001731
1732 // Nothing to initialize.
1733 CXXMemberInit = 0;
1734 return false;
1735}
John McCallf1860e52010-05-20 23:23:51 +00001736
1737namespace {
1738struct BaseAndFieldInfo {
1739 Sema &S;
1740 CXXConstructorDecl *Ctor;
1741 bool AnyErrorsInInits;
1742 ImplicitInitializerKind IIK;
1743 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1744 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1745
1746 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1747 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1748 // FIXME: Handle implicit move constructors.
1749 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1750 IIK = IIK_Copy;
1751 else
1752 IIK = IIK_Default;
1753 }
1754};
1755}
1756
1757static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1758 FieldDecl *Top, FieldDecl *Field) {
1759
Chandler Carruthe861c602010-06-30 02:59:29 +00001760 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001761 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001762 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001763 return false;
1764 }
1765
1766 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1767 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1768 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001769 CXXRecordDecl *FieldClassDecl
1770 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001771
1772 // Even though union members never have non-trivial default
1773 // constructions in C++03, we still build member initializers for aggregate
1774 // record types which can be union members, and C++0x allows non-trivial
1775 // default constructors for union members, so we ensure that only one
1776 // member is initialized for these.
1777 if (FieldClassDecl->isUnion()) {
1778 // First check for an explicit initializer for one field.
1779 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1780 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1781 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001782 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001783
1784 // Once we've initialized a field of an anonymous union, the union
1785 // field in the class is also initialized, so exit immediately.
1786 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001787 } else if ((*FA)->isAnonymousStructOrUnion()) {
1788 if (CollectFieldInitializer(Info, Top, *FA))
1789 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001790 }
1791 }
1792
1793 // Fallthrough and construct a default initializer for the union as
1794 // a whole, which can call its default constructor if such a thing exists
1795 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1796 // behavior going forward with C++0x, when anonymous unions there are
1797 // finalized, we should revisit this.
1798 } else {
1799 // For structs, we simply descend through to initialize all members where
1800 // necessary.
1801 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1802 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1803 if (CollectFieldInitializer(Info, Top, *FA))
1804 return true;
1805 }
1806 }
John McCallf1860e52010-05-20 23:23:51 +00001807 }
1808
1809 // Don't try to build an implicit initializer if there were semantic
1810 // errors in any of the initializers (and therefore we might be
1811 // missing some that the user actually wrote).
1812 if (Info.AnyErrorsInInits)
1813 return false;
1814
1815 CXXBaseOrMemberInitializer *Init = 0;
1816 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1817 return true;
John McCallf1860e52010-05-20 23:23:51 +00001818
Francois Pichet00eb3f92010-12-04 09:14:42 +00001819 if (Init)
1820 Info.AllToInit.push_back(Init);
1821
John McCallf1860e52010-05-20 23:23:51 +00001822 return false;
1823}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001824
Eli Friedman80c30da2009-11-09 19:20:36 +00001825bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001826Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001827 CXXBaseOrMemberInitializer **Initializers,
1828 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001829 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001830 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001831 // Just store the initializers as written, they will be checked during
1832 // instantiation.
1833 if (NumInitializers > 0) {
1834 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1835 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1836 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1837 memcpy(baseOrMemberInitializers, Initializers,
1838 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1839 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1840 }
1841
1842 return false;
1843 }
1844
John McCallf1860e52010-05-20 23:23:51 +00001845 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001846
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001847 // We need to build the initializer AST according to order of construction
1848 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001849 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001850 if (!ClassDecl)
1851 return true;
1852
Eli Friedman80c30da2009-11-09 19:20:36 +00001853 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001855 for (unsigned i = 0; i < NumInitializers; i++) {
1856 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001857
1858 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001859 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001860 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00001861 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001862 }
1863
Anders Carlsson711f34a2010-04-21 19:52:01 +00001864 // Keep track of the direct virtual bases.
1865 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1866 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1867 E = ClassDecl->bases_end(); I != E; ++I) {
1868 if (I->isVirtual())
1869 DirectVBases.insert(I);
1870 }
1871
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001872 // Push virtual bases before others.
1873 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1874 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1875
1876 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001877 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1878 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001879 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001880 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001881 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001882 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001883 VBase, IsInheritedVirtualBase,
1884 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001885 HadError = true;
1886 continue;
1887 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001888
John McCallf1860e52010-05-20 23:23:51 +00001889 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001890 }
1891 }
Mike Stump1eb44332009-09-09 15:08:12 +00001892
John McCallf1860e52010-05-20 23:23:51 +00001893 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001894 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1895 E = ClassDecl->bases_end(); Base != E; ++Base) {
1896 // Virtuals are in the virtual base list and already constructed.
1897 if (Base->isVirtual())
1898 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001900 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001901 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1902 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001903 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001904 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001905 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001906 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001907 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001908 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001909 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001910 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001911
John McCallf1860e52010-05-20 23:23:51 +00001912 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001913 }
1914 }
Mike Stump1eb44332009-09-09 15:08:12 +00001915
John McCallf1860e52010-05-20 23:23:51 +00001916 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001917 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001918 E = ClassDecl->field_end(); Field != E; ++Field) {
1919 if ((*Field)->getType()->isIncompleteArrayType()) {
1920 assert(ClassDecl->hasFlexibleArrayMember() &&
1921 "Incomplete array type is not valid");
1922 continue;
1923 }
John McCallf1860e52010-05-20 23:23:51 +00001924 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001925 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
John McCallf1860e52010-05-20 23:23:51 +00001928 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001929 if (NumInitializers > 0) {
1930 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1931 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1932 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001933 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001934 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001935 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001936
John McCallef027fe2010-03-16 21:39:52 +00001937 // Constructors implicitly reference the base and member
1938 // destructors.
1939 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1940 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001941 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001942
1943 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001944}
1945
Eli Friedman6347f422009-07-21 19:28:10 +00001946static void *GetKeyForTopLevelField(FieldDecl *Field) {
1947 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001948 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001949 if (RT->getDecl()->isAnonymousStructOrUnion())
1950 return static_cast<void *>(RT->getDecl());
1951 }
1952 return static_cast<void *>(Field);
1953}
1954
Anders Carlssonea356fb2010-04-02 05:42:15 +00001955static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1956 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001957}
1958
Anders Carlssonea356fb2010-04-02 05:42:15 +00001959static void *GetKeyForMember(ASTContext &Context,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001960 CXXBaseOrMemberInitializer *Member) {
1961 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001962 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001963
Eli Friedman6347f422009-07-21 19:28:10 +00001964 // For fields injected into the class via declaration of an anonymous union,
1965 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00001966 FieldDecl *Field = Member->getAnyMember();
1967
John McCall3c3ccdb2010-04-10 09:28:51 +00001968 // If the field is a member of an anonymous struct or union, our key
1969 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001970 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001971 if (RD->isAnonymousStructOrUnion()) {
1972 while (true) {
1973 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1974 if (Parent->isAnonymousStructOrUnion())
1975 RD = Parent;
1976 else
1977 break;
1978 }
1979
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001980 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001983 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001984}
1985
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001986static void
1987DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001988 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001989 CXXBaseOrMemberInitializer **Inits,
1990 unsigned NumInits) {
1991 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001992 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
John McCalld6ca8da2010-04-10 07:37:23 +00001994 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1995 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001996 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001997
John McCalld6ca8da2010-04-10 07:37:23 +00001998 // Build the list of bases and members in the order that they'll
1999 // actually be initialized. The explicit initializers should be in
2000 // this same order but may be missing things.
2001 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlsson071d6102010-04-02 03:38:04 +00002003 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2004
John McCalld6ca8da2010-04-10 07:37:23 +00002005 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002006 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002007 ClassDecl->vbases_begin(),
2008 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002009 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002010
John McCalld6ca8da2010-04-10 07:37:23 +00002011 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002012 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002013 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002014 if (Base->isVirtual())
2015 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002016 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
John McCalld6ca8da2010-04-10 07:37:23 +00002019 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002020 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2021 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002022 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002023
John McCalld6ca8da2010-04-10 07:37:23 +00002024 unsigned NumIdealInits = IdealInitKeys.size();
2025 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002026
John McCalld6ca8da2010-04-10 07:37:23 +00002027 CXXBaseOrMemberInitializer *PrevInit = 0;
2028 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2029 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002030 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002031
2032 // Scan forward to try to find this initializer in the idealized
2033 // initializers list.
2034 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2035 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002036 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002037
2038 // If we didn't find this initializer, it must be because we
2039 // scanned past it on a previous iteration. That can only
2040 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002041 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002042 Sema::SemaDiagnosticBuilder D =
2043 SemaRef.Diag(PrevInit->getSourceLocation(),
2044 diag::warn_initializer_out_of_order);
2045
Francois Pichet00eb3f92010-12-04 09:14:42 +00002046 if (PrevInit->isAnyMemberInitializer())
2047 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002048 else
2049 D << 1 << PrevInit->getBaseClassInfo()->getType();
2050
Francois Pichet00eb3f92010-12-04 09:14:42 +00002051 if (Init->isAnyMemberInitializer())
2052 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002053 else
2054 D << 1 << Init->getBaseClassInfo()->getType();
2055
2056 // Move back to the initializer's location in the ideal list.
2057 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2058 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002059 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002060
2061 assert(IdealIndex != NumIdealInits &&
2062 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002063 }
John McCalld6ca8da2010-04-10 07:37:23 +00002064
2065 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002066 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002067}
2068
John McCall3c3ccdb2010-04-10 09:28:51 +00002069namespace {
2070bool CheckRedundantInit(Sema &S,
2071 CXXBaseOrMemberInitializer *Init,
2072 CXXBaseOrMemberInitializer *&PrevInit) {
2073 if (!PrevInit) {
2074 PrevInit = Init;
2075 return false;
2076 }
2077
2078 if (FieldDecl *Field = Init->getMember())
2079 S.Diag(Init->getSourceLocation(),
2080 diag::err_multiple_mem_initialization)
2081 << Field->getDeclName()
2082 << Init->getSourceRange();
2083 else {
2084 Type *BaseClass = Init->getBaseClass();
2085 assert(BaseClass && "neither field nor base");
2086 S.Diag(Init->getSourceLocation(),
2087 diag::err_multiple_base_initialization)
2088 << QualType(BaseClass, 0)
2089 << Init->getSourceRange();
2090 }
2091 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2092 << 0 << PrevInit->getSourceRange();
2093
2094 return true;
2095}
2096
2097typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2098typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2099
2100bool CheckRedundantUnionInit(Sema &S,
2101 CXXBaseOrMemberInitializer *Init,
2102 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002103 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002104 RecordDecl *Parent = Field->getParent();
2105 if (!Parent->isAnonymousStructOrUnion())
2106 return false;
2107
2108 NamedDecl *Child = Field;
2109 do {
2110 if (Parent->isUnion()) {
2111 UnionEntry &En = Unions[Parent];
2112 if (En.first && En.first != Child) {
2113 S.Diag(Init->getSourceLocation(),
2114 diag::err_multiple_mem_union_initialization)
2115 << Field->getDeclName()
2116 << Init->getSourceRange();
2117 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2118 << 0 << En.second->getSourceRange();
2119 return true;
2120 } else if (!En.first) {
2121 En.first = Child;
2122 En.second = Init;
2123 }
2124 }
2125
2126 Child = Parent;
2127 Parent = cast<RecordDecl>(Parent->getDeclContext());
2128 } while (Parent->isAnonymousStructOrUnion());
2129
2130 return false;
2131}
2132}
2133
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002134/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002135void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002136 SourceLocation ColonLoc,
2137 MemInitTy **meminits, unsigned NumMemInits,
2138 bool AnyErrors) {
2139 if (!ConstructorDecl)
2140 return;
2141
2142 AdjustDeclIfTemplate(ConstructorDecl);
2143
2144 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002145 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002146
2147 if (!Constructor) {
2148 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2149 return;
2150 }
2151
2152 CXXBaseOrMemberInitializer **MemInits =
2153 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002154
2155 // Mapping for the duplicate initializers check.
2156 // For member initializers, this is keyed with a FieldDecl*.
2157 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002158 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002159
2160 // Mapping for the inconsistent anonymous-union initializers check.
2161 RedundantUnionMap MemberUnions;
2162
Anders Carlssonea356fb2010-04-02 05:42:15 +00002163 bool HadError = false;
2164 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002165 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002166
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002167 // Set the source order index.
2168 Init->setSourceOrder(i);
2169
Francois Pichet00eb3f92010-12-04 09:14:42 +00002170 if (Init->isAnyMemberInitializer()) {
2171 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002172 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2173 CheckRedundantUnionInit(*this, Init, MemberUnions))
2174 HadError = true;
2175 } else {
2176 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2177 if (CheckRedundantInit(*this, Init, Members[Key]))
2178 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002179 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002180 }
2181
Anders Carlssonea356fb2010-04-02 05:42:15 +00002182 if (HadError)
2183 return;
2184
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002185 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002186
2187 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002188}
2189
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002190void
John McCallef027fe2010-03-16 21:39:52 +00002191Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2192 CXXRecordDecl *ClassDecl) {
2193 // Ignore dependent contexts.
2194 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002195 return;
John McCall58e6f342010-03-16 05:22:47 +00002196
2197 // FIXME: all the access-control diagnostics are positioned on the
2198 // field/base declaration. That's probably good; that said, the
2199 // user might reasonably want to know why the destructor is being
2200 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002201
Anders Carlsson9f853df2009-11-17 04:44:12 +00002202 // Non-static data members.
2203 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2204 E = ClassDecl->field_end(); I != E; ++I) {
2205 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002206 if (Field->isInvalidDecl())
2207 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002208 QualType FieldType = Context.getBaseElementType(Field->getType());
2209
2210 const RecordType* RT = FieldType->getAs<RecordType>();
2211 if (!RT)
2212 continue;
2213
2214 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2215 if (FieldClassDecl->hasTrivialDestructor())
2216 continue;
2217
Douglas Gregordb89f282010-07-01 22:47:18 +00002218 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002219 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002220 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002221 << Field->getDeclName()
2222 << FieldType);
2223
John McCallef027fe2010-03-16 21:39:52 +00002224 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002225 }
2226
John McCall58e6f342010-03-16 05:22:47 +00002227 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2228
Anders Carlsson9f853df2009-11-17 04:44:12 +00002229 // Bases.
2230 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2231 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002232 // Bases are always records in a well-formed non-dependent class.
2233 const RecordType *RT = Base->getType()->getAs<RecordType>();
2234
2235 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002236 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002237 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002238
2239 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002241 if (BaseClassDecl->hasTrivialDestructor())
2242 continue;
John McCall58e6f342010-03-16 05:22:47 +00002243
Douglas Gregordb89f282010-07-01 22:47:18 +00002244 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002245
2246 // FIXME: caret should be on the start of the class name
2247 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002248 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002249 << Base->getType()
2250 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002251
John McCallef027fe2010-03-16 21:39:52 +00002252 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002253 }
2254
2255 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002256 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2257 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002258
2259 // Bases are always records in a well-formed non-dependent class.
2260 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2261
2262 // Ignore direct virtual bases.
2263 if (DirectVirtualBases.count(RT))
2264 continue;
2265
Anders Carlsson9f853df2009-11-17 04:44:12 +00002266 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002267 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002268 if (BaseClassDecl->hasTrivialDestructor())
2269 continue;
John McCall58e6f342010-03-16 05:22:47 +00002270
Douglas Gregordb89f282010-07-01 22:47:18 +00002271 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002272 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002273 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002274 << VBase->getType());
2275
John McCallef027fe2010-03-16 21:39:52 +00002276 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002277 }
2278}
2279
John McCalld226f652010-08-21 09:40:31 +00002280void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002281 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002282 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Mike Stump1eb44332009-09-09 15:08:12 +00002284 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002285 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002286 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002287}
2288
Mike Stump1eb44332009-09-09 15:08:12 +00002289bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002290 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002291 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002292 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002293 else
John McCall94c3b562010-08-18 09:41:07 +00002294 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002295}
2296
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002297bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002298 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002299 if (!getLangOptions().CPlusPlus)
2300 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Anders Carlsson11f21a02009-03-23 19:10:31 +00002302 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002303 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Ted Kremenek6217b802009-07-29 21:53:49 +00002305 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002306 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002307 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002308 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002310 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002311 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002312 }
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Ted Kremenek6217b802009-07-29 21:53:49 +00002314 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002315 if (!RT)
2316 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002317
John McCall86ff3082010-02-04 22:26:26 +00002318 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002319
John McCall94c3b562010-08-18 09:41:07 +00002320 // We can't answer whether something is abstract until it has a
2321 // definition. If it's currently being defined, we'll walk back
2322 // over all the declarations when we have a full definition.
2323 const CXXRecordDecl *Def = RD->getDefinition();
2324 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002325 return false;
2326
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002327 if (!RD->isAbstract())
2328 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002330 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002331 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002332
John McCall94c3b562010-08-18 09:41:07 +00002333 return true;
2334}
2335
2336void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2337 // Check if we've already emitted the list of pure virtual functions
2338 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002339 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002340 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002342 CXXFinalOverriderMap FinalOverriders;
2343 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002345 // Keep a set of seen pure methods so we won't diagnose the same method
2346 // more than once.
2347 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2348
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002349 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2350 MEnd = FinalOverriders.end();
2351 M != MEnd;
2352 ++M) {
2353 for (OverridingMethods::iterator SO = M->second.begin(),
2354 SOEnd = M->second.end();
2355 SO != SOEnd; ++SO) {
2356 // C++ [class.abstract]p4:
2357 // A class is abstract if it contains or inherits at least one
2358 // pure virtual function for which the final overrider is pure
2359 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002361 //
2362 if (SO->second.size() != 1)
2363 continue;
2364
2365 if (!SO->second.front().Method->isPure())
2366 continue;
2367
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002368 if (!SeenPureMethods.insert(SO->second.front().Method))
2369 continue;
2370
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002371 Diag(SO->second.front().Method->getLocation(),
2372 diag::note_pure_virtual_function)
2373 << SO->second.front().Method->getDeclName();
2374 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002375 }
2376
2377 if (!PureVirtualClassDiagSet)
2378 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2379 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002380}
2381
Anders Carlsson8211eff2009-03-24 01:19:16 +00002382namespace {
John McCall94c3b562010-08-18 09:41:07 +00002383struct AbstractUsageInfo {
2384 Sema &S;
2385 CXXRecordDecl *Record;
2386 CanQualType AbstractType;
2387 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002388
John McCall94c3b562010-08-18 09:41:07 +00002389 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2390 : S(S), Record(Record),
2391 AbstractType(S.Context.getCanonicalType(
2392 S.Context.getTypeDeclType(Record))),
2393 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002394
John McCall94c3b562010-08-18 09:41:07 +00002395 void DiagnoseAbstractType() {
2396 if (Invalid) return;
2397 S.DiagnoseAbstractType(Record);
2398 Invalid = true;
2399 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002400
John McCall94c3b562010-08-18 09:41:07 +00002401 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2402};
2403
2404struct CheckAbstractUsage {
2405 AbstractUsageInfo &Info;
2406 const NamedDecl *Ctx;
2407
2408 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2409 : Info(Info), Ctx(Ctx) {}
2410
2411 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2412 switch (TL.getTypeLocClass()) {
2413#define ABSTRACT_TYPELOC(CLASS, PARENT)
2414#define TYPELOC(CLASS, PARENT) \
2415 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2416#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002417 }
John McCall94c3b562010-08-18 09:41:07 +00002418 }
Mike Stump1eb44332009-09-09 15:08:12 +00002419
John McCall94c3b562010-08-18 09:41:07 +00002420 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2421 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2422 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2423 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2424 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002425 }
John McCall94c3b562010-08-18 09:41:07 +00002426 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002427
John McCall94c3b562010-08-18 09:41:07 +00002428 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2429 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2430 }
Mike Stump1eb44332009-09-09 15:08:12 +00002431
John McCall94c3b562010-08-18 09:41:07 +00002432 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2433 // Visit the type parameters from a permissive context.
2434 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2435 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2436 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2437 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2438 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2439 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002440 }
John McCall94c3b562010-08-18 09:41:07 +00002441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
John McCall94c3b562010-08-18 09:41:07 +00002443 // Visit pointee types from a permissive context.
2444#define CheckPolymorphic(Type) \
2445 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2446 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2447 }
2448 CheckPolymorphic(PointerTypeLoc)
2449 CheckPolymorphic(ReferenceTypeLoc)
2450 CheckPolymorphic(MemberPointerTypeLoc)
2451 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002452
John McCall94c3b562010-08-18 09:41:07 +00002453 /// Handle all the types we haven't given a more specific
2454 /// implementation for above.
2455 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2456 // Every other kind of type that we haven't called out already
2457 // that has an inner type is either (1) sugar or (2) contains that
2458 // inner type in some way as a subobject.
2459 if (TypeLoc Next = TL.getNextTypeLoc())
2460 return Visit(Next, Sel);
2461
2462 // If there's no inner type and we're in a permissive context,
2463 // don't diagnose.
2464 if (Sel == Sema::AbstractNone) return;
2465
2466 // Check whether the type matches the abstract type.
2467 QualType T = TL.getType();
2468 if (T->isArrayType()) {
2469 Sel = Sema::AbstractArrayType;
2470 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002471 }
John McCall94c3b562010-08-18 09:41:07 +00002472 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2473 if (CT != Info.AbstractType) return;
2474
2475 // It matched; do some magic.
2476 if (Sel == Sema::AbstractArrayType) {
2477 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2478 << T << TL.getSourceRange();
2479 } else {
2480 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2481 << Sel << T << TL.getSourceRange();
2482 }
2483 Info.DiagnoseAbstractType();
2484 }
2485};
2486
2487void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2488 Sema::AbstractDiagSelID Sel) {
2489 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2490}
2491
2492}
2493
2494/// Check for invalid uses of an abstract type in a method declaration.
2495static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2496 CXXMethodDecl *MD) {
2497 // No need to do the check on definitions, which require that
2498 // the return/param types be complete.
2499 if (MD->isThisDeclarationADefinition())
2500 return;
2501
2502 // For safety's sake, just ignore it if we don't have type source
2503 // information. This should never happen for non-implicit methods,
2504 // but...
2505 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2506 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2507}
2508
2509/// Check for invalid uses of an abstract type within a class definition.
2510static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2511 CXXRecordDecl *RD) {
2512 for (CXXRecordDecl::decl_iterator
2513 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2514 Decl *D = *I;
2515 if (D->isImplicit()) continue;
2516
2517 // Methods and method templates.
2518 if (isa<CXXMethodDecl>(D)) {
2519 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2520 } else if (isa<FunctionTemplateDecl>(D)) {
2521 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2522 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2523
2524 // Fields and static variables.
2525 } else if (isa<FieldDecl>(D)) {
2526 FieldDecl *FD = cast<FieldDecl>(D);
2527 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2528 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2529 } else if (isa<VarDecl>(D)) {
2530 VarDecl *VD = cast<VarDecl>(D);
2531 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2532 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2533
2534 // Nested classes and class templates.
2535 } else if (isa<CXXRecordDecl>(D)) {
2536 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2537 } else if (isa<ClassTemplateDecl>(D)) {
2538 CheckAbstractClassUsage(Info,
2539 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2540 }
2541 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002542}
2543
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002544/// \brief Perform semantic checks on a class definition that has been
2545/// completing, introducing implicitly-declared members, checking for
2546/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002547void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002548 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002549 return;
2550
John McCall94c3b562010-08-18 09:41:07 +00002551 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2552 AbstractUsageInfo Info(*this, Record);
2553 CheckAbstractClassUsage(Info, Record);
2554 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002555
2556 // If this is not an aggregate type and has no user-declared constructor,
2557 // complain about any non-static data members of reference or const scalar
2558 // type, since they will never get initializers.
2559 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2560 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2561 bool Complained = false;
2562 for (RecordDecl::field_iterator F = Record->field_begin(),
2563 FEnd = Record->field_end();
2564 F != FEnd; ++F) {
2565 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002566 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002567 if (!Complained) {
2568 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2569 << Record->getTagKind() << Record;
2570 Complained = true;
2571 }
2572
2573 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2574 << F->getType()->isReferenceType()
2575 << F->getDeclName();
2576 }
2577 }
2578 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002579
2580 if (Record->isDynamicClass())
2581 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002582
2583 if (Record->getIdentifier()) {
2584 // C++ [class.mem]p13:
2585 // If T is the name of a class, then each of the following shall have a
2586 // name different from T:
2587 // - every member of every anonymous union that is a member of class T.
2588 //
2589 // C++ [class.mem]p14:
2590 // In addition, if class T has a user-declared constructor (12.1), every
2591 // non-static data member of class T shall have a name different from T.
2592 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002593 R.first != R.second; ++R.first) {
2594 NamedDecl *D = *R.first;
2595 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2596 isa<IndirectFieldDecl>(D)) {
2597 Diag(D->getLocation(), diag::err_member_name_of_class)
2598 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002599 break;
2600 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002601 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002602 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002603}
2604
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002605void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002606 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002607 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002608 SourceLocation RBrac,
2609 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002610 if (!TagDecl)
2611 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor42af25f2009-05-11 19:58:34 +00002613 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002614
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002615 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002616 // strict aliasing violation!
2617 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002618 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002619
Douglas Gregor23c94db2010-07-02 17:43:08 +00002620 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002621 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002622}
2623
Douglas Gregord92ec472010-07-01 05:10:53 +00002624namespace {
2625 /// \brief Helper class that collects exception specifications for
2626 /// implicitly-declared special member functions.
2627 class ImplicitExceptionSpecification {
2628 ASTContext &Context;
2629 bool AllowsAllExceptions;
2630 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2631 llvm::SmallVector<QualType, 4> Exceptions;
2632
2633 public:
2634 explicit ImplicitExceptionSpecification(ASTContext &Context)
2635 : Context(Context), AllowsAllExceptions(false) { }
2636
2637 /// \brief Whether the special member function should have any
2638 /// exception specification at all.
2639 bool hasExceptionSpecification() const {
2640 return !AllowsAllExceptions;
2641 }
2642
2643 /// \brief Whether the special member function should have a
2644 /// throw(...) exception specification (a Microsoft extension).
2645 bool hasAnyExceptionSpecification() const {
2646 return false;
2647 }
2648
2649 /// \brief The number of exceptions in the exception specification.
2650 unsigned size() const { return Exceptions.size(); }
2651
2652 /// \brief The set of exceptions in the exception specification.
2653 const QualType *data() const { return Exceptions.data(); }
2654
2655 /// \brief Note that
2656 void CalledDecl(CXXMethodDecl *Method) {
2657 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002658 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002659 return;
2660
2661 const FunctionProtoType *Proto
2662 = Method->getType()->getAs<FunctionProtoType>();
2663
2664 // If this function can throw any exceptions, make a note of that.
2665 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2666 AllowsAllExceptions = true;
2667 ExceptionsSeen.clear();
2668 Exceptions.clear();
2669 return;
2670 }
2671
2672 // Record the exceptions in this function's exception specification.
2673 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2674 EEnd = Proto->exception_end();
2675 E != EEnd; ++E)
2676 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2677 Exceptions.push_back(*E);
2678 }
2679 };
2680}
2681
2682
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002683/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2684/// special functions, such as the default constructor, copy
2685/// constructor, or destructor, to the given C++ class (C++
2686/// [special]p1). This routine can only be executed just before the
2687/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002688void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002689 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002690 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002691
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002692 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002693 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002694
Douglas Gregora376d102010-07-02 21:50:04 +00002695 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2696 ++ASTContext::NumImplicitCopyAssignmentOperators;
2697
2698 // If we have a dynamic class, then the copy assignment operator may be
2699 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2700 // it shows up in the right place in the vtable and that we diagnose
2701 // problems with the implicit exception specification.
2702 if (ClassDecl->isDynamicClass())
2703 DeclareImplicitCopyAssignment(ClassDecl);
2704 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002705
Douglas Gregor4923aa22010-07-02 20:37:36 +00002706 if (!ClassDecl->hasUserDeclaredDestructor()) {
2707 ++ASTContext::NumImplicitDestructors;
2708
2709 // If we have a dynamic class, then the destructor may be virtual, so we
2710 // have to declare the destructor immediately. This ensures that, e.g., it
2711 // shows up in the right place in the vtable and that we diagnose problems
2712 // with the implicit exception specification.
2713 if (ClassDecl->isDynamicClass())
2714 DeclareImplicitDestructor(ClassDecl);
2715 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002716}
2717
John McCalld226f652010-08-21 09:40:31 +00002718void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002719 if (!D)
2720 return;
2721
2722 TemplateParameterList *Params = 0;
2723 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2724 Params = Template->getTemplateParameters();
2725 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2726 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2727 Params = PartialSpec->getTemplateParameters();
2728 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002729 return;
2730
Douglas Gregor6569d682009-05-27 23:11:45 +00002731 for (TemplateParameterList::iterator Param = Params->begin(),
2732 ParamEnd = Params->end();
2733 Param != ParamEnd; ++Param) {
2734 NamedDecl *Named = cast<NamedDecl>(*Param);
2735 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002736 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002737 IdResolver.AddDecl(Named);
2738 }
2739 }
2740}
2741
John McCalld226f652010-08-21 09:40:31 +00002742void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002743 if (!RecordD) return;
2744 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002745 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002746 PushDeclContext(S, Record);
2747}
2748
John McCalld226f652010-08-21 09:40:31 +00002749void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002750 if (!RecordD) return;
2751 PopDeclContext();
2752}
2753
Douglas Gregor72b505b2008-12-16 21:30:33 +00002754/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2755/// parsing a top-level (non-nested) C++ class, and we are now
2756/// parsing those parts of the given Method declaration that could
2757/// not be parsed earlier (C++ [class.mem]p2), such as default
2758/// arguments. This action should enter the scope of the given
2759/// Method declaration as if we had just parsed the qualified method
2760/// name. However, it should not bring the parameters into scope;
2761/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002762void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002763}
2764
2765/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2766/// C++ method declaration. We're (re-)introducing the given
2767/// function parameter into scope for use in parsing later parts of
2768/// the method declaration. For example, we could see an
2769/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002770void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002771 if (!ParamD)
2772 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002773
John McCalld226f652010-08-21 09:40:31 +00002774 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002775
2776 // If this parameter has an unparsed default argument, clear it out
2777 // to make way for the parsed default argument.
2778 if (Param->hasUnparsedDefaultArg())
2779 Param->setDefaultArg(0);
2780
John McCalld226f652010-08-21 09:40:31 +00002781 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002782 if (Param->getDeclName())
2783 IdResolver.AddDecl(Param);
2784}
2785
2786/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2787/// processing the delayed method declaration for Method. The method
2788/// declaration is now considered finished. There may be a separate
2789/// ActOnStartOfFunctionDef action later (not necessarily
2790/// immediately!) for this method, if it was also defined inside the
2791/// class body.
John McCalld226f652010-08-21 09:40:31 +00002792void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002793 if (!MethodD)
2794 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002796 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002797
John McCalld226f652010-08-21 09:40:31 +00002798 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002799
2800 // Now that we have our default arguments, check the constructor
2801 // again. It could produce additional diagnostics or affect whether
2802 // the class has implicitly-declared destructors, among other
2803 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002804 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2805 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002806
2807 // Check the default arguments, which we may have added.
2808 if (!Method->isInvalidDecl())
2809 CheckCXXDefaultArguments(Method);
2810}
2811
Douglas Gregor42a552f2008-11-05 20:51:48 +00002812/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002813/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002814/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002815/// emit diagnostics and set the invalid bit to true. In any case, the type
2816/// will be updated to reflect a well-formed type for the constructor and
2817/// returned.
2818QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002819 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002820 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002821
2822 // C++ [class.ctor]p3:
2823 // A constructor shall not be virtual (10.3) or static (9.4). A
2824 // constructor can be invoked for a const, volatile or const
2825 // volatile object. A constructor shall not be declared const,
2826 // volatile, or const volatile (9.3.2).
2827 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002828 if (!D.isInvalidType())
2829 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2830 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2831 << SourceRange(D.getIdentifierLoc());
2832 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002833 }
John McCalld931b082010-08-26 03:08:43 +00002834 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002835 if (!D.isInvalidType())
2836 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2837 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2838 << SourceRange(D.getIdentifierLoc());
2839 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002840 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002841 }
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Chris Lattner65401802009-04-25 08:28:21 +00002843 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2844 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002845 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002846 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2847 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002848 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002849 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2850 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002851 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002852 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2853 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002854 }
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Douglas Gregor42a552f2008-11-05 20:51:48 +00002856 // Rebuild the function type "R" without any type qualifiers (in
2857 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002858 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002859 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002860 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2861 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002862 Proto->isVariadic(), 0,
2863 Proto->hasExceptionSpec(),
2864 Proto->hasAnyExceptionSpec(),
2865 Proto->getNumExceptions(),
2866 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002867 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002868}
2869
Douglas Gregor72b505b2008-12-16 21:30:33 +00002870/// CheckConstructor - Checks a fully-formed constructor for
2871/// well-formedness, issuing any diagnostics required. Returns true if
2872/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002873void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002874 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002875 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2876 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002877 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002878
2879 // C++ [class.copy]p3:
2880 // A declaration of a constructor for a class X is ill-formed if
2881 // its first parameter is of type (optionally cv-qualified) X and
2882 // either there are no other parameters or else all other
2883 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002884 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002885 ((Constructor->getNumParams() == 1) ||
2886 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002887 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2888 Constructor->getTemplateSpecializationKind()
2889 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002890 QualType ParamType = Constructor->getParamDecl(0)->getType();
2891 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2892 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002893 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002894 const char *ConstRef
2895 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2896 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002897 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002898 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002899
2900 // FIXME: Rather that making the constructor invalid, we should endeavor
2901 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002902 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002903 }
2904 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002905}
2906
John McCall15442822010-08-04 01:04:25 +00002907/// CheckDestructor - Checks a fully-formed destructor definition for
2908/// well-formedness, issuing any diagnostics required. Returns true
2909/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002910bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002911 CXXRecordDecl *RD = Destructor->getParent();
2912
2913 if (Destructor->isVirtual()) {
2914 SourceLocation Loc;
2915
2916 if (!Destructor->isImplicit())
2917 Loc = Destructor->getLocation();
2918 else
2919 Loc = RD->getLocation();
2920
2921 // If we have a virtual destructor, look up the deallocation function
2922 FunctionDecl *OperatorDelete = 0;
2923 DeclarationName Name =
2924 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002925 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002926 return true;
John McCall5efd91a2010-07-03 18:33:00 +00002927
2928 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00002929
2930 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002931 }
Anders Carlsson37909802009-11-30 21:24:50 +00002932
2933 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002934}
2935
Mike Stump1eb44332009-09-09 15:08:12 +00002936static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002937FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2938 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2939 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00002940 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002941}
2942
Douglas Gregor42a552f2008-11-05 20:51:48 +00002943/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2944/// the well-formednes of the destructor declarator @p D with type @p
2945/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002946/// emit diagnostics and set the declarator to invalid. Even if this happens,
2947/// will be updated to reflect a well-formed type for the destructor and
2948/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00002949QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002950 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002951 // C++ [class.dtor]p1:
2952 // [...] A typedef-name that names a class is a class-name
2953 // (7.1.3); however, a typedef-name that names a class shall not
2954 // be used as the identifier in the declarator for a destructor
2955 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002956 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00002957 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00002958 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002959 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002960
2961 // C++ [class.dtor]p2:
2962 // A destructor is used to destroy objects of its class type. A
2963 // destructor takes no parameters, and no return type can be
2964 // specified for it (not even void). The address of a destructor
2965 // shall not be taken. A destructor shall not be static. A
2966 // destructor can be invoked for a const, volatile or const
2967 // volatile object. A destructor shall not be declared const,
2968 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00002969 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002970 if (!D.isInvalidType())
2971 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2972 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00002973 << SourceRange(D.getIdentifierLoc())
2974 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2975
John McCalld931b082010-08-26 03:08:43 +00002976 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002977 }
Chris Lattner65401802009-04-25 08:28:21 +00002978 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002979 // Destructors don't have return types, but the parser will
2980 // happily parse something like:
2981 //
2982 // class X {
2983 // float ~X();
2984 // };
2985 //
2986 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002987 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2988 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2989 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002990 }
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Chris Lattner65401802009-04-25 08:28:21 +00002992 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2993 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002994 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2996 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002997 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002998 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2999 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003000 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003001 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3002 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003003 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003004 }
3005
3006 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003007 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003008 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3009
3010 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003011 FTI.freeArgs();
3012 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003013 }
3014
Mike Stump1eb44332009-09-09 15:08:12 +00003015 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003016 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003017 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003018 D.setInvalidType();
3019 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003020
3021 // Rebuild the function type "R" without any type qualifiers or
3022 // parameters (in case any of the errors above fired) and with
3023 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003024 // types.
3025 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3026 if (!Proto)
3027 return QualType();
3028
Douglas Gregorce056bc2010-02-21 22:15:06 +00003029 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003030 Proto->hasExceptionSpec(),
3031 Proto->hasAnyExceptionSpec(),
3032 Proto->getNumExceptions(),
3033 Proto->exception_begin(),
3034 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003035}
3036
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003037/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3038/// well-formednes of the conversion function declarator @p D with
3039/// type @p R. If there are any errors in the declarator, this routine
3040/// will emit diagnostics and return true. Otherwise, it will return
3041/// false. Either way, the type @p R will be updated to reflect a
3042/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003043void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003044 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003045 // C++ [class.conv.fct]p1:
3046 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003047 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003048 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003049 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003050 if (!D.isInvalidType())
3051 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3052 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3053 << SourceRange(D.getIdentifierLoc());
3054 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003055 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003056 }
John McCalla3f81372010-04-13 00:04:31 +00003057
3058 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3059
Chris Lattner6e475012009-04-25 08:35:12 +00003060 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003061 // Conversion functions don't have return types, but the parser will
3062 // happily parse something like:
3063 //
3064 // class X {
3065 // float operator bool();
3066 // };
3067 //
3068 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003069 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3070 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3071 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003072 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003073 }
3074
John McCalla3f81372010-04-13 00:04:31 +00003075 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3076
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003077 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003078 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003079 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3080
3081 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003082 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003083 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003084 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003085 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003086 D.setInvalidType();
3087 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003088
John McCalla3f81372010-04-13 00:04:31 +00003089 // Diagnose "&operator bool()" and other such nonsense. This
3090 // is actually a gcc extension which we don't support.
3091 if (Proto->getResultType() != ConvType) {
3092 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3093 << Proto->getResultType();
3094 D.setInvalidType();
3095 ConvType = Proto->getResultType();
3096 }
3097
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003098 // C++ [class.conv.fct]p4:
3099 // The conversion-type-id shall not represent a function type nor
3100 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003101 if (ConvType->isArrayType()) {
3102 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3103 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003104 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003105 } else if (ConvType->isFunctionType()) {
3106 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3107 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003108 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003109 }
3110
3111 // Rebuild the function type "R" without any parameters (in case any
3112 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003113 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003114 if (D.isInvalidType()) {
3115 R = Context.getFunctionType(ConvType, 0, 0, false,
3116 Proto->getTypeQuals(),
3117 Proto->hasExceptionSpec(),
3118 Proto->hasAnyExceptionSpec(),
3119 Proto->getNumExceptions(),
3120 Proto->exception_begin(),
3121 Proto->getExtInfo());
3122 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003123
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003124 // C++0x explicit conversion operators.
3125 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003126 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003127 diag::warn_explicit_conversion_functions)
3128 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003129}
3130
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003131/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3132/// the declaration of the given C++ conversion function. This routine
3133/// is responsible for recording the conversion function in the C++
3134/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003135Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003136 assert(Conversion && "Expected to receive a conversion function declaration");
3137
Douglas Gregor9d350972008-12-12 08:25:50 +00003138 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003139
3140 // Make sure we aren't redeclaring the conversion function.
3141 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003142
3143 // C++ [class.conv.fct]p1:
3144 // [...] A conversion function is never used to convert a
3145 // (possibly cv-qualified) object to the (possibly cv-qualified)
3146 // same object type (or a reference to it), to a (possibly
3147 // cv-qualified) base class of that type (or a reference to it),
3148 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003149 // FIXME: Suppress this warning if the conversion function ends up being a
3150 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003151 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003152 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003153 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003154 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003155 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3156 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003157 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003158 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003159 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3160 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003161 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003162 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003163 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003164 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003165 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003166 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003167 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003168 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003169 }
3170
Douglas Gregore80622f2010-09-29 04:25:11 +00003171 if (FunctionTemplateDecl *ConversionTemplate
3172 = Conversion->getDescribedFunctionTemplate())
3173 return ConversionTemplate;
3174
John McCalld226f652010-08-21 09:40:31 +00003175 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003176}
3177
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003178//===----------------------------------------------------------------------===//
3179// Namespace Handling
3180//===----------------------------------------------------------------------===//
3181
John McCallea318642010-08-26 09:15:37 +00003182
3183
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003184/// ActOnStartNamespaceDef - This is called at the start of a namespace
3185/// definition.
John McCalld226f652010-08-21 09:40:31 +00003186Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003187 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003188 SourceLocation IdentLoc,
3189 IdentifierInfo *II,
3190 SourceLocation LBrace,
3191 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003192 // anonymous namespace starts at its left brace
3193 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3194 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003195 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003196 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003197
3198 Scope *DeclRegionScope = NamespcScope->getParent();
3199
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003200 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3201
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003202 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallea318642010-08-26 09:15:37 +00003203 PushVisibilityAttr(attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003204
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003205 if (II) {
3206 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003207 // The identifier in an original-namespace-definition shall not
3208 // have been previously defined in the declarative region in
3209 // which the original-namespace-definition appears. The
3210 // identifier in an original-namespace-definition is the name of
3211 // the namespace. Subsequently in that declarative region, it is
3212 // treated as an original-namespace-name.
3213 //
3214 // Since namespace names are unique in their scope, and we don't
3215 // look through using directives, just
3216 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3217 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003218
Douglas Gregor44b43212008-12-11 16:49:14 +00003219 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3220 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003221 if (Namespc->isInline() != OrigNS->isInline()) {
3222 // inline-ness must match
3223 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3224 << Namespc->isInline();
3225 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3226 Namespc->setInvalidDecl();
3227 // Recover by ignoring the new namespace's inline status.
3228 Namespc->setInline(OrigNS->isInline());
3229 }
3230
Douglas Gregor44b43212008-12-11 16:49:14 +00003231 // Attach this namespace decl to the chain of extended namespace
3232 // definitions.
3233 OrigNS->setNextNamespace(Namespc);
3234 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003235
Mike Stump1eb44332009-09-09 15:08:12 +00003236 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003237 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003238 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003239 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003240 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003241 } else if (PrevDecl) {
3242 // This is an invalid name redefinition.
3243 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3244 << Namespc->getDeclName();
3245 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3246 Namespc->setInvalidDecl();
3247 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003248 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003249 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003250 // This is the first "real" definition of the namespace "std", so update
3251 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003252 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003253 // We had already defined a dummy namespace "std". Link this new
3254 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003255 StdNS->setNextNamespace(Namespc);
3256 StdNS->setLocation(IdentLoc);
3257 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003258 }
3259
3260 // Make our StdNamespace cache point at the first real definition of the
3261 // "std" namespace.
3262 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003263 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003264
3265 PushOnScopeChains(Namespc, DeclRegionScope);
3266 } else {
John McCall9aeed322009-10-01 00:25:31 +00003267 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003268 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003269
3270 // Link the anonymous namespace into its parent.
3271 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003272 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003273 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3274 PrevDecl = TU->getAnonymousNamespace();
3275 TU->setAnonymousNamespace(Namespc);
3276 } else {
3277 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3278 PrevDecl = ND->getAnonymousNamespace();
3279 ND->setAnonymousNamespace(Namespc);
3280 }
3281
3282 // Link the anonymous namespace with its previous declaration.
3283 if (PrevDecl) {
3284 assert(PrevDecl->isAnonymousNamespace());
3285 assert(!PrevDecl->getNextNamespace());
3286 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3287 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003288
3289 if (Namespc->isInline() != PrevDecl->isInline()) {
3290 // inline-ness must match
3291 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3292 << Namespc->isInline();
3293 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3294 Namespc->setInvalidDecl();
3295 // Recover by ignoring the new namespace's inline status.
3296 Namespc->setInline(PrevDecl->isInline());
3297 }
John McCall5fdd7642009-12-16 02:06:49 +00003298 }
John McCall9aeed322009-10-01 00:25:31 +00003299
Douglas Gregora4181472010-03-24 00:46:35 +00003300 CurContext->addDecl(Namespc);
3301
John McCall9aeed322009-10-01 00:25:31 +00003302 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3303 // behaves as if it were replaced by
3304 // namespace unique { /* empty body */ }
3305 // using namespace unique;
3306 // namespace unique { namespace-body }
3307 // where all occurrences of 'unique' in a translation unit are
3308 // replaced by the same identifier and this identifier differs
3309 // from all other identifiers in the entire program.
3310
3311 // We just create the namespace with an empty name and then add an
3312 // implicit using declaration, just like the standard suggests.
3313 //
3314 // CodeGen enforces the "universally unique" aspect by giving all
3315 // declarations semantically contained within an anonymous
3316 // namespace internal linkage.
3317
John McCall5fdd7642009-12-16 02:06:49 +00003318 if (!PrevDecl) {
3319 UsingDirectiveDecl* UD
3320 = UsingDirectiveDecl::Create(Context, CurContext,
3321 /* 'using' */ LBrace,
3322 /* 'namespace' */ SourceLocation(),
3323 /* qualifier */ SourceRange(),
3324 /* NNS */ NULL,
3325 /* identifier */ SourceLocation(),
3326 Namespc,
3327 /* Ancestor */ CurContext);
3328 UD->setImplicit();
3329 CurContext->addDecl(UD);
3330 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003331 }
3332
3333 // Although we could have an invalid decl (i.e. the namespace name is a
3334 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003335 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3336 // for the namespace has the declarations that showed up in that particular
3337 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003338 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003339 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003340}
3341
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003342/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3343/// is a namespace alias, returns the namespace it points to.
3344static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3345 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3346 return AD->getNamespace();
3347 return dyn_cast_or_null<NamespaceDecl>(D);
3348}
3349
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003350/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3351/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003352void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003353 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3354 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3355 Namespc->setRBracLoc(RBrace);
3356 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003357 if (Namespc->hasAttr<VisibilityAttr>())
3358 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003359}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003360
John McCall384aff82010-08-25 07:42:41 +00003361CXXRecordDecl *Sema::getStdBadAlloc() const {
3362 return cast_or_null<CXXRecordDecl>(
3363 StdBadAlloc.get(Context.getExternalSource()));
3364}
3365
3366NamespaceDecl *Sema::getStdNamespace() const {
3367 return cast_or_null<NamespaceDecl>(
3368 StdNamespace.get(Context.getExternalSource()));
3369}
3370
Douglas Gregor66992202010-06-29 17:53:46 +00003371/// \brief Retrieve the special "std" namespace, which may require us to
3372/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003373NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003374 if (!StdNamespace) {
3375 // The "std" namespace has not yet been defined, so build one implicitly.
3376 StdNamespace = NamespaceDecl::Create(Context,
3377 Context.getTranslationUnitDecl(),
3378 SourceLocation(),
3379 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003380 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003381 }
3382
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003383 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003384}
3385
John McCalld226f652010-08-21 09:40:31 +00003386Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003387 SourceLocation UsingLoc,
3388 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003389 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003390 SourceLocation IdentLoc,
3391 IdentifierInfo *NamespcName,
3392 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003393 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3394 assert(NamespcName && "Invalid NamespcName.");
3395 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003396
3397 // This can only happen along a recovery path.
3398 while (S->getFlags() & Scope::TemplateParamScope)
3399 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003400 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003401
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003402 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003403 NestedNameSpecifier *Qualifier = 0;
3404 if (SS.isSet())
3405 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3406
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003407 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003408 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3409 LookupParsedName(R, S, &SS);
3410 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003411 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003412
Douglas Gregor66992202010-06-29 17:53:46 +00003413 if (R.empty()) {
3414 // Allow "using namespace std;" or "using namespace ::std;" even if
3415 // "std" hasn't been defined yet, for GCC compatibility.
3416 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3417 NamespcName->isStr("std")) {
3418 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003419 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003420 R.resolveKind();
3421 }
3422 // Otherwise, attempt typo correction.
3423 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3424 CTC_NoKeywords, 0)) {
3425 if (R.getAsSingle<NamespaceDecl>() ||
3426 R.getAsSingle<NamespaceAliasDecl>()) {
3427 if (DeclContext *DC = computeDeclContext(SS, false))
3428 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3429 << NamespcName << DC << Corrected << SS.getRange()
3430 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3431 else
3432 Diag(IdentLoc, diag::err_using_directive_suggest)
3433 << NamespcName << Corrected
3434 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3435 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3436 << Corrected;
3437
3438 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003439 } else {
3440 R.clear();
3441 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003442 }
3443 }
3444 }
3445
John McCallf36e02d2009-10-09 21:13:30 +00003446 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003447 NamedDecl *Named = R.getFoundDecl();
3448 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3449 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003450 // C++ [namespace.udir]p1:
3451 // A using-directive specifies that the names in the nominated
3452 // namespace can be used in the scope in which the
3453 // using-directive appears after the using-directive. During
3454 // unqualified name lookup (3.4.1), the names appear as if they
3455 // were declared in the nearest enclosing namespace which
3456 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003457 // namespace. [Note: in this context, "contains" means "contains
3458 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003459
3460 // Find enclosing context containing both using-directive and
3461 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003462 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003463 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3464 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3465 CommonAncestor = CommonAncestor->getParent();
3466
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003467 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003468 SS.getRange(),
3469 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003470 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003471 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003472 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003473 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003474 }
3475
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003476 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003477 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003478}
3479
3480void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3481 // If scope has associated entity, then using directive is at namespace
3482 // or translation unit scope. We add UsingDirectiveDecls, into
3483 // it's lookup structure.
3484 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003485 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003486 else
3487 // Otherwise it is block-sope. using-directives will affect lookup
3488 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003489 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003490}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003491
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003492
John McCalld226f652010-08-21 09:40:31 +00003493Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003494 AccessSpecifier AS,
3495 bool HasUsingKeyword,
3496 SourceLocation UsingLoc,
3497 CXXScopeSpec &SS,
3498 UnqualifiedId &Name,
3499 AttributeList *AttrList,
3500 bool IsTypeName,
3501 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003502 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Douglas Gregor12c118a2009-11-04 16:30:06 +00003504 switch (Name.getKind()) {
3505 case UnqualifiedId::IK_Identifier:
3506 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003507 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003508 case UnqualifiedId::IK_ConversionFunctionId:
3509 break;
3510
3511 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003512 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003513 // C++0x inherited constructors.
3514 if (getLangOptions().CPlusPlus0x) break;
3515
Douglas Gregor12c118a2009-11-04 16:30:06 +00003516 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3517 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003518 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003519
3520 case UnqualifiedId::IK_DestructorName:
3521 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3522 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003523 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003524
3525 case UnqualifiedId::IK_TemplateId:
3526 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3527 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003528 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003529 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003530
3531 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3532 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003533 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003534 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003535
John McCall60fa3cf2009-12-11 02:10:03 +00003536 // Warn about using declarations.
3537 // TODO: store that the declaration was written without 'using' and
3538 // talk about access decls instead of using decls in the
3539 // diagnostics.
3540 if (!HasUsingKeyword) {
3541 UsingLoc = Name.getSourceRange().getBegin();
3542
3543 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003544 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003545 }
3546
John McCall9488ea12009-11-17 05:59:44 +00003547 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003548 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003549 /* IsInstantiation */ false,
3550 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003551 if (UD)
3552 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003553
John McCalld226f652010-08-21 09:40:31 +00003554 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003555}
3556
Douglas Gregor09acc982010-07-07 23:08:52 +00003557/// \brief Determine whether a using declaration considers the given
3558/// declarations as "equivalent", e.g., if they are redeclarations of
3559/// the same entity or are both typedefs of the same type.
3560static bool
3561IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3562 bool &SuppressRedeclaration) {
3563 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3564 SuppressRedeclaration = false;
3565 return true;
3566 }
3567
3568 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3569 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3570 SuppressRedeclaration = true;
3571 return Context.hasSameType(TD1->getUnderlyingType(),
3572 TD2->getUnderlyingType());
3573 }
3574
3575 return false;
3576}
3577
3578
John McCall9f54ad42009-12-10 09:41:52 +00003579/// Determines whether to create a using shadow decl for a particular
3580/// decl, given the set of decls existing prior to this using lookup.
3581bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3582 const LookupResult &Previous) {
3583 // Diagnose finding a decl which is not from a base class of the
3584 // current class. We do this now because there are cases where this
3585 // function will silently decide not to build a shadow decl, which
3586 // will pre-empt further diagnostics.
3587 //
3588 // We don't need to do this in C++0x because we do the check once on
3589 // the qualifier.
3590 //
3591 // FIXME: diagnose the following if we care enough:
3592 // struct A { int foo; };
3593 // struct B : A { using A::foo; };
3594 // template <class T> struct C : A {};
3595 // template <class T> struct D : C<T> { using B::foo; } // <---
3596 // This is invalid (during instantiation) in C++03 because B::foo
3597 // resolves to the using decl in B, which is not a base class of D<T>.
3598 // We can't diagnose it immediately because C<T> is an unknown
3599 // specialization. The UsingShadowDecl in D<T> then points directly
3600 // to A::foo, which will look well-formed when we instantiate.
3601 // The right solution is to not collapse the shadow-decl chain.
3602 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3603 DeclContext *OrigDC = Orig->getDeclContext();
3604
3605 // Handle enums and anonymous structs.
3606 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3607 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3608 while (OrigRec->isAnonymousStructOrUnion())
3609 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3610
3611 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3612 if (OrigDC == CurContext) {
3613 Diag(Using->getLocation(),
3614 diag::err_using_decl_nested_name_specifier_is_current_class)
3615 << Using->getNestedNameRange();
3616 Diag(Orig->getLocation(), diag::note_using_decl_target);
3617 return true;
3618 }
3619
3620 Diag(Using->getNestedNameRange().getBegin(),
3621 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3622 << Using->getTargetNestedNameDecl()
3623 << cast<CXXRecordDecl>(CurContext)
3624 << Using->getNestedNameRange();
3625 Diag(Orig->getLocation(), diag::note_using_decl_target);
3626 return true;
3627 }
3628 }
3629
3630 if (Previous.empty()) return false;
3631
3632 NamedDecl *Target = Orig;
3633 if (isa<UsingShadowDecl>(Target))
3634 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3635
John McCalld7533ec2009-12-11 02:33:26 +00003636 // If the target happens to be one of the previous declarations, we
3637 // don't have a conflict.
3638 //
3639 // FIXME: but we might be increasing its access, in which case we
3640 // should redeclare it.
3641 NamedDecl *NonTag = 0, *Tag = 0;
3642 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3643 I != E; ++I) {
3644 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003645 bool Result;
3646 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3647 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003648
3649 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3650 }
3651
John McCall9f54ad42009-12-10 09:41:52 +00003652 if (Target->isFunctionOrFunctionTemplate()) {
3653 FunctionDecl *FD;
3654 if (isa<FunctionTemplateDecl>(Target))
3655 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3656 else
3657 FD = cast<FunctionDecl>(Target);
3658
3659 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003660 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003661 case Ovl_Overload:
3662 return false;
3663
3664 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003665 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003666 break;
3667
3668 // We found a decl with the exact signature.
3669 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003670 // If we're in a record, we want to hide the target, so we
3671 // return true (without a diagnostic) to tell the caller not to
3672 // build a shadow decl.
3673 if (CurContext->isRecord())
3674 return true;
3675
3676 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003677 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003678 break;
3679 }
3680
3681 Diag(Target->getLocation(), diag::note_using_decl_target);
3682 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3683 return true;
3684 }
3685
3686 // Target is not a function.
3687
John McCall9f54ad42009-12-10 09:41:52 +00003688 if (isa<TagDecl>(Target)) {
3689 // No conflict between a tag and a non-tag.
3690 if (!Tag) return false;
3691
John McCall41ce66f2009-12-10 19:51:03 +00003692 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003693 Diag(Target->getLocation(), diag::note_using_decl_target);
3694 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3695 return true;
3696 }
3697
3698 // No conflict between a tag and a non-tag.
3699 if (!NonTag) 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(NonTag->getLocation(), diag::note_using_decl_conflict);
3704 return true;
3705}
3706
John McCall9488ea12009-11-17 05:59:44 +00003707/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003708UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003709 UsingDecl *UD,
3710 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003711
3712 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003713 NamedDecl *Target = Orig;
3714 if (isa<UsingShadowDecl>(Target)) {
3715 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3716 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003717 }
3718
3719 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003720 = UsingShadowDecl::Create(Context, CurContext,
3721 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003722 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003723
3724 Shadow->setAccess(UD->getAccess());
3725 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3726 Shadow->setInvalidDecl();
3727
John McCall9488ea12009-11-17 05:59:44 +00003728 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003729 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003730 else
John McCall604e7f12009-12-08 07:46:18 +00003731 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003732
John McCall604e7f12009-12-08 07:46:18 +00003733
John McCall9f54ad42009-12-10 09:41:52 +00003734 return Shadow;
3735}
John McCall604e7f12009-12-08 07:46:18 +00003736
John McCall9f54ad42009-12-10 09:41:52 +00003737/// Hides a using shadow declaration. This is required by the current
3738/// using-decl implementation when a resolvable using declaration in a
3739/// class is followed by a declaration which would hide or override
3740/// one or more of the using decl's targets; for example:
3741///
3742/// struct Base { void foo(int); };
3743/// struct Derived : Base {
3744/// using Base::foo;
3745/// void foo(int);
3746/// };
3747///
3748/// The governing language is C++03 [namespace.udecl]p12:
3749///
3750/// When a using-declaration brings names from a base class into a
3751/// derived class scope, member functions in the derived class
3752/// override and/or hide member functions with the same name and
3753/// parameter types in a base class (rather than conflicting).
3754///
3755/// There are two ways to implement this:
3756/// (1) optimistically create shadow decls when they're not hidden
3757/// by existing declarations, or
3758/// (2) don't create any shadow decls (or at least don't make them
3759/// visible) until we've fully parsed/instantiated the class.
3760/// The problem with (1) is that we might have to retroactively remove
3761/// a shadow decl, which requires several O(n) operations because the
3762/// decl structures are (very reasonably) not designed for removal.
3763/// (2) avoids this but is very fiddly and phase-dependent.
3764void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003765 if (Shadow->getDeclName().getNameKind() ==
3766 DeclarationName::CXXConversionFunctionName)
3767 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3768
John McCall9f54ad42009-12-10 09:41:52 +00003769 // Remove it from the DeclContext...
3770 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003771
John McCall9f54ad42009-12-10 09:41:52 +00003772 // ...and the scope, if applicable...
3773 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003774 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003775 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003776 }
3777
John McCall9f54ad42009-12-10 09:41:52 +00003778 // ...and the using decl.
3779 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3780
3781 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003782 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003783}
3784
John McCall7ba107a2009-11-18 02:36:19 +00003785/// Builds a using declaration.
3786///
3787/// \param IsInstantiation - Whether this call arises from an
3788/// instantiation of an unresolved using declaration. We treat
3789/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003790NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3791 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003792 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003793 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003794 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003795 bool IsInstantiation,
3796 bool IsTypeName,
3797 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003798 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003799 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003800 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003801
Anders Carlsson550b14b2009-08-28 05:49:21 +00003802 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00003803
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003804 if (SS.isEmpty()) {
3805 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003806 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003807 }
Mike Stump1eb44332009-09-09 15:08:12 +00003808
John McCall9f54ad42009-12-10 09:41:52 +00003809 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003810 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003811 ForRedeclaration);
3812 Previous.setHideTags(false);
3813 if (S) {
3814 LookupName(Previous, S);
3815
3816 // It is really dumb that we have to do this.
3817 LookupResult::Filter F = Previous.makeFilter();
3818 while (F.hasNext()) {
3819 NamedDecl *D = F.next();
3820 if (!isDeclInScope(D, CurContext, S))
3821 F.erase();
3822 }
3823 F.done();
3824 } else {
3825 assert(IsInstantiation && "no scope in non-instantiation");
3826 assert(CurContext->isRecord() && "scope not record in instantiation");
3827 LookupQualifiedName(Previous, CurContext);
3828 }
3829
Mike Stump1eb44332009-09-09 15:08:12 +00003830 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003831 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3832
John McCall9f54ad42009-12-10 09:41:52 +00003833 // Check for invalid redeclarations.
3834 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3835 return 0;
3836
3837 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003838 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3839 return 0;
3840
John McCallaf8e6ed2009-11-12 03:15:40 +00003841 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003842 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003843 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003844 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003845 // FIXME: not all declaration name kinds are legal here
3846 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3847 UsingLoc, TypenameLoc,
3848 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003849 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003850 } else {
3851 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003852 UsingLoc, SS.getRange(),
3853 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003854 }
John McCalled976492009-12-04 22:46:56 +00003855 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003856 D = UsingDecl::Create(Context, CurContext,
3857 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003858 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003859 }
John McCalled976492009-12-04 22:46:56 +00003860 D->setAccess(AS);
3861 CurContext->addDecl(D);
3862
3863 if (!LookupContext) return D;
3864 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003865
John McCall77bb1aa2010-05-01 00:40:08 +00003866 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003867 UD->setInvalidDecl();
3868 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003869 }
3870
John McCall604e7f12009-12-08 07:46:18 +00003871 // Look up the target name.
3872
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003873 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003874
John McCall604e7f12009-12-08 07:46:18 +00003875 // Unlike most lookups, we don't always want to hide tag
3876 // declarations: tag names are visible through the using declaration
3877 // even if hidden by ordinary names, *except* in a dependent context
3878 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003879 if (!IsInstantiation)
3880 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003881
John McCalla24dc2e2009-11-17 02:14:36 +00003882 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003883
John McCallf36e02d2009-10-09 21:13:30 +00003884 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003885 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003886 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003887 UD->setInvalidDecl();
3888 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003889 }
3890
John McCalled976492009-12-04 22:46:56 +00003891 if (R.isAmbiguous()) {
3892 UD->setInvalidDecl();
3893 return UD;
3894 }
Mike Stump1eb44332009-09-09 15:08:12 +00003895
John McCall7ba107a2009-11-18 02:36:19 +00003896 if (IsTypeName) {
3897 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003898 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003899 Diag(IdentLoc, diag::err_using_typename_non_type);
3900 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3901 Diag((*I)->getUnderlyingDecl()->getLocation(),
3902 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003903 UD->setInvalidDecl();
3904 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003905 }
3906 } else {
3907 // If we asked for a non-typename and we got a type, error out,
3908 // but only if this is an instantiation of an unresolved using
3909 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003910 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003911 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3912 Diag(R.getFoundDecl()->getLocation(), 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 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003916 }
3917
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003918 // C++0x N2914 [namespace.udecl]p6:
3919 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003920 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003921 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3922 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003923 UD->setInvalidDecl();
3924 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926
John McCall9f54ad42009-12-10 09:41:52 +00003927 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3928 if (!CheckUsingShadowDecl(UD, *I, Previous))
3929 BuildUsingShadowDecl(S, UD, *I);
3930 }
John McCall9488ea12009-11-17 05:59:44 +00003931
3932 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003933}
3934
John McCall9f54ad42009-12-10 09:41:52 +00003935/// Checks that the given using declaration is not an invalid
3936/// redeclaration. Note that this is checking only for the using decl
3937/// itself, not for any ill-formedness among the UsingShadowDecls.
3938bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3939 bool isTypeName,
3940 const CXXScopeSpec &SS,
3941 SourceLocation NameLoc,
3942 const LookupResult &Prev) {
3943 // C++03 [namespace.udecl]p8:
3944 // C++0x [namespace.udecl]p10:
3945 // A using-declaration is a declaration and can therefore be used
3946 // repeatedly where (and only where) multiple declarations are
3947 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00003948 //
John McCall8a726212010-11-29 18:01:58 +00003949 // That's in non-member contexts.
3950 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00003951 return false;
3952
3953 NestedNameSpecifier *Qual
3954 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3955
3956 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3957 NamedDecl *D = *I;
3958
3959 bool DTypename;
3960 NestedNameSpecifier *DQual;
3961 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3962 DTypename = UD->isTypeName();
3963 DQual = UD->getTargetNestedNameDecl();
3964 } else if (UnresolvedUsingValueDecl *UD
3965 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3966 DTypename = false;
3967 DQual = UD->getTargetNestedNameSpecifier();
3968 } else if (UnresolvedUsingTypenameDecl *UD
3969 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3970 DTypename = true;
3971 DQual = UD->getTargetNestedNameSpecifier();
3972 } else continue;
3973
3974 // using decls differ if one says 'typename' and the other doesn't.
3975 // FIXME: non-dependent using decls?
3976 if (isTypeName != DTypename) continue;
3977
3978 // using decls differ if they name different scopes (but note that
3979 // template instantiation can cause this check to trigger when it
3980 // didn't before instantiation).
3981 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3982 Context.getCanonicalNestedNameSpecifier(DQual))
3983 continue;
3984
3985 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003986 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003987 return true;
3988 }
3989
3990 return false;
3991}
3992
John McCall604e7f12009-12-08 07:46:18 +00003993
John McCalled976492009-12-04 22:46:56 +00003994/// Checks that the given nested-name qualifier used in a using decl
3995/// in the current context is appropriately related to the current
3996/// scope. If an error is found, diagnoses it and returns true.
3997bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3998 const CXXScopeSpec &SS,
3999 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004000 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004001
John McCall604e7f12009-12-08 07:46:18 +00004002 if (!CurContext->isRecord()) {
4003 // C++03 [namespace.udecl]p3:
4004 // C++0x [namespace.udecl]p8:
4005 // A using-declaration for a class member shall be a member-declaration.
4006
4007 // If we weren't able to compute a valid scope, it must be a
4008 // dependent class scope.
4009 if (!NamedContext || NamedContext->isRecord()) {
4010 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4011 << SS.getRange();
4012 return true;
4013 }
4014
4015 // Otherwise, everything is known to be fine.
4016 return false;
4017 }
4018
4019 // The current scope is a record.
4020
4021 // If the named context is dependent, we can't decide much.
4022 if (!NamedContext) {
4023 // FIXME: in C++0x, we can diagnose if we can prove that the
4024 // nested-name-specifier does not refer to a base class, which is
4025 // still possible in some cases.
4026
4027 // Otherwise we have to conservatively report that things might be
4028 // okay.
4029 return false;
4030 }
4031
4032 if (!NamedContext->isRecord()) {
4033 // Ideally this would point at the last name in the specifier,
4034 // but we don't have that level of source info.
4035 Diag(SS.getRange().getBegin(),
4036 diag::err_using_decl_nested_name_specifier_is_not_class)
4037 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4038 return true;
4039 }
4040
4041 if (getLangOptions().CPlusPlus0x) {
4042 // C++0x [namespace.udecl]p3:
4043 // In a using-declaration used as a member-declaration, the
4044 // nested-name-specifier shall name a base class of the class
4045 // being defined.
4046
4047 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4048 cast<CXXRecordDecl>(NamedContext))) {
4049 if (CurContext == NamedContext) {
4050 Diag(NameLoc,
4051 diag::err_using_decl_nested_name_specifier_is_current_class)
4052 << SS.getRange();
4053 return true;
4054 }
4055
4056 Diag(SS.getRange().getBegin(),
4057 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4058 << (NestedNameSpecifier*) SS.getScopeRep()
4059 << cast<CXXRecordDecl>(CurContext)
4060 << SS.getRange();
4061 return true;
4062 }
4063
4064 return false;
4065 }
4066
4067 // C++03 [namespace.udecl]p4:
4068 // A using-declaration used as a member-declaration shall refer
4069 // to a member of a base class of the class being defined [etc.].
4070
4071 // Salient point: SS doesn't have to name a base class as long as
4072 // lookup only finds members from base classes. Therefore we can
4073 // diagnose here only if we can prove that that can't happen,
4074 // i.e. if the class hierarchies provably don't intersect.
4075
4076 // TODO: it would be nice if "definitely valid" results were cached
4077 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4078 // need to be repeated.
4079
4080 struct UserData {
4081 llvm::DenseSet<const CXXRecordDecl*> Bases;
4082
4083 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4084 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4085 Data->Bases.insert(Base);
4086 return true;
4087 }
4088
4089 bool hasDependentBases(const CXXRecordDecl *Class) {
4090 return !Class->forallBases(collect, this);
4091 }
4092
4093 /// Returns true if the base is dependent or is one of the
4094 /// accumulated base classes.
4095 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4096 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4097 return !Data->Bases.count(Base);
4098 }
4099
4100 bool mightShareBases(const CXXRecordDecl *Class) {
4101 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4102 }
4103 };
4104
4105 UserData Data;
4106
4107 // Returns false if we find a dependent base.
4108 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4109 return false;
4110
4111 // Returns false if the class has a dependent base or if it or one
4112 // of its bases is present in the base set of the current context.
4113 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4114 return false;
4115
4116 Diag(SS.getRange().getBegin(),
4117 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4118 << (NestedNameSpecifier*) SS.getScopeRep()
4119 << cast<CXXRecordDecl>(CurContext)
4120 << SS.getRange();
4121
4122 return true;
John McCalled976492009-12-04 22:46:56 +00004123}
4124
John McCalld226f652010-08-21 09:40:31 +00004125Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004126 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004127 SourceLocation AliasLoc,
4128 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004129 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004130 SourceLocation IdentLoc,
4131 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Anders Carlsson81c85c42009-03-28 23:53:49 +00004133 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004134 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4135 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004136
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004137 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004138 NamedDecl *PrevDecl
4139 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4140 ForRedeclaration);
4141 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4142 PrevDecl = 0;
4143
4144 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004145 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004146 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004147 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004148 // FIXME: At some point, we'll want to create the (redundant)
4149 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004150 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004151 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004152 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004153 }
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004155 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4156 diag::err_redefinition_different_kind;
4157 Diag(AliasLoc, DiagID) << Alias;
4158 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004159 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004160 }
4161
John McCalla24dc2e2009-11-17 02:14:36 +00004162 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004163 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004164
John McCallf36e02d2009-10-09 21:13:30 +00004165 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004166 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4167 CTC_NoKeywords, 0)) {
4168 if (R.getAsSingle<NamespaceDecl>() ||
4169 R.getAsSingle<NamespaceAliasDecl>()) {
4170 if (DeclContext *DC = computeDeclContext(SS, false))
4171 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4172 << Ident << DC << Corrected << SS.getRange()
4173 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4174 else
4175 Diag(IdentLoc, diag::err_using_directive_suggest)
4176 << Ident << Corrected
4177 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4178
4179 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4180 << Corrected;
4181
4182 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004183 } else {
4184 R.clear();
4185 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004186 }
4187 }
4188
4189 if (R.empty()) {
4190 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004191 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004192 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004193 }
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004195 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004196 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4197 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004198 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004199 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004200
John McCall3dbd3d52010-02-16 06:53:13 +00004201 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004202 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004203}
4204
Douglas Gregor39957dc2010-05-01 15:04:51 +00004205namespace {
4206 /// \brief Scoped object used to handle the state changes required in Sema
4207 /// to implicitly define the body of a C++ member function;
4208 class ImplicitlyDefinedFunctionScope {
4209 Sema &S;
4210 DeclContext *PreviousContext;
4211
4212 public:
4213 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4214 : S(S), PreviousContext(S.CurContext)
4215 {
4216 S.CurContext = Method;
4217 S.PushFunctionScope();
4218 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4219 }
4220
4221 ~ImplicitlyDefinedFunctionScope() {
4222 S.PopExpressionEvaluationContext();
4223 S.PopFunctionOrBlockScope();
4224 S.CurContext = PreviousContext;
4225 }
4226 };
4227}
4228
Sebastian Redl751025d2010-09-13 22:02:47 +00004229static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4230 CXXRecordDecl *D) {
4231 ASTContext &Context = Self.Context;
4232 QualType ClassType = Context.getTypeDeclType(D);
4233 DeclarationName ConstructorName
4234 = Context.DeclarationNames.getCXXConstructorName(
4235 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4236
4237 DeclContext::lookup_const_iterator Con, ConEnd;
4238 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4239 Con != ConEnd; ++Con) {
4240 // FIXME: In C++0x, a constructor template can be a default constructor.
4241 if (isa<FunctionTemplateDecl>(*Con))
4242 continue;
4243
4244 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4245 if (Constructor->isDefaultConstructor())
4246 return Constructor;
4247 }
4248 return 0;
4249}
4250
Douglas Gregor23c94db2010-07-02 17:43:08 +00004251CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4252 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004253 // C++ [class.ctor]p5:
4254 // A default constructor for a class X is a constructor of class X
4255 // that can be called without an argument. If there is no
4256 // user-declared constructor for class X, a default constructor is
4257 // implicitly declared. An implicitly-declared default constructor
4258 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004259 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4260 "Should not build implicit default constructor!");
4261
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004262 // C++ [except.spec]p14:
4263 // An implicitly declared special member function (Clause 12) shall have an
4264 // exception-specification. [...]
4265 ImplicitExceptionSpecification ExceptSpec(Context);
4266
4267 // Direct base-class destructors.
4268 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4269 BEnd = ClassDecl->bases_end();
4270 B != BEnd; ++B) {
4271 if (B->isVirtual()) // Handled below.
4272 continue;
4273
Douglas Gregor18274032010-07-03 00:47:00 +00004274 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4275 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4276 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4277 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004278 else if (CXXConstructorDecl *Constructor
4279 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004280 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004281 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004282 }
4283
4284 // Virtual base-class destructors.
4285 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4286 BEnd = ClassDecl->vbases_end();
4287 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004288 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4289 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4290 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4291 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4292 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004293 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004294 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004295 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004296 }
4297
4298 // Field destructors.
4299 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4300 FEnd = ClassDecl->field_end();
4301 F != FEnd; ++F) {
4302 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004303 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4304 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4305 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4306 ExceptSpec.CalledDecl(
4307 DeclareImplicitDefaultConstructor(FieldClassDecl));
4308 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004309 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004310 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004311 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004312 }
4313
4314
4315 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004316 CanQualType ClassType
4317 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4318 DeclarationName Name
4319 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004320 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004321 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004322 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004323 Context.getFunctionType(Context.VoidTy,
4324 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004325 ExceptSpec.hasExceptionSpecification(),
4326 ExceptSpec.hasAnyExceptionSpecification(),
4327 ExceptSpec.size(),
4328 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004329 FunctionType::ExtInfo()),
4330 /*TInfo=*/0,
4331 /*isExplicit=*/false,
4332 /*isInline=*/true,
4333 /*isImplicitlyDeclared=*/true);
4334 DefaultCon->setAccess(AS_public);
4335 DefaultCon->setImplicit();
4336 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004337
4338 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004339 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4340
Douglas Gregor23c94db2010-07-02 17:43:08 +00004341 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004342 PushOnScopeChains(DefaultCon, S, false);
4343 ClassDecl->addDecl(DefaultCon);
4344
Douglas Gregor32df23e2010-07-01 22:02:46 +00004345 return DefaultCon;
4346}
4347
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004348void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4349 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004350 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004351 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004352 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004354 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004355 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004356
Douglas Gregor39957dc2010-05-01 15:04:51 +00004357 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004358 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004359 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4360 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004361 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004362 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004363 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004364 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004365 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004366
4367 SourceLocation Loc = Constructor->getLocation();
4368 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4369
4370 Constructor->setUsed();
4371 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004372}
4373
Douglas Gregor23c94db2010-07-02 17:43:08 +00004374CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004375 // C++ [class.dtor]p2:
4376 // If a class has no user-declared destructor, a destructor is
4377 // declared implicitly. An implicitly-declared destructor is an
4378 // inline public member of its class.
4379
4380 // C++ [except.spec]p14:
4381 // An implicitly declared special member function (Clause 12) shall have
4382 // an exception-specification.
4383 ImplicitExceptionSpecification ExceptSpec(Context);
4384
4385 // Direct base-class destructors.
4386 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4387 BEnd = ClassDecl->bases_end();
4388 B != BEnd; ++B) {
4389 if (B->isVirtual()) // Handled below.
4390 continue;
4391
4392 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4393 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004394 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004395 }
4396
4397 // Virtual base-class destructors.
4398 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4399 BEnd = ClassDecl->vbases_end();
4400 B != BEnd; ++B) {
4401 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4402 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004403 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004404 }
4405
4406 // Field destructors.
4407 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4408 FEnd = ClassDecl->field_end();
4409 F != FEnd; ++F) {
4410 if (const RecordType *RecordTy
4411 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4412 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004413 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004414 }
4415
Douglas Gregor4923aa22010-07-02 20:37:36 +00004416 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004417 QualType Ty = Context.getFunctionType(Context.VoidTy,
4418 0, 0, false, 0,
4419 ExceptSpec.hasExceptionSpecification(),
4420 ExceptSpec.hasAnyExceptionSpecification(),
4421 ExceptSpec.size(),
4422 ExceptSpec.data(),
4423 FunctionType::ExtInfo());
4424
4425 CanQualType ClassType
4426 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4427 DeclarationName Name
4428 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004429 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004430 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004431 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004432 /*isInline=*/true,
4433 /*isImplicitlyDeclared=*/true);
4434 Destructor->setAccess(AS_public);
4435 Destructor->setImplicit();
4436 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004437
4438 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004439 ++ASTContext::NumImplicitDestructorsDeclared;
4440
4441 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004442 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004443 PushOnScopeChains(Destructor, S, false);
4444 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004445
4446 // This could be uniqued if it ever proves significant.
4447 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4448
4449 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004450
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004451 return Destructor;
4452}
4453
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004454void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004455 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004456 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004457 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004458 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004459 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004460
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004461 if (Destructor->isInvalidDecl())
4462 return;
4463
Douglas Gregor39957dc2010-05-01 15:04:51 +00004464 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004465
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004466 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004467 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4468 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004469
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004470 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004471 Diag(CurrentLocation, diag::note_member_synthesized_at)
4472 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4473
4474 Destructor->setInvalidDecl();
4475 return;
4476 }
4477
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004478 SourceLocation Loc = Destructor->getLocation();
4479 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4480
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004481 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004482 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004483}
4484
Douglas Gregor06a9f362010-05-01 20:49:11 +00004485/// \brief Builds a statement that copies the given entity from \p From to
4486/// \c To.
4487///
4488/// This routine is used to copy the members of a class with an
4489/// implicitly-declared copy assignment operator. When the entities being
4490/// copied are arrays, this routine builds for loops to copy them.
4491///
4492/// \param S The Sema object used for type-checking.
4493///
4494/// \param Loc The location where the implicit copy is being generated.
4495///
4496/// \param T The type of the expressions being copied. Both expressions must
4497/// have this type.
4498///
4499/// \param To The expression we are copying to.
4500///
4501/// \param From The expression we are copying from.
4502///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004503/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4504/// Otherwise, it's a non-static member subobject.
4505///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004506/// \param Depth Internal parameter recording the depth of the recursion.
4507///
4508/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004509static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004510BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004511 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004512 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004513 // C++0x [class.copy]p30:
4514 // Each subobject is assigned in the manner appropriate to its type:
4515 //
4516 // - if the subobject is of class type, the copy assignment operator
4517 // for the class is used (as if by explicit qualification; that is,
4518 // ignoring any possible virtual overriding functions in more derived
4519 // classes);
4520 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4521 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4522
4523 // Look for operator=.
4524 DeclarationName Name
4525 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4526 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4527 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4528
4529 // Filter out any result that isn't a copy-assignment operator.
4530 LookupResult::Filter F = OpLookup.makeFilter();
4531 while (F.hasNext()) {
4532 NamedDecl *D = F.next();
4533 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4534 if (Method->isCopyAssignmentOperator())
4535 continue;
4536
4537 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004538 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004539 F.done();
4540
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004541 // Suppress the protected check (C++ [class.protected]) for each of the
4542 // assignment operators we found. This strange dance is required when
4543 // we're assigning via a base classes's copy-assignment operator. To
4544 // ensure that we're getting the right base class subobject (without
4545 // ambiguities), we need to cast "this" to that subobject type; to
4546 // ensure that we don't go through the virtual call mechanism, we need
4547 // to qualify the operator= name with the base class (see below). However,
4548 // this means that if the base class has a protected copy assignment
4549 // operator, the protected member access check will fail. So, we
4550 // rewrite "protected" access to "public" access in this case, since we
4551 // know by construction that we're calling from a derived class.
4552 if (CopyingBaseSubobject) {
4553 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4554 L != LEnd; ++L) {
4555 if (L.getAccess() == AS_protected)
4556 L.setAccess(AS_public);
4557 }
4558 }
4559
Douglas Gregor06a9f362010-05-01 20:49:11 +00004560 // Create the nested-name-specifier that will be used to qualify the
4561 // reference to operator=; this is required to suppress the virtual
4562 // call mechanism.
4563 CXXScopeSpec SS;
4564 SS.setRange(Loc);
4565 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4566 T.getTypePtr()));
4567
4568 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004569 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004570 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004571 /*FirstQualifierInScope=*/0, OpLookup,
4572 /*TemplateArgs=*/0,
4573 /*SuppressQualifierCheck=*/true);
4574 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004575 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004576
4577 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004578
John McCall60d7b3a2010-08-24 06:29:42 +00004579 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004580 OpEqualRef.takeAs<Expr>(),
4581 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004582 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004583 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004584
4585 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004586 }
John McCallb0207482010-03-16 06:11:48 +00004587
Douglas Gregor06a9f362010-05-01 20:49:11 +00004588 // - if the subobject is of scalar type, the built-in assignment
4589 // operator is used.
4590 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4591 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004592 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004593 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004594 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004595
4596 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004597 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004598
4599 // - if the subobject is an array, each element is assigned, in the
4600 // manner appropriate to the element type;
4601
4602 // Construct a loop over the array bounds, e.g.,
4603 //
4604 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4605 //
4606 // that will copy each of the array elements.
4607 QualType SizeType = S.Context.getSizeType();
4608
4609 // Create the iteration variable.
4610 IdentifierInfo *IterationVarName = 0;
4611 {
4612 llvm::SmallString<8> Str;
4613 llvm::raw_svector_ostream OS(Str);
4614 OS << "__i" << Depth;
4615 IterationVarName = &S.Context.Idents.get(OS.str());
4616 }
4617 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4618 IterationVarName, SizeType,
4619 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004620 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004621
4622 // Initialize the iteration variable to zero.
4623 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004624 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004625
4626 // Create a reference to the iteration variable; we'll use this several
4627 // times throughout.
4628 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00004629 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004630 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4631
4632 // Create the DeclStmt that holds the iteration variable.
4633 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4634
4635 // Create the comparison against the array bound.
4636 llvm::APInt Upper = ArrayTy->getSize();
4637 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004638 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00004639 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00004640 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4641 BO_NE, S.Context.BoolTy,
4642 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004643
4644 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004645 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00004646 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4647 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004648
4649 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004650 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4651 IterationVarRef, Loc));
4652 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4653 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004654
4655 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00004656 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4657 To, From, CopyingBaseSubobject,
4658 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004659 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004660 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004661
4662 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004663 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004664 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004665 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004666 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004667}
4668
Douglas Gregora376d102010-07-02 21:50:04 +00004669/// \brief Determine whether the given class has a copy assignment operator
4670/// that accepts a const-qualified argument.
4671static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4672 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4673
4674 if (!Class->hasDeclaredCopyAssignment())
4675 S.DeclareImplicitCopyAssignment(Class);
4676
4677 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4678 DeclarationName OpName
4679 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4680
4681 DeclContext::lookup_const_iterator Op, OpEnd;
4682 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4683 // C++ [class.copy]p9:
4684 // A user-declared copy assignment operator is a non-static non-template
4685 // member function of class X with exactly one parameter of type X, X&,
4686 // const X&, volatile X& or const volatile X&.
4687 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4688 if (!Method)
4689 continue;
4690
4691 if (Method->isStatic())
4692 continue;
4693 if (Method->getPrimaryTemplate())
4694 continue;
4695 const FunctionProtoType *FnType =
4696 Method->getType()->getAs<FunctionProtoType>();
4697 assert(FnType && "Overloaded operator has no prototype.");
4698 // Don't assert on this; an invalid decl might have been left in the AST.
4699 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4700 continue;
4701 bool AcceptsConst = true;
4702 QualType ArgType = FnType->getArgType(0);
4703 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4704 ArgType = Ref->getPointeeType();
4705 // Is it a non-const lvalue reference?
4706 if (!ArgType.isConstQualified())
4707 AcceptsConst = false;
4708 }
4709 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4710 continue;
4711
4712 // We have a single argument of type cv X or cv X&, i.e. we've found the
4713 // copy assignment operator. Return whether it accepts const arguments.
4714 return AcceptsConst;
4715 }
4716 assert(Class->isInvalidDecl() &&
4717 "No copy assignment operator declared in valid code.");
4718 return false;
4719}
4720
Douglas Gregor23c94db2010-07-02 17:43:08 +00004721CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004722 // Note: The following rules are largely analoguous to the copy
4723 // constructor rules. Note that virtual bases are not taken into account
4724 // for determining the argument type of the operator. Note also that
4725 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004726
4727
Douglas Gregord3c35902010-07-01 16:36:15 +00004728 // C++ [class.copy]p10:
4729 // If the class definition does not explicitly declare a copy
4730 // assignment operator, one is declared implicitly.
4731 // The implicitly-defined copy assignment operator for a class X
4732 // will have the form
4733 //
4734 // X& X::operator=(const X&)
4735 //
4736 // if
4737 bool HasConstCopyAssignment = true;
4738
4739 // -- each direct base class B of X has a copy assignment operator
4740 // whose parameter is of type const B&, const volatile B& or B,
4741 // and
4742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4743 BaseEnd = ClassDecl->bases_end();
4744 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4745 assert(!Base->getType()->isDependentType() &&
4746 "Cannot generate implicit members for class with dependent bases.");
4747 const CXXRecordDecl *BaseClassDecl
4748 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004749 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004750 }
4751
4752 // -- for all the nonstatic data members of X that are of a class
4753 // type M (or array thereof), each such class type has a copy
4754 // assignment operator whose parameter is of type const M&,
4755 // const volatile M& or M.
4756 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4757 FieldEnd = ClassDecl->field_end();
4758 HasConstCopyAssignment && Field != FieldEnd;
4759 ++Field) {
4760 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4761 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4762 const CXXRecordDecl *FieldClassDecl
4763 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004764 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004765 }
4766 }
4767
4768 // Otherwise, the implicitly declared copy assignment operator will
4769 // have the form
4770 //
4771 // X& X::operator=(X&)
4772 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4773 QualType RetType = Context.getLValueReferenceType(ArgType);
4774 if (HasConstCopyAssignment)
4775 ArgType = ArgType.withConst();
4776 ArgType = Context.getLValueReferenceType(ArgType);
4777
Douglas Gregorb87786f2010-07-01 17:48:08 +00004778 // C++ [except.spec]p14:
4779 // An implicitly declared special member function (Clause 12) shall have an
4780 // exception-specification. [...]
4781 ImplicitExceptionSpecification ExceptSpec(Context);
4782 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4783 BaseEnd = ClassDecl->bases_end();
4784 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004785 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004786 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004787
4788 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4789 DeclareImplicitCopyAssignment(BaseClassDecl);
4790
Douglas Gregorb87786f2010-07-01 17:48:08 +00004791 if (CXXMethodDecl *CopyAssign
4792 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4793 ExceptSpec.CalledDecl(CopyAssign);
4794 }
4795 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4796 FieldEnd = ClassDecl->field_end();
4797 Field != FieldEnd;
4798 ++Field) {
4799 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4800 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004801 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004802 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004803
4804 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4805 DeclareImplicitCopyAssignment(FieldClassDecl);
4806
Douglas Gregorb87786f2010-07-01 17:48:08 +00004807 if (CXXMethodDecl *CopyAssign
4808 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4809 ExceptSpec.CalledDecl(CopyAssign);
4810 }
4811 }
4812
Douglas Gregord3c35902010-07-01 16:36:15 +00004813 // An implicitly-declared copy assignment operator is an inline public
4814 // member of its class.
4815 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004816 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004817 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004818 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004819 Context.getFunctionType(RetType, &ArgType, 1,
4820 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004821 ExceptSpec.hasExceptionSpecification(),
4822 ExceptSpec.hasAnyExceptionSpecification(),
4823 ExceptSpec.size(),
4824 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004825 FunctionType::ExtInfo()),
4826 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004827 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004828 /*isInline=*/true);
4829 CopyAssignment->setAccess(AS_public);
4830 CopyAssignment->setImplicit();
4831 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004832
4833 // Add the parameter to the operator.
4834 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4835 ClassDecl->getLocation(),
4836 /*Id=*/0,
4837 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004838 SC_None,
4839 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004840 CopyAssignment->setParams(&FromParam, 1);
4841
Douglas Gregora376d102010-07-02 21:50:04 +00004842 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004843 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4844
Douglas Gregor23c94db2010-07-02 17:43:08 +00004845 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004846 PushOnScopeChains(CopyAssignment, S, false);
4847 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004848
4849 AddOverriddenMethods(ClassDecl, CopyAssignment);
4850 return CopyAssignment;
4851}
4852
Douglas Gregor06a9f362010-05-01 20:49:11 +00004853void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4854 CXXMethodDecl *CopyAssignOperator) {
4855 assert((CopyAssignOperator->isImplicit() &&
4856 CopyAssignOperator->isOverloadedOperator() &&
4857 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004858 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004859 "DefineImplicitCopyAssignment called for wrong function");
4860
4861 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4862
4863 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4864 CopyAssignOperator->setInvalidDecl();
4865 return;
4866 }
4867
4868 CopyAssignOperator->setUsed();
4869
4870 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004871 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004872
4873 // C++0x [class.copy]p30:
4874 // The implicitly-defined or explicitly-defaulted copy assignment operator
4875 // for a non-union class X performs memberwise copy assignment of its
4876 // subobjects. The direct base classes of X are assigned first, in the
4877 // order of their declaration in the base-specifier-list, and then the
4878 // immediate non-static data members of X are assigned, in the order in
4879 // which they were declared in the class definition.
4880
4881 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004882 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004883
4884 // The parameter for the "other" object, which we are copying from.
4885 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4886 Qualifiers OtherQuals = Other->getType().getQualifiers();
4887 QualType OtherRefType = Other->getType();
4888 if (const LValueReferenceType *OtherRef
4889 = OtherRefType->getAs<LValueReferenceType>()) {
4890 OtherRefType = OtherRef->getPointeeType();
4891 OtherQuals = OtherRefType.getQualifiers();
4892 }
4893
4894 // Our location for everything implicitly-generated.
4895 SourceLocation Loc = CopyAssignOperator->getLocation();
4896
4897 // Construct a reference to the "other" object. We'll be using this
4898 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00004899 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004900 assert(OtherRef && "Reference to parameter cannot fail!");
4901
4902 // Construct the "this" pointer. We'll be using this throughout the generated
4903 // ASTs.
4904 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4905 assert(This && "Reference to this cannot fail!");
4906
4907 // Assign base classes.
4908 bool Invalid = false;
4909 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4910 E = ClassDecl->bases_end(); Base != E; ++Base) {
4911 // Form the assignment:
4912 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4913 QualType BaseType = Base->getType().getUnqualifiedType();
4914 CXXRecordDecl *BaseClassDecl = 0;
4915 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4916 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4917 else {
4918 Invalid = true;
4919 continue;
4920 }
4921
John McCallf871d0c2010-08-07 06:22:56 +00004922 CXXCastPath BasePath;
4923 BasePath.push_back(Base);
4924
Douglas Gregor06a9f362010-05-01 20:49:11 +00004925 // Construct the "from" expression, which is an implicit cast to the
4926 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00004927 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004928 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004929 CK_UncheckedDerivedToBase,
4930 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004931
4932 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004933 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004934
4935 // Implicitly cast "this" to the appropriately-qualified base type.
4936 Expr *ToE = To.takeAs<Expr>();
4937 ImpCastExprToType(ToE,
4938 Context.getCVRQualifiedType(BaseType,
4939 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004940 CK_UncheckedDerivedToBase,
4941 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004942 To = Owned(ToE);
4943
4944 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004945 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004946 To.get(), From,
4947 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004948 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004949 Diag(CurrentLocation, diag::note_member_synthesized_at)
4950 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4951 CopyAssignOperator->setInvalidDecl();
4952 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004953 }
4954
4955 // Success! Record the copy.
4956 Statements.push_back(Copy.takeAs<Expr>());
4957 }
4958
4959 // \brief Reference to the __builtin_memcpy function.
4960 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00004961 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00004962 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004963
4964 // Assign non-static members.
4965 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4966 FieldEnd = ClassDecl->field_end();
4967 Field != FieldEnd; ++Field) {
4968 // Check for members of reference type; we can't copy those.
4969 if (Field->getType()->isReferenceType()) {
4970 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4971 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4972 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004973 Diag(CurrentLocation, diag::note_member_synthesized_at)
4974 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004975 Invalid = true;
4976 continue;
4977 }
4978
4979 // Check for members of const-qualified, non-class type.
4980 QualType BaseType = Context.getBaseElementType(Field->getType());
4981 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4982 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4983 << Context.getTagDeclType(ClassDecl) << 1 << 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 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00004992 if (FieldType->isIncompleteArrayType()) {
4993 assert(ClassDecl->hasFlexibleArrayMember() &&
4994 "Incomplete array type is not valid");
4995 continue;
4996 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004997
4998 // Build references to the field in the object we're copying from and to.
4999 CXXScopeSpec SS; // Intentionally empty
5000 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5001 LookupMemberName);
5002 MemberLookup.addDecl(*Field);
5003 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005004 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005005 Loc, /*IsArrow=*/false,
5006 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005007 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005008 Loc, /*IsArrow=*/true,
5009 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005010 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5011 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5012
5013 // If the field should be copied with __builtin_memcpy rather than via
5014 // explicit assignments, do so. This optimization only applies for arrays
5015 // of scalars and arrays of class type with trivial copy-assignment
5016 // operators.
5017 if (FieldType->isArrayType() &&
5018 (!BaseType->isRecordType() ||
5019 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5020 ->hasTrivialCopyAssignment())) {
5021 // Compute the size of the memory buffer to be copied.
5022 QualType SizeType = Context.getSizeType();
5023 llvm::APInt Size(Context.getTypeSize(SizeType),
5024 Context.getTypeSizeInChars(BaseType).getQuantity());
5025 for (const ConstantArrayType *Array
5026 = Context.getAsConstantArrayType(FieldType);
5027 Array;
5028 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5029 llvm::APInt ArraySize = Array->getSize();
5030 ArraySize.zextOrTrunc(Size.getBitWidth());
5031 Size *= ArraySize;
5032 }
5033
5034 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005035 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5036 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005037
5038 bool NeedsCollectableMemCpy =
5039 (BaseType->isRecordType() &&
5040 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5041
5042 if (NeedsCollectableMemCpy) {
5043 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005044 // Create a reference to the __builtin_objc_memmove_collectable function.
5045 LookupResult R(*this,
5046 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005047 Loc, LookupOrdinaryName);
5048 LookupName(R, TUScope, true);
5049
5050 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5051 if (!CollectableMemCpy) {
5052 // Something went horribly wrong earlier, and we will have
5053 // complained about it.
5054 Invalid = true;
5055 continue;
5056 }
5057
5058 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5059 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005060 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005061 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5062 }
5063 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005064 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005065 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005066 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5067 LookupOrdinaryName);
5068 LookupName(R, TUScope, true);
5069
5070 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5071 if (!BuiltinMemCpy) {
5072 // Something went horribly wrong earlier, and we will have complained
5073 // about it.
5074 Invalid = true;
5075 continue;
5076 }
5077
5078 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5079 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005080 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005081 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5082 }
5083
John McCallca0408f2010-08-23 06:44:23 +00005084 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005085 CallArgs.push_back(To.takeAs<Expr>());
5086 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005087 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005088 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005089 if (NeedsCollectableMemCpy)
5090 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005091 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005092 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005093 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005094 else
5095 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005096 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005097 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005098 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005099
Douglas Gregor06a9f362010-05-01 20:49:11 +00005100 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5101 Statements.push_back(Call.takeAs<Expr>());
5102 continue;
5103 }
5104
5105 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005106 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005107 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005108 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005109 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005110 Diag(CurrentLocation, diag::note_member_synthesized_at)
5111 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5112 CopyAssignOperator->setInvalidDecl();
5113 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005114 }
5115
5116 // Success! Record the copy.
5117 Statements.push_back(Copy.takeAs<Stmt>());
5118 }
5119
5120 if (!Invalid) {
5121 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005122 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005123
John McCall60d7b3a2010-08-24 06:29:42 +00005124 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005125 if (Return.isInvalid())
5126 Invalid = true;
5127 else {
5128 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005129
5130 if (Trap.hasErrorOccurred()) {
5131 Diag(CurrentLocation, diag::note_member_synthesized_at)
5132 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5133 Invalid = true;
5134 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005135 }
5136 }
5137
5138 if (Invalid) {
5139 CopyAssignOperator->setInvalidDecl();
5140 return;
5141 }
5142
John McCall60d7b3a2010-08-24 06:29:42 +00005143 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005144 /*isStmtExpr=*/false);
5145 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5146 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005147}
5148
Douglas Gregor23c94db2010-07-02 17:43:08 +00005149CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5150 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005151 // C++ [class.copy]p4:
5152 // If the class definition does not explicitly declare a copy
5153 // constructor, one is declared implicitly.
5154
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005155 // C++ [class.copy]p5:
5156 // The implicitly-declared copy constructor for a class X will
5157 // have the form
5158 //
5159 // X::X(const X&)
5160 //
5161 // if
5162 bool HasConstCopyConstructor = true;
5163
5164 // -- each direct or virtual base class B of X has a copy
5165 // constructor whose first parameter is of type const B& or
5166 // const volatile B&, and
5167 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5168 BaseEnd = ClassDecl->bases_end();
5169 HasConstCopyConstructor && Base != BaseEnd;
5170 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005171 // Virtual bases are handled below.
5172 if (Base->isVirtual())
5173 continue;
5174
Douglas Gregor22584312010-07-02 23:41:54 +00005175 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005176 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005177 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5178 DeclareImplicitCopyConstructor(BaseClassDecl);
5179
Douglas Gregor598a8542010-07-01 18:27:03 +00005180 HasConstCopyConstructor
5181 = BaseClassDecl->hasConstCopyConstructor(Context);
5182 }
5183
5184 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5185 BaseEnd = ClassDecl->vbases_end();
5186 HasConstCopyConstructor && Base != BaseEnd;
5187 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005188 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005189 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005190 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5191 DeclareImplicitCopyConstructor(BaseClassDecl);
5192
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005193 HasConstCopyConstructor
5194 = BaseClassDecl->hasConstCopyConstructor(Context);
5195 }
5196
5197 // -- for all the nonstatic data members of X that are of a
5198 // class type M (or array thereof), each such class type
5199 // has a copy constructor whose first parameter is of type
5200 // const M& or const volatile M&.
5201 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5202 FieldEnd = ClassDecl->field_end();
5203 HasConstCopyConstructor && Field != FieldEnd;
5204 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005205 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005206 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005207 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005208 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005209 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5210 DeclareImplicitCopyConstructor(FieldClassDecl);
5211
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005212 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005213 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005214 }
5215 }
5216
5217 // Otherwise, the implicitly declared copy constructor will have
5218 // the form
5219 //
5220 // X::X(X&)
5221 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5222 QualType ArgType = ClassType;
5223 if (HasConstCopyConstructor)
5224 ArgType = ArgType.withConst();
5225 ArgType = Context.getLValueReferenceType(ArgType);
5226
Douglas Gregor0d405db2010-07-01 20:59:04 +00005227 // C++ [except.spec]p14:
5228 // An implicitly declared special member function (Clause 12) shall have an
5229 // exception-specification. [...]
5230 ImplicitExceptionSpecification ExceptSpec(Context);
5231 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5232 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5233 BaseEnd = ClassDecl->bases_end();
5234 Base != BaseEnd;
5235 ++Base) {
5236 // Virtual bases are handled below.
5237 if (Base->isVirtual())
5238 continue;
5239
Douglas Gregor22584312010-07-02 23:41:54 +00005240 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005241 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005242 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5243 DeclareImplicitCopyConstructor(BaseClassDecl);
5244
Douglas Gregor0d405db2010-07-01 20:59:04 +00005245 if (CXXConstructorDecl *CopyConstructor
5246 = BaseClassDecl->getCopyConstructor(Context, Quals))
5247 ExceptSpec.CalledDecl(CopyConstructor);
5248 }
5249 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5250 BaseEnd = ClassDecl->vbases_end();
5251 Base != BaseEnd;
5252 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005253 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005254 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005255 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5256 DeclareImplicitCopyConstructor(BaseClassDecl);
5257
Douglas Gregor0d405db2010-07-01 20:59:04 +00005258 if (CXXConstructorDecl *CopyConstructor
5259 = BaseClassDecl->getCopyConstructor(Context, Quals))
5260 ExceptSpec.CalledDecl(CopyConstructor);
5261 }
5262 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5263 FieldEnd = ClassDecl->field_end();
5264 Field != FieldEnd;
5265 ++Field) {
5266 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5267 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005268 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005269 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005270 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5271 DeclareImplicitCopyConstructor(FieldClassDecl);
5272
Douglas Gregor0d405db2010-07-01 20:59:04 +00005273 if (CXXConstructorDecl *CopyConstructor
5274 = FieldClassDecl->getCopyConstructor(Context, Quals))
5275 ExceptSpec.CalledDecl(CopyConstructor);
5276 }
5277 }
5278
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005279 // An implicitly-declared copy constructor is an inline public
5280 // member of its class.
5281 DeclarationName Name
5282 = Context.DeclarationNames.getCXXConstructorName(
5283 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005284 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005285 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005286 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005287 Context.getFunctionType(Context.VoidTy,
5288 &ArgType, 1,
5289 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005290 ExceptSpec.hasExceptionSpecification(),
5291 ExceptSpec.hasAnyExceptionSpecification(),
5292 ExceptSpec.size(),
5293 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005294 FunctionType::ExtInfo()),
5295 /*TInfo=*/0,
5296 /*isExplicit=*/false,
5297 /*isInline=*/true,
5298 /*isImplicitlyDeclared=*/true);
5299 CopyConstructor->setAccess(AS_public);
5300 CopyConstructor->setImplicit();
5301 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5302
Douglas Gregor22584312010-07-02 23:41:54 +00005303 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005304 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5305
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005306 // Add the parameter to the constructor.
5307 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5308 ClassDecl->getLocation(),
5309 /*IdentifierInfo=*/0,
5310 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005311 SC_None,
5312 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005313 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005314 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005315 PushOnScopeChains(CopyConstructor, S, false);
5316 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005317
5318 return CopyConstructor;
5319}
5320
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005321void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5322 CXXConstructorDecl *CopyConstructor,
5323 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005324 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005325 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005326 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005327 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005328
Anders Carlsson63010a72010-04-23 16:24:12 +00005329 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005330 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005331
Douglas Gregor39957dc2010-05-01 15:04:51 +00005332 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005333 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005334
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005335 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5336 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005337 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005338 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005339 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005340 } else {
5341 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5342 CopyConstructor->getLocation(),
5343 MultiStmtArg(*this, 0, 0),
5344 /*isStmtExpr=*/false)
5345 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005346 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005347
5348 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005349}
5350
John McCall60d7b3a2010-08-24 06:29:42 +00005351ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005352Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005353 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005354 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005355 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005356 unsigned ConstructKind,
5357 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005358 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005359
Douglas Gregor2f599792010-04-02 18:24:57 +00005360 // C++0x [class.copy]p34:
5361 // When certain criteria are met, an implementation is allowed to
5362 // omit the copy/move construction of a class object, even if the
5363 // copy/move constructor and/or destructor for the object have
5364 // side effects. [...]
5365 // - when a temporary class object that has not been bound to a
5366 // reference (12.2) would be copied/moved to a class object
5367 // with the same cv-unqualified type, the copy/move operation
5368 // can be omitted by constructing the temporary object
5369 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005370 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5371 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005372 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005373 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005374 }
Mike Stump1eb44332009-09-09 15:08:12 +00005375
5376 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005377 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005378 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005379}
5380
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005381/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5382/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005383ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005384Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5385 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005386 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005387 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005388 unsigned ConstructKind,
5389 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005390 unsigned NumExprs = ExprArgs.size();
5391 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005392
Douglas Gregor7edfb692009-11-23 12:27:39 +00005393 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005394 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005395 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005396 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005397 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5398 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005399}
5400
Mike Stump1eb44332009-09-09 15:08:12 +00005401bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005402 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005403 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005404 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005405 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005406 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005407 move(Exprs), false, CXXConstructExpr::CK_Complete,
5408 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005409 if (TempResult.isInvalid())
5410 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005412 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005413 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005414 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005415 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005416 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005417
Anders Carlssonfe2de492009-08-25 05:18:00 +00005418 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005419}
5420
John McCall68c6c9a2010-02-02 09:10:11 +00005421void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5422 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005423 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005424 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005425 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005426 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005427 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005428 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005429 << VD->getDeclName()
5430 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005431
John McCallae792222010-09-18 05:25:11 +00005432 // TODO: this should be re-enabled for static locals by !CXAAtExit
5433 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005434 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005435 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005436}
5437
Mike Stump1eb44332009-09-09 15:08:12 +00005438/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005439/// ActOnDeclarator, when a C++ direct initializer is present.
5440/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005441void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005442 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005443 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005444 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005445 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005446
5447 // If there is no declaration, there was an error parsing it. Just ignore
5448 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005449 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005450 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005451
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005452 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5453 if (!VDecl) {
5454 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5455 RealDecl->setInvalidDecl();
5456 return;
5457 }
5458
Douglas Gregor83ddad32009-08-26 21:14:46 +00005459 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005460 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005461 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5462 //
5463 // Clients that want to distinguish between the two forms, can check for
5464 // direct initializer using VarDecl::hasCXXDirectInitializer().
5465 // A major benefit is that clients that don't particularly care about which
5466 // exactly form was it (like the CodeGen) can handle both cases without
5467 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005468
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005469 // C++ 8.5p11:
5470 // The form of initialization (using parentheses or '=') is generally
5471 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005472 // class type.
5473
Douglas Gregor4dffad62010-02-11 22:55:30 +00005474 if (!VDecl->getType()->isDependentType() &&
5475 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005476 diag::err_typecheck_decl_incomplete_type)) {
5477 VDecl->setInvalidDecl();
5478 return;
5479 }
5480
Douglas Gregor90f93822009-12-22 22:17:25 +00005481 // The variable can not have an abstract class type.
5482 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5483 diag::err_abstract_type_in_decl,
5484 AbstractVariableType))
5485 VDecl->setInvalidDecl();
5486
Sebastian Redl31310a22010-02-01 20:16:42 +00005487 const VarDecl *Def;
5488 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005489 Diag(VDecl->getLocation(), diag::err_redefinition)
5490 << VDecl->getDeclName();
5491 Diag(Def->getLocation(), diag::note_previous_definition);
5492 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005493 return;
5494 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005495
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005496 // C++ [class.static.data]p4
5497 // If a static data member is of const integral or const
5498 // enumeration type, its declaration in the class definition can
5499 // specify a constant-initializer which shall be an integral
5500 // constant expression (5.19). In that case, the member can appear
5501 // in integral constant expressions. The member shall still be
5502 // defined in a namespace scope if it is used in the program and the
5503 // namespace scope definition shall not contain an initializer.
5504 //
5505 // We already performed a redefinition check above, but for static
5506 // data members we also need to check whether there was an in-class
5507 // declaration with an initializer.
5508 const VarDecl* PrevInit = 0;
5509 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5510 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5511 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5512 return;
5513 }
5514
Douglas Gregor4dffad62010-02-11 22:55:30 +00005515 // If either the declaration has a dependent type or if any of the
5516 // expressions is type-dependent, we represent the initialization
5517 // via a ParenListExpr for later use during template instantiation.
5518 if (VDecl->getType()->isDependentType() ||
5519 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5520 // Let clients know that initialization was done with a direct initializer.
5521 VDecl->setCXXDirectInitializer(true);
5522
5523 // Store the initialization expressions as a ParenListExpr.
5524 unsigned NumExprs = Exprs.size();
5525 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5526 (Expr **)Exprs.release(),
5527 NumExprs, RParenLoc));
5528 return;
5529 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005530
5531 // Capture the variable that is being initialized and the style of
5532 // initialization.
5533 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5534
5535 // FIXME: Poor source location information.
5536 InitializationKind Kind
5537 = InitializationKind::CreateDirect(VDecl->getLocation(),
5538 LParenLoc, RParenLoc);
5539
5540 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005541 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005542 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005543 if (Result.isInvalid()) {
5544 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005545 return;
5546 }
John McCallb4eb64d2010-10-08 02:01:28 +00005547
5548 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005549
John McCall4765fa02010-12-06 08:20:24 +00005550 Result = MaybeCreateExprWithCleanups(Result.get());
Douglas Gregor838db382010-02-11 01:19:42 +00005551 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005552 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005553
John McCall4204f072010-08-02 21:13:48 +00005554 if (!VDecl->isInvalidDecl() &&
5555 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005556 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005557 !VDecl->getInit()->isConstantInitializer(Context,
5558 VDecl->getType()->isReferenceType()))
5559 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5560 << VDecl->getInit()->getSourceRange();
5561
John McCall68c6c9a2010-02-02 09:10:11 +00005562 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5563 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005564}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005565
Douglas Gregor39da0b82009-09-09 23:08:42 +00005566/// \brief Given a constructor and the set of arguments provided for the
5567/// constructor, convert the arguments and add any required default arguments
5568/// to form a proper call to this constructor.
5569///
5570/// \returns true if an error occurred, false otherwise.
5571bool
5572Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5573 MultiExprArg ArgsPtr,
5574 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005575 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005576 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5577 unsigned NumArgs = ArgsPtr.size();
5578 Expr **Args = (Expr **)ArgsPtr.get();
5579
5580 const FunctionProtoType *Proto
5581 = Constructor->getType()->getAs<FunctionProtoType>();
5582 assert(Proto && "Constructor without a prototype?");
5583 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005584
5585 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005586 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005587 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005588 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005589 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005590
5591 VariadicCallType CallType =
5592 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5593 llvm::SmallVector<Expr *, 8> AllArgs;
5594 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5595 Proto, 0, Args, NumArgs, AllArgs,
5596 CallType);
5597 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5598 ConvertedArgs.push_back(AllArgs[i]);
5599 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005600}
5601
Anders Carlsson20d45d22009-12-12 00:32:00 +00005602static inline bool
5603CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5604 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005605 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005606 if (isa<NamespaceDecl>(DC)) {
5607 return SemaRef.Diag(FnDecl->getLocation(),
5608 diag::err_operator_new_delete_declared_in_namespace)
5609 << FnDecl->getDeclName();
5610 }
5611
5612 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005613 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005614 return SemaRef.Diag(FnDecl->getLocation(),
5615 diag::err_operator_new_delete_declared_static)
5616 << FnDecl->getDeclName();
5617 }
5618
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005619 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005620}
5621
Anders Carlsson156c78e2009-12-13 17:53:43 +00005622static inline bool
5623CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5624 CanQualType ExpectedResultType,
5625 CanQualType ExpectedFirstParamType,
5626 unsigned DependentParamTypeDiag,
5627 unsigned InvalidParamTypeDiag) {
5628 QualType ResultType =
5629 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5630
5631 // Check that the result type is not dependent.
5632 if (ResultType->isDependentType())
5633 return SemaRef.Diag(FnDecl->getLocation(),
5634 diag::err_operator_new_delete_dependent_result_type)
5635 << FnDecl->getDeclName() << ExpectedResultType;
5636
5637 // Check that the result type is what we expect.
5638 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5639 return SemaRef.Diag(FnDecl->getLocation(),
5640 diag::err_operator_new_delete_invalid_result_type)
5641 << FnDecl->getDeclName() << ExpectedResultType;
5642
5643 // A function template must have at least 2 parameters.
5644 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5645 return SemaRef.Diag(FnDecl->getLocation(),
5646 diag::err_operator_new_delete_template_too_few_parameters)
5647 << FnDecl->getDeclName();
5648
5649 // The function decl must have at least 1 parameter.
5650 if (FnDecl->getNumParams() == 0)
5651 return SemaRef.Diag(FnDecl->getLocation(),
5652 diag::err_operator_new_delete_too_few_parameters)
5653 << FnDecl->getDeclName();
5654
5655 // Check the the first parameter type is not dependent.
5656 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5657 if (FirstParamType->isDependentType())
5658 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5659 << FnDecl->getDeclName() << ExpectedFirstParamType;
5660
5661 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005662 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005663 ExpectedFirstParamType)
5664 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5665 << FnDecl->getDeclName() << ExpectedFirstParamType;
5666
5667 return false;
5668}
5669
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005670static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005671CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005672 // C++ [basic.stc.dynamic.allocation]p1:
5673 // A program is ill-formed if an allocation function is declared in a
5674 // namespace scope other than global scope or declared static in global
5675 // scope.
5676 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5677 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005678
5679 CanQualType SizeTy =
5680 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5681
5682 // C++ [basic.stc.dynamic.allocation]p1:
5683 // The return type shall be void*. The first parameter shall have type
5684 // std::size_t.
5685 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5686 SizeTy,
5687 diag::err_operator_new_dependent_param_type,
5688 diag::err_operator_new_param_type))
5689 return true;
5690
5691 // C++ [basic.stc.dynamic.allocation]p1:
5692 // The first parameter shall not have an associated default argument.
5693 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005694 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005695 diag::err_operator_new_default_arg)
5696 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5697
5698 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005699}
5700
5701static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005702CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5703 // C++ [basic.stc.dynamic.deallocation]p1:
5704 // A program is ill-formed if deallocation functions are declared in a
5705 // namespace scope other than global scope or declared static in global
5706 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005707 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5708 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005709
5710 // C++ [basic.stc.dynamic.deallocation]p2:
5711 // Each deallocation function shall return void and its first parameter
5712 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005713 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5714 SemaRef.Context.VoidPtrTy,
5715 diag::err_operator_delete_dependent_param_type,
5716 diag::err_operator_delete_param_type))
5717 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005718
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005719 return false;
5720}
5721
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005722/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5723/// of this overloaded operator is well-formed. If so, returns false;
5724/// otherwise, emits appropriate diagnostics and returns true.
5725bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005726 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005727 "Expected an overloaded operator declaration");
5728
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005729 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5730
Mike Stump1eb44332009-09-09 15:08:12 +00005731 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005732 // The allocation and deallocation functions, operator new,
5733 // operator new[], operator delete and operator delete[], are
5734 // described completely in 3.7.3. The attributes and restrictions
5735 // found in the rest of this subclause do not apply to them unless
5736 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005737 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005738 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005739
Anders Carlssona3ccda52009-12-12 00:26:23 +00005740 if (Op == OO_New || Op == OO_Array_New)
5741 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005742
5743 // C++ [over.oper]p6:
5744 // An operator function shall either be a non-static member
5745 // function or be a non-member function and have at least one
5746 // parameter whose type is a class, a reference to a class, an
5747 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005748 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5749 if (MethodDecl->isStatic())
5750 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005751 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005752 } else {
5753 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005754 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5755 ParamEnd = FnDecl->param_end();
5756 Param != ParamEnd; ++Param) {
5757 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005758 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5759 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005760 ClassOrEnumParam = true;
5761 break;
5762 }
5763 }
5764
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005765 if (!ClassOrEnumParam)
5766 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005767 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005768 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005769 }
5770
5771 // C++ [over.oper]p8:
5772 // An operator function cannot have default arguments (8.3.6),
5773 // except where explicitly stated below.
5774 //
Mike Stump1eb44332009-09-09 15:08:12 +00005775 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005776 // (C++ [over.call]p1).
5777 if (Op != OO_Call) {
5778 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5779 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005780 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005781 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005782 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005783 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005784 }
5785 }
5786
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005787 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5788 { false, false, false }
5789#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5790 , { Unary, Binary, MemberOnly }
5791#include "clang/Basic/OperatorKinds.def"
5792 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005793
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005794 bool CanBeUnaryOperator = OperatorUses[Op][0];
5795 bool CanBeBinaryOperator = OperatorUses[Op][1];
5796 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005797
5798 // C++ [over.oper]p8:
5799 // [...] Operator functions cannot have more or fewer parameters
5800 // than the number required for the corresponding operator, as
5801 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005802 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005803 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005804 if (Op != OO_Call &&
5805 ((NumParams == 1 && !CanBeUnaryOperator) ||
5806 (NumParams == 2 && !CanBeBinaryOperator) ||
5807 (NumParams < 1) || (NumParams > 2))) {
5808 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005809 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005810 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005811 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005812 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005813 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005814 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005815 assert(CanBeBinaryOperator &&
5816 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005817 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005818 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005819
Chris Lattner416e46f2008-11-21 07:57:12 +00005820 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005821 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005822 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005823
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005824 // Overloaded operators other than operator() cannot be variadic.
5825 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005826 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005827 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005828 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005829 }
5830
5831 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005832 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5833 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005834 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005835 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005836 }
5837
5838 // C++ [over.inc]p1:
5839 // The user-defined function called operator++ implements the
5840 // prefix and postfix ++ operator. If this function is a member
5841 // function with no parameters, or a non-member function with one
5842 // parameter of class or enumeration type, it defines the prefix
5843 // increment operator ++ for objects of that type. If the function
5844 // is a member function with one parameter (which shall be of type
5845 // int) or a non-member function with two parameters (the second
5846 // of which shall be of type int), it defines the postfix
5847 // increment operator ++ for objects of that type.
5848 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5849 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5850 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005851 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005852 ParamIsInt = BT->getKind() == BuiltinType::Int;
5853
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005854 if (!ParamIsInt)
5855 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005856 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005857 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005858 }
5859
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005860 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005861}
Chris Lattner5a003a42008-12-17 07:09:26 +00005862
Sean Hunta6c058d2010-01-13 09:01:02 +00005863/// CheckLiteralOperatorDeclaration - Check whether the declaration
5864/// of this literal operator function is well-formed. If so, returns
5865/// false; otherwise, emits appropriate diagnostics and returns true.
5866bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5867 DeclContext *DC = FnDecl->getDeclContext();
5868 Decl::Kind Kind = DC->getDeclKind();
5869 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5870 Kind != Decl::LinkageSpec) {
5871 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5872 << FnDecl->getDeclName();
5873 return true;
5874 }
5875
5876 bool Valid = false;
5877
Sean Hunt216c2782010-04-07 23:11:06 +00005878 // template <char...> type operator "" name() is the only valid template
5879 // signature, and the only valid signature with no parameters.
5880 if (FnDecl->param_size() == 0) {
5881 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5882 // Must have only one template parameter
5883 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5884 if (Params->size() == 1) {
5885 NonTypeTemplateParmDecl *PmDecl =
5886 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005887
Sean Hunt216c2782010-04-07 23:11:06 +00005888 // The template parameter must be a char parameter pack.
5889 // FIXME: This test will always fail because non-type parameter packs
5890 // have not been implemented.
5891 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5892 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5893 Valid = true;
5894 }
5895 }
5896 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005897 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005898 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5899
Sean Hunta6c058d2010-01-13 09:01:02 +00005900 QualType T = (*Param)->getType();
5901
Sean Hunt30019c02010-04-07 22:57:35 +00005902 // unsigned long long int, long double, and any character type are allowed
5903 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005904 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5905 Context.hasSameType(T, Context.LongDoubleTy) ||
5906 Context.hasSameType(T, Context.CharTy) ||
5907 Context.hasSameType(T, Context.WCharTy) ||
5908 Context.hasSameType(T, Context.Char16Ty) ||
5909 Context.hasSameType(T, Context.Char32Ty)) {
5910 if (++Param == FnDecl->param_end())
5911 Valid = true;
5912 goto FinishedParams;
5913 }
5914
Sean Hunt30019c02010-04-07 22:57:35 +00005915 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005916 const PointerType *PT = T->getAs<PointerType>();
5917 if (!PT)
5918 goto FinishedParams;
5919 T = PT->getPointeeType();
5920 if (!T.isConstQualified())
5921 goto FinishedParams;
5922 T = T.getUnqualifiedType();
5923
5924 // Move on to the second parameter;
5925 ++Param;
5926
5927 // If there is no second parameter, the first must be a const char *
5928 if (Param == FnDecl->param_end()) {
5929 if (Context.hasSameType(T, Context.CharTy))
5930 Valid = true;
5931 goto FinishedParams;
5932 }
5933
5934 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5935 // are allowed as the first parameter to a two-parameter function
5936 if (!(Context.hasSameType(T, Context.CharTy) ||
5937 Context.hasSameType(T, Context.WCharTy) ||
5938 Context.hasSameType(T, Context.Char16Ty) ||
5939 Context.hasSameType(T, Context.Char32Ty)))
5940 goto FinishedParams;
5941
5942 // The second and final parameter must be an std::size_t
5943 T = (*Param)->getType().getUnqualifiedType();
5944 if (Context.hasSameType(T, Context.getSizeType()) &&
5945 ++Param == FnDecl->param_end())
5946 Valid = true;
5947 }
5948
5949 // FIXME: This diagnostic is absolutely terrible.
5950FinishedParams:
5951 if (!Valid) {
5952 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5953 << FnDecl->getDeclName();
5954 return true;
5955 }
5956
5957 return false;
5958}
5959
Douglas Gregor074149e2009-01-05 19:45:36 +00005960/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5961/// linkage specification, including the language and (if present)
5962/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5963/// the location of the language string literal, which is provided
5964/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5965/// the '{' brace. Otherwise, this linkage specification does not
5966/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00005967Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5968 SourceLocation LangLoc,
5969 llvm::StringRef Lang,
5970 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005971 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005972 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005973 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005974 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005975 Language = LinkageSpecDecl::lang_cxx;
5976 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005977 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00005978 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005979 }
Mike Stump1eb44332009-09-09 15:08:12 +00005980
Chris Lattnercc98eac2008-12-17 07:13:27 +00005981 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005982
Douglas Gregor074149e2009-01-05 19:45:36 +00005983 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005984 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005985 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005986 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005987 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00005988 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00005989}
5990
Abramo Bagnara35f9a192010-07-30 16:47:02 +00005991/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00005992/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5993/// valid, it's the position of the closing '}' brace in a linkage
5994/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00005995Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
5996 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005997 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005998 if (LinkageSpec)
5999 PopDeclContext();
6000 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006001}
6002
Douglas Gregord308e622009-05-18 20:51:54 +00006003/// \brief Perform semantic analysis for the variable declaration that
6004/// occurs within a C++ catch clause, returning the newly-created
6005/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006006VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006007 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006008 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006009 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006010 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006011 QualType ExDeclType = TInfo->getType();
6012
Sebastian Redl4b07b292008-12-22 19:15:10 +00006013 // Arrays and functions decay.
6014 if (ExDeclType->isArrayType())
6015 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6016 else if (ExDeclType->isFunctionType())
6017 ExDeclType = Context.getPointerType(ExDeclType);
6018
6019 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6020 // The exception-declaration shall not denote a pointer or reference to an
6021 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006022 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006023 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006024 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006025 Invalid = true;
6026 }
Douglas Gregord308e622009-05-18 20:51:54 +00006027
Douglas Gregora2762912010-03-08 01:47:36 +00006028 // GCC allows catching pointers and references to incomplete types
6029 // as an extension; so do we, but we warn by default.
6030
Sebastian Redl4b07b292008-12-22 19:15:10 +00006031 QualType BaseType = ExDeclType;
6032 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006033 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006034 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006035 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006036 BaseType = Ptr->getPointeeType();
6037 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006038 DK = diag::ext_catch_incomplete_ptr;
6039 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006040 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006041 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006042 BaseType = Ref->getPointeeType();
6043 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006044 DK = diag::ext_catch_incomplete_ref;
6045 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006046 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006047 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006048 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6049 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006050 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006051
Mike Stump1eb44332009-09-09 15:08:12 +00006052 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006053 RequireNonAbstractType(Loc, ExDeclType,
6054 diag::err_abstract_type_in_decl,
6055 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006056 Invalid = true;
6057
John McCall5a180392010-07-24 00:37:23 +00006058 // Only the non-fragile NeXT runtime currently supports C++ catches
6059 // of ObjC types, and no runtime supports catching ObjC types by value.
6060 if (!Invalid && getLangOptions().ObjC1) {
6061 QualType T = ExDeclType;
6062 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6063 T = RT->getPointeeType();
6064
6065 if (T->isObjCObjectType()) {
6066 Diag(Loc, diag::err_objc_object_catch);
6067 Invalid = true;
6068 } else if (T->isObjCObjectPointerType()) {
6069 if (!getLangOptions().NeXTRuntime) {
6070 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6071 Invalid = true;
6072 } else if (!getLangOptions().ObjCNonFragileABI) {
6073 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6074 Invalid = true;
6075 }
6076 }
6077 }
6078
Mike Stump1eb44332009-09-09 15:08:12 +00006079 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006080 Name, ExDeclType, TInfo, SC_None,
6081 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006082 ExDecl->setExceptionVariable(true);
6083
Douglas Gregor6d182892010-03-05 23:38:39 +00006084 if (!Invalid) {
6085 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6086 // C++ [except.handle]p16:
6087 // The object declared in an exception-declaration or, if the
6088 // exception-declaration does not specify a name, a temporary (12.2) is
6089 // copy-initialized (8.5) from the exception object. [...]
6090 // The object is destroyed when the handler exits, after the destruction
6091 // of any automatic objects initialized within the handler.
6092 //
6093 // We just pretend to initialize the object with itself, then make sure
6094 // it can be destroyed later.
6095 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6096 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006097 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006098 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6099 SourceLocation());
6100 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006101 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006102 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006103 if (Result.isInvalid())
6104 Invalid = true;
6105 else
6106 FinalizeVarWithDestructor(ExDecl, RecordTy);
6107 }
6108 }
6109
Douglas Gregord308e622009-05-18 20:51:54 +00006110 if (Invalid)
6111 ExDecl->setInvalidDecl();
6112
6113 return ExDecl;
6114}
6115
6116/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6117/// handler.
John McCalld226f652010-08-21 09:40:31 +00006118Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6120 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006121
6122 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006123 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006124 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006125 LookupOrdinaryName,
6126 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006127 // The scope should be freshly made just for us. There is just no way
6128 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006129 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006130 if (PrevDecl->isTemplateParameter()) {
6131 // Maybe we will complain about the shadowed template parameter.
6132 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006133 }
6134 }
6135
Chris Lattnereaaebc72009-04-25 08:06:05 +00006136 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006137 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6138 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006139 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006140 }
6141
Douglas Gregor83cb9422010-09-09 17:09:21 +00006142 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006143 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006144 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006145
Chris Lattnereaaebc72009-04-25 08:06:05 +00006146 if (Invalid)
6147 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006148
Sebastian Redl4b07b292008-12-22 19:15:10 +00006149 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006150 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006151 PushOnScopeChains(ExDecl, S);
6152 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006153 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006154
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006155 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006156 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006157}
Anders Carlssonfb311762009-03-14 00:25:26 +00006158
John McCalld226f652010-08-21 09:40:31 +00006159Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006160 Expr *AssertExpr,
6161 Expr *AssertMessageExpr_) {
6162 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006163
Anders Carlssonc3082412009-03-14 00:33:21 +00006164 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6165 llvm::APSInt Value(32);
6166 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6167 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6168 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006169 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006170 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006171
Anders Carlssonc3082412009-03-14 00:33:21 +00006172 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006173 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006174 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006175 }
6176 }
Mike Stump1eb44332009-09-09 15:08:12 +00006177
Mike Stump1eb44332009-09-09 15:08:12 +00006178 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006179 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006180
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006181 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006182 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006183}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006184
Douglas Gregor1d869352010-04-07 16:53:43 +00006185/// \brief Perform semantic analysis of the given friend type declaration.
6186///
6187/// \returns A friend declaration that.
6188FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6189 TypeSourceInfo *TSInfo) {
6190 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6191
6192 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006193 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006194
Douglas Gregor06245bf2010-04-07 17:57:12 +00006195 if (!getLangOptions().CPlusPlus0x) {
6196 // C++03 [class.friend]p2:
6197 // An elaborated-type-specifier shall be used in a friend declaration
6198 // for a class.*
6199 //
6200 // * The class-key of the elaborated-type-specifier is required.
6201 if (!ActiveTemplateInstantiations.empty()) {
6202 // Do not complain about the form of friend template types during
6203 // template instantiation; we will already have complained when the
6204 // template was declared.
6205 } else if (!T->isElaboratedTypeSpecifier()) {
6206 // If we evaluated the type to a record type, suggest putting
6207 // a tag in front.
6208 if (const RecordType *RT = T->getAs<RecordType>()) {
6209 RecordDecl *RD = RT->getDecl();
6210
6211 std::string InsertionText = std::string(" ") + RD->getKindName();
6212
6213 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6214 << (unsigned) RD->getTagKind()
6215 << T
6216 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6217 InsertionText);
6218 } else {
6219 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6220 << T
6221 << SourceRange(FriendLoc, TypeRange.getEnd());
6222 }
6223 } else if (T->getAs<EnumType>()) {
6224 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006225 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006226 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006227 }
6228 }
6229
Douglas Gregor06245bf2010-04-07 17:57:12 +00006230 // C++0x [class.friend]p3:
6231 // If the type specifier in a friend declaration designates a (possibly
6232 // cv-qualified) class type, that class is declared as a friend; otherwise,
6233 // the friend declaration is ignored.
6234
6235 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6236 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006237
6238 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6239}
6240
John McCall9a34edb2010-10-19 01:40:49 +00006241/// Handle a friend tag declaration where the scope specifier was
6242/// templated.
6243Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6244 unsigned TagSpec, SourceLocation TagLoc,
6245 CXXScopeSpec &SS,
6246 IdentifierInfo *Name, SourceLocation NameLoc,
6247 AttributeList *Attr,
6248 MultiTemplateParamsArg TempParamLists) {
6249 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6250
6251 bool isExplicitSpecialization = false;
6252 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6253 bool Invalid = false;
6254
6255 if (TemplateParameterList *TemplateParams
6256 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6257 TempParamLists.get(),
6258 TempParamLists.size(),
6259 /*friend*/ true,
6260 isExplicitSpecialization,
6261 Invalid)) {
6262 --NumMatchedTemplateParamLists;
6263
6264 if (TemplateParams->size() > 0) {
6265 // This is a declaration of a class template.
6266 if (Invalid)
6267 return 0;
6268
6269 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6270 SS, Name, NameLoc, Attr,
6271 TemplateParams, AS_public).take();
6272 } else {
6273 // The "template<>" header is extraneous.
6274 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6275 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6276 isExplicitSpecialization = true;
6277 }
6278 }
6279
6280 if (Invalid) return 0;
6281
6282 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6283
6284 bool isAllExplicitSpecializations = true;
6285 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6286 if (TempParamLists.get()[I]->size()) {
6287 isAllExplicitSpecializations = false;
6288 break;
6289 }
6290 }
6291
6292 // FIXME: don't ignore attributes.
6293
6294 // If it's explicit specializations all the way down, just forget
6295 // about the template header and build an appropriate non-templated
6296 // friend. TODO: for source fidelity, remember the headers.
6297 if (isAllExplicitSpecializations) {
6298 ElaboratedTypeKeyword Keyword
6299 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6300 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6301 TagLoc, SS.getRange(), NameLoc);
6302 if (T.isNull())
6303 return 0;
6304
6305 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6306 if (isa<DependentNameType>(T)) {
6307 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6308 TL.setKeywordLoc(TagLoc);
6309 TL.setQualifierRange(SS.getRange());
6310 TL.setNameLoc(NameLoc);
6311 } else {
6312 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6313 TL.setKeywordLoc(TagLoc);
6314 TL.setQualifierRange(SS.getRange());
6315 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6316 }
6317
6318 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6319 TSI, FriendLoc);
6320 Friend->setAccess(AS_public);
6321 CurContext->addDecl(Friend);
6322 return Friend;
6323 }
6324
6325 // Handle the case of a templated-scope friend class. e.g.
6326 // template <class T> class A<T>::B;
6327 // FIXME: we don't support these right now.
6328 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6329 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6330 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6331 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6332 TL.setKeywordLoc(TagLoc);
6333 TL.setQualifierRange(SS.getRange());
6334 TL.setNameLoc(NameLoc);
6335
6336 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6337 TSI, FriendLoc);
6338 Friend->setAccess(AS_public);
6339 Friend->setUnsupportedFriend(true);
6340 CurContext->addDecl(Friend);
6341 return Friend;
6342}
6343
6344
John McCalldd4a3b02009-09-16 22:47:08 +00006345/// Handle a friend type declaration. This works in tandem with
6346/// ActOnTag.
6347///
6348/// Notes on friend class templates:
6349///
6350/// We generally treat friend class declarations as if they were
6351/// declaring a class. So, for example, the elaborated type specifier
6352/// in a friend declaration is required to obey the restrictions of a
6353/// class-head (i.e. no typedefs in the scope chain), template
6354/// parameters are required to match up with simple template-ids, &c.
6355/// However, unlike when declaring a template specialization, it's
6356/// okay to refer to a template specialization without an empty
6357/// template parameter declaration, e.g.
6358/// friend class A<T>::B<unsigned>;
6359/// We permit this as a special case; if there are any template
6360/// parameters present at all, require proper matching, i.e.
6361/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006362Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006363 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006364 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006365
6366 assert(DS.isFriendSpecified());
6367 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6368
John McCalldd4a3b02009-09-16 22:47:08 +00006369 // Try to convert the decl specifier to a type. This works for
6370 // friend templates because ActOnTag never produces a ClassTemplateDecl
6371 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006372 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006373 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6374 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006375 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006376 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006377
John McCalldd4a3b02009-09-16 22:47:08 +00006378 // This is definitely an error in C++98. It's probably meant to
6379 // be forbidden in C++0x, too, but the specification is just
6380 // poorly written.
6381 //
6382 // The problem is with declarations like the following:
6383 // template <T> friend A<T>::foo;
6384 // where deciding whether a class C is a friend or not now hinges
6385 // on whether there exists an instantiation of A that causes
6386 // 'foo' to equal C. There are restrictions on class-heads
6387 // (which we declare (by fiat) elaborated friend declarations to
6388 // be) that makes this tractable.
6389 //
6390 // FIXME: handle "template <> friend class A<T>;", which
6391 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006392 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006393 Diag(Loc, diag::err_tagless_friend_type_template)
6394 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006395 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006396 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006397
John McCall02cace72009-08-28 07:59:38 +00006398 // C++98 [class.friend]p1: A friend of a class is a function
6399 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006400 // This is fixed in DR77, which just barely didn't make the C++03
6401 // deadline. It's also a very silly restriction that seriously
6402 // affects inner classes and which nobody else seems to implement;
6403 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006404 //
6405 // But note that we could warn about it: it's always useless to
6406 // friend one of your own members (it's not, however, worthless to
6407 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006408
John McCalldd4a3b02009-09-16 22:47:08 +00006409 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006410 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006411 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006412 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006413 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006414 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006415 DS.getFriendSpecLoc());
6416 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006417 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6418
6419 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006420 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006421
John McCalldd4a3b02009-09-16 22:47:08 +00006422 D->setAccess(AS_public);
6423 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006424
John McCalld226f652010-08-21 09:40:31 +00006425 return D;
John McCall02cace72009-08-28 07:59:38 +00006426}
6427
John McCall337ec3d2010-10-12 23:13:28 +00006428Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6429 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006430 const DeclSpec &DS = D.getDeclSpec();
6431
6432 assert(DS.isFriendSpecified());
6433 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6434
6435 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006436 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6437 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006438
6439 // C++ [class.friend]p1
6440 // A friend of a class is a function or class....
6441 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006442 // It *doesn't* see through dependent types, which is correct
6443 // according to [temp.arg.type]p3:
6444 // If a declaration acquires a function type through a
6445 // type dependent on a template-parameter and this causes
6446 // a declaration that does not use the syntactic form of a
6447 // function declarator to have a function type, the program
6448 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006449 if (!T->isFunctionType()) {
6450 Diag(Loc, diag::err_unexpected_friend);
6451
6452 // It might be worthwhile to try to recover by creating an
6453 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006454 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006455 }
6456
6457 // C++ [namespace.memdef]p3
6458 // - If a friend declaration in a non-local class first declares a
6459 // class or function, the friend class or function is a member
6460 // of the innermost enclosing namespace.
6461 // - The name of the friend is not found by simple name lookup
6462 // until a matching declaration is provided in that namespace
6463 // scope (either before or after the class declaration granting
6464 // friendship).
6465 // - If a friend function is called, its name may be found by the
6466 // name lookup that considers functions from namespaces and
6467 // classes associated with the types of the function arguments.
6468 // - When looking for a prior declaration of a class or a function
6469 // declared as a friend, scopes outside the innermost enclosing
6470 // namespace scope are not considered.
6471
John McCall337ec3d2010-10-12 23:13:28 +00006472 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006473 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6474 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006475 assert(Name);
6476
John McCall67d1a672009-08-06 02:15:43 +00006477 // The context we found the declaration in, or in which we should
6478 // create the declaration.
6479 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006480 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006481 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006482 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006483
John McCall337ec3d2010-10-12 23:13:28 +00006484 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006485
John McCall337ec3d2010-10-12 23:13:28 +00006486 // There are four cases here.
6487 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006488 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006489 // there as appropriate.
6490 // Recover from invalid scope qualifiers as if they just weren't there.
6491 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006492 // C++0x [namespace.memdef]p3:
6493 // If the name in a friend declaration is neither qualified nor
6494 // a template-id and the declaration is a function or an
6495 // elaborated-type-specifier, the lookup to determine whether
6496 // the entity has been previously declared shall not consider
6497 // any scopes outside the innermost enclosing namespace.
6498 // C++0x [class.friend]p11:
6499 // If a friend declaration appears in a local class and the name
6500 // specified is an unqualified name, a prior declaration is
6501 // looked up without considering scopes that are outside the
6502 // innermost enclosing non-class scope. For a friend function
6503 // declaration, if there is no prior declaration, the program is
6504 // ill-formed.
6505 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006506 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006507
John McCall29ae6e52010-10-13 05:45:15 +00006508 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006509 DC = CurContext;
6510 while (true) {
6511 // Skip class contexts. If someone can cite chapter and verse
6512 // for this behavior, that would be nice --- it's what GCC and
6513 // EDG do, and it seems like a reasonable intent, but the spec
6514 // really only says that checks for unqualified existing
6515 // declarations should stop at the nearest enclosing namespace,
6516 // not that they should only consider the nearest enclosing
6517 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006518 while (DC->isRecord())
6519 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006520
John McCall68263142009-11-18 22:49:29 +00006521 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006522
6523 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006524 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006525 break;
John McCall29ae6e52010-10-13 05:45:15 +00006526
John McCall8a407372010-10-14 22:22:28 +00006527 if (isTemplateId) {
6528 if (isa<TranslationUnitDecl>(DC)) break;
6529 } else {
6530 if (DC->isFileContext()) break;
6531 }
John McCall67d1a672009-08-06 02:15:43 +00006532 DC = DC->getParent();
6533 }
6534
6535 // C++ [class.friend]p1: A friend of a class is a function or
6536 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006537 // C++0x changes this for both friend types and functions.
6538 // Most C++ 98 compilers do seem to give an error here, so
6539 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006540 if (!Previous.empty() && DC->Equals(CurContext)
6541 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006542 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006543
John McCall380aaa42010-10-13 06:22:15 +00006544 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006545
John McCall337ec3d2010-10-12 23:13:28 +00006546 // - There's a non-dependent scope specifier, in which case we
6547 // compute it and do a previous lookup there for a function
6548 // or function template.
6549 } else if (!SS.getScopeRep()->isDependent()) {
6550 DC = computeDeclContext(SS);
6551 if (!DC) return 0;
6552
6553 if (RequireCompleteDeclContext(SS, DC)) return 0;
6554
6555 LookupQualifiedName(Previous, DC);
6556
6557 // Ignore things found implicitly in the wrong scope.
6558 // TODO: better diagnostics for this case. Suggesting the right
6559 // qualified scope would be nice...
6560 LookupResult::Filter F = Previous.makeFilter();
6561 while (F.hasNext()) {
6562 NamedDecl *D = F.next();
6563 if (!DC->InEnclosingNamespaceSetOf(
6564 D->getDeclContext()->getRedeclContext()))
6565 F.erase();
6566 }
6567 F.done();
6568
6569 if (Previous.empty()) {
6570 D.setInvalidType();
6571 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6572 return 0;
6573 }
6574
6575 // C++ [class.friend]p1: A friend of a class is a function or
6576 // class that is not a member of the class . . .
6577 if (DC->Equals(CurContext))
6578 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6579
6580 // - There's a scope specifier that does not match any template
6581 // parameter lists, in which case we use some arbitrary context,
6582 // create a method or method template, and wait for instantiation.
6583 // - There's a scope specifier that does match some template
6584 // parameter lists, which we don't handle right now.
6585 } else {
6586 DC = CurContext;
6587 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006588 }
6589
John McCall29ae6e52010-10-13 05:45:15 +00006590 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006591 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006592 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6593 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6594 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006595 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006596 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6597 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006598 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006599 }
John McCall67d1a672009-08-06 02:15:43 +00006600 }
6601
Douglas Gregor182ddf02009-09-28 00:08:27 +00006602 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006603 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006604 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006605 IsDefinition,
6606 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006607 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006608
Douglas Gregor182ddf02009-09-28 00:08:27 +00006609 assert(ND->getDeclContext() == DC);
6610 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006611
John McCallab88d972009-08-31 22:39:49 +00006612 // Add the function declaration to the appropriate lookup tables,
6613 // adjusting the redeclarations list as necessary. We don't
6614 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006615 //
John McCallab88d972009-08-31 22:39:49 +00006616 // Also update the scope-based lookup if the target context's
6617 // lookup context is in lexical scope.
6618 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006619 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006620 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006621 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006622 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006623 }
John McCall02cace72009-08-28 07:59:38 +00006624
6625 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006626 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006627 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006628 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006629 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006630
John McCall337ec3d2010-10-12 23:13:28 +00006631 if (ND->isInvalidDecl())
6632 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006633 else {
6634 FunctionDecl *FD;
6635 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6636 FD = FTD->getTemplatedDecl();
6637 else
6638 FD = cast<FunctionDecl>(ND);
6639
6640 // Mark templated-scope function declarations as unsupported.
6641 if (FD->getNumTemplateParameterLists())
6642 FrD->setUnsupportedFriend(true);
6643 }
John McCall337ec3d2010-10-12 23:13:28 +00006644
John McCalld226f652010-08-21 09:40:31 +00006645 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006646}
6647
John McCalld226f652010-08-21 09:40:31 +00006648void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6649 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006650
Sebastian Redl50de12f2009-03-24 22:27:57 +00006651 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6652 if (!Fn) {
6653 Diag(DelLoc, diag::err_deleted_non_function);
6654 return;
6655 }
6656 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6657 Diag(DelLoc, diag::err_deleted_decl_not_first);
6658 Diag(Prev->getLocation(), diag::note_previous_declaration);
6659 // If the declaration wasn't the first, we delete the function anyway for
6660 // recovery.
6661 }
6662 Fn->setDeleted();
6663}
Sebastian Redl13e88542009-04-27 21:33:24 +00006664
6665static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6666 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6667 ++CI) {
6668 Stmt *SubStmt = *CI;
6669 if (!SubStmt)
6670 continue;
6671 if (isa<ReturnStmt>(SubStmt))
6672 Self.Diag(SubStmt->getSourceRange().getBegin(),
6673 diag::err_return_in_constructor_handler);
6674 if (!isa<Expr>(SubStmt))
6675 SearchForReturnInStmt(Self, SubStmt);
6676 }
6677}
6678
6679void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6680 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6681 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6682 SearchForReturnInStmt(*this, Handler);
6683 }
6684}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006685
Mike Stump1eb44332009-09-09 15:08:12 +00006686bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006687 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006688 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6689 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006690
Chandler Carruth73857792010-02-15 11:53:20 +00006691 if (Context.hasSameType(NewTy, OldTy) ||
6692 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006693 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006694
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006695 // Check if the return types are covariant
6696 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006697
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006698 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006699 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6700 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006701 NewClassTy = NewPT->getPointeeType();
6702 OldClassTy = OldPT->getPointeeType();
6703 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006704 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6705 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6706 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6707 NewClassTy = NewRT->getPointeeType();
6708 OldClassTy = OldRT->getPointeeType();
6709 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006710 }
6711 }
Mike Stump1eb44332009-09-09 15:08:12 +00006712
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006713 // The return types aren't either both pointers or references to a class type.
6714 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006715 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006716 diag::err_different_return_type_for_overriding_virtual_function)
6717 << New->getDeclName() << NewTy << OldTy;
6718 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006719
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006720 return true;
6721 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006722
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006723 // C++ [class.virtual]p6:
6724 // If the return type of D::f differs from the return type of B::f, the
6725 // class type in the return type of D::f shall be complete at the point of
6726 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006727 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6728 if (!RT->isBeingDefined() &&
6729 RequireCompleteType(New->getLocation(), NewClassTy,
6730 PDiag(diag::err_covariant_return_incomplete)
6731 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006732 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006733 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006734
Douglas Gregora4923eb2009-11-16 21:35:15 +00006735 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006736 // Check if the new class derives from the old class.
6737 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6738 Diag(New->getLocation(),
6739 diag::err_covariant_return_not_derived)
6740 << New->getDeclName() << NewTy << OldTy;
6741 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6742 return true;
6743 }
Mike Stump1eb44332009-09-09 15:08:12 +00006744
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006745 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006746 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006747 diag::err_covariant_return_inaccessible_base,
6748 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6749 // FIXME: Should this point to the return type?
6750 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006751 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6752 return true;
6753 }
6754 }
Mike Stump1eb44332009-09-09 15:08:12 +00006755
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006756 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006757 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006758 Diag(New->getLocation(),
6759 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006760 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006761 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6762 return true;
6763 };
Mike Stump1eb44332009-09-09 15:08:12 +00006764
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006765
6766 // The new class type must have the same or less qualifiers as the old type.
6767 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6768 Diag(New->getLocation(),
6769 diag::err_covariant_return_type_class_type_more_qualified)
6770 << New->getDeclName() << NewTy << OldTy;
6771 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6772 return true;
6773 };
Mike Stump1eb44332009-09-09 15:08:12 +00006774
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006775 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006776}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006777
Sean Huntbbd37c62009-11-21 08:43:09 +00006778bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6779 const CXXMethodDecl *Old)
6780{
6781 if (Old->hasAttr<FinalAttr>()) {
6782 Diag(New->getLocation(), diag::err_final_function_overridden)
6783 << New->getDeclName();
6784 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6785 return true;
6786 }
6787
6788 return false;
6789}
6790
Douglas Gregor4ba31362009-12-01 17:24:26 +00006791/// \brief Mark the given method pure.
6792///
6793/// \param Method the method to be marked pure.
6794///
6795/// \param InitRange the source range that covers the "0" initializer.
6796bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6797 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6798 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006799 return false;
6800 }
6801
6802 if (!Method->isInvalidDecl())
6803 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6804 << Method->getDeclName() << InitRange;
6805 return true;
6806}
6807
John McCall731ad842009-12-19 09:28:58 +00006808/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6809/// an initializer for the out-of-line declaration 'Dcl'. The scope
6810/// is a fresh scope pushed for just this purpose.
6811///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006812/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6813/// static data member of class X, names should be looked up in the scope of
6814/// class X.
John McCalld226f652010-08-21 09:40:31 +00006815void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006816 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006817 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006818
John McCall731ad842009-12-19 09:28:58 +00006819 // We should only get called for declarations with scope specifiers, like:
6820 // int foo::bar;
6821 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006822 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006823}
6824
6825/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006826/// initializer for the out-of-line declaration 'D'.
6827void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006828 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006829 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006830
John McCall731ad842009-12-19 09:28:58 +00006831 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006832 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006833}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006834
6835/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6836/// C++ if/switch/while/for statement.
6837/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006838DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006839 // C++ 6.4p2:
6840 // The declarator shall not specify a function or an array.
6841 // The type-specifier-seq shall not contain typedef and shall not declare a
6842 // new class or enumeration.
6843 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6844 "Parser allowed 'typedef' as storage class of condition decl.");
6845
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006846 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006847 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6848 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006849
6850 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6851 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6852 // would be created and CXXConditionDeclExpr wants a VarDecl.
6853 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6854 << D.getSourceRange();
6855 return DeclResult();
6856 } else if (OwnedTag && OwnedTag->isDefinition()) {
6857 // The type-specifier-seq shall not declare a new class or enumeration.
6858 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6859 }
6860
John McCalld226f652010-08-21 09:40:31 +00006861 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006862 if (!Dcl)
6863 return DeclResult();
6864
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006865 return Dcl;
6866}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006867
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006868void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6869 bool DefinitionRequired) {
6870 // Ignore any vtable uses in unevaluated operands or for classes that do
6871 // not have a vtable.
6872 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6873 CurContext->isDependentContext() ||
6874 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006875 return;
6876
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006877 // Try to insert this class into the map.
6878 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6879 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6880 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6881 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006882 // If we already had an entry, check to see if we are promoting this vtable
6883 // to required a definition. If so, we need to reappend to the VTableUses
6884 // list, since we may have already processed the first entry.
6885 if (DefinitionRequired && !Pos.first->second) {
6886 Pos.first->second = true;
6887 } else {
6888 // Otherwise, we can early exit.
6889 return;
6890 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006891 }
6892
6893 // Local classes need to have their virtual members marked
6894 // immediately. For all other classes, we mark their virtual members
6895 // at the end of the translation unit.
6896 if (Class->isLocalClass())
6897 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006898 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006899 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006900}
6901
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006902bool Sema::DefineUsedVTables() {
6903 // If any dynamic classes have their key function defined within
6904 // this translation unit, then those vtables are considered "used" and must
6905 // be emitted.
6906 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6907 if (const CXXMethodDecl *KeyFunction
6908 = Context.getKeyFunction(DynamicClasses[I])) {
6909 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006910 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006911 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6912 }
6913 }
6914
6915 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006916 return false;
6917
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006918 // Note: The VTableUses vector could grow as a result of marking
6919 // the members of a class as "used", so we check the size each
6920 // time through the loop and prefer indices (with are stable) to
6921 // iterators (which are not).
6922 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006923 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006924 if (!Class)
6925 continue;
6926
6927 SourceLocation Loc = VTableUses[I].second;
6928
6929 // If this class has a key function, but that key function is
6930 // defined in another translation unit, we don't need to emit the
6931 // vtable even though we're using it.
6932 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006933 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006934 switch (KeyFunction->getTemplateSpecializationKind()) {
6935 case TSK_Undeclared:
6936 case TSK_ExplicitSpecialization:
6937 case TSK_ExplicitInstantiationDeclaration:
6938 // The key function is in another translation unit.
6939 continue;
6940
6941 case TSK_ExplicitInstantiationDefinition:
6942 case TSK_ImplicitInstantiation:
6943 // We will be instantiating the key function.
6944 break;
6945 }
6946 } else if (!KeyFunction) {
6947 // If we have a class with no key function that is the subject
6948 // of an explicit instantiation declaration, suppress the
6949 // vtable; it will live with the explicit instantiation
6950 // definition.
6951 bool IsExplicitInstantiationDeclaration
6952 = Class->getTemplateSpecializationKind()
6953 == TSK_ExplicitInstantiationDeclaration;
6954 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6955 REnd = Class->redecls_end();
6956 R != REnd; ++R) {
6957 TemplateSpecializationKind TSK
6958 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6959 if (TSK == TSK_ExplicitInstantiationDeclaration)
6960 IsExplicitInstantiationDeclaration = true;
6961 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6962 IsExplicitInstantiationDeclaration = false;
6963 break;
6964 }
6965 }
6966
6967 if (IsExplicitInstantiationDeclaration)
6968 continue;
6969 }
6970
6971 // Mark all of the virtual members of this class as referenced, so
6972 // that we can build a vtable. Then, tell the AST consumer that a
6973 // vtable for this class is required.
6974 MarkVirtualMembersReferenced(Loc, Class);
6975 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6976 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6977
6978 // Optionally warn if we're emitting a weak vtable.
6979 if (Class->getLinkage() == ExternalLinkage &&
6980 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006981 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006982 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6983 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006984 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006985 VTableUses.clear();
6986
Anders Carlssond6a637f2009-12-07 08:24:59 +00006987 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006988}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006989
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006990void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6991 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006992 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6993 e = RD->method_end(); i != e; ++i) {
6994 CXXMethodDecl *MD = *i;
6995
6996 // C++ [basic.def.odr]p2:
6997 // [...] A virtual member function is used if it is not pure. [...]
6998 if (MD->isVirtual() && !MD->isPure())
6999 MarkDeclarationReferenced(Loc, MD);
7000 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007001
7002 // Only classes that have virtual bases need a VTT.
7003 if (RD->getNumVBases() == 0)
7004 return;
7005
7006 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7007 e = RD->bases_end(); i != e; ++i) {
7008 const CXXRecordDecl *Base =
7009 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007010 if (Base->getNumVBases() == 0)
7011 continue;
7012 MarkVirtualMembersReferenced(Loc, Base);
7013 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007014}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007015
7016/// SetIvarInitializers - This routine builds initialization ASTs for the
7017/// Objective-C implementation whose ivars need be initialized.
7018void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7019 if (!getLangOptions().CPlusPlus)
7020 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007021 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007022 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7023 CollectIvarsToConstructOrDestruct(OID, ivars);
7024 if (ivars.empty())
7025 return;
7026 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7027 for (unsigned i = 0; i < ivars.size(); i++) {
7028 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007029 if (Field->isInvalidDecl())
7030 continue;
7031
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007032 CXXBaseOrMemberInitializer *Member;
7033 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7034 InitializationKind InitKind =
7035 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7036
7037 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007038 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007039 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCall4765fa02010-12-06 08:20:24 +00007040 MemberInit = MaybeCreateExprWithCleanups(MemberInit.get());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007041 // Note, MemberInit could actually come back empty if no initialization
7042 // is required (e.g., because it would call a trivial default constructor)
7043 if (!MemberInit.get() || MemberInit.isInvalid())
7044 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007045
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007046 Member =
7047 new (Context) CXXBaseOrMemberInitializer(Context,
7048 Field, SourceLocation(),
7049 SourceLocation(),
7050 MemberInit.takeAs<Expr>(),
7051 SourceLocation());
7052 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007053
7054 // Be sure that the destructor is accessible and is marked as referenced.
7055 if (const RecordType *RecordTy
7056 = Context.getBaseElementType(Field->getType())
7057 ->getAs<RecordType>()) {
7058 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007059 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007060 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7061 CheckDestructorAccess(Field->getLocation(), Destructor,
7062 PDiag(diag::err_access_dtor_ivar)
7063 << Context.getBaseElementType(Field->getType()));
7064 }
7065 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007066 }
7067 ObjCImplementation->setIvarInitializers(Context,
7068 AllToInit.data(), AllToInit.size());
7069 }
7070}