blob: d53871591708f92b5141861e42095a746f13287f [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Anders Carlssonf1c26952009-08-25 01:02:06 +0000180 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000181 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
182 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000183 Param->setInvalidDecl();
184 return;
185 }
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCallb268a282010-08-23 23:25:46 +0000187 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000188}
189
Douglas Gregor58354032008-12-24 00:01:03 +0000190/// ActOnParamUnparsedDefaultArgument - We've seen a default
191/// argument for a function parameter, but we can't parse it yet
192/// because we're inside a class definition. Note that this default
193/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000194void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000195 SourceLocation EqualLoc,
196 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump11289f42009-09-09 15:08:12 +0000199
John McCall48871652010-08-21 09:40:31 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000201 if (Param)
202 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000205}
206
Douglas Gregor4d87df52008-12-16 21:30:33 +0000207/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
208/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000209void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000210 if (!param)
211 return;
Mike Stump11289f42009-09-09 15:08:12 +0000212
John McCall48871652010-08-21 09:40:31 +0000213 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000214
Anders Carlsson84613c42009-06-12 16:51:40 +0000215 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000216
Anders Carlsson84613c42009-06-12 16:51:40 +0000217 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000218}
219
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000220/// CheckExtraCXXDefaultArguments - Check for any extra default
221/// arguments in the declarator, which is not a function declaration
222/// or definition and therefore is not permitted to have default
223/// arguments. This routine should be invoked for every declarator
224/// that is not a function declaration or definition.
225void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
226 // C++ [dcl.fct.default]p3
227 // A default argument expression shall be specified only in the
228 // parameter-declaration-clause of a function declaration or in a
229 // template-parameter (14.1). It shall not be specified for a
230 // parameter pack. If it is specified in a
231 // parameter-declaration-clause, it shall not occur within a
232 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000234 DeclaratorChunk &chunk = D.getTypeObject(i);
235 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000236 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
237 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000238 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000239 if (Param->hasUnparsedDefaultArg()) {
240 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000241 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
242 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
243 delete Toks;
244 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000245 } else if (Param->getDefaultArg()) {
246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << Param->getDefaultArg()->getSourceRange();
248 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000249 }
250 }
251 }
252 }
253}
254
Chris Lattner199abbc2008-04-08 05:04:30 +0000255// MergeCXXFunctionDecl - Merge two declarations of the same C++
256// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000257// type. Subroutine of MergeFunctionDecl. Returns true if there was an
258// error, false otherwise.
259bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
260 bool Invalid = false;
261
Chris Lattner199abbc2008-04-08 05:04:30 +0000262 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000263 // For non-template functions, default arguments can be added in
264 // later declarations of a function in the same
265 // scope. Declarations in different scopes have completely
266 // distinct sets of default arguments. That is, declarations in
267 // inner scopes do not acquire default arguments from
268 // declarations in outer scopes, and vice versa. In a given
269 // function declaration, all parameters subsequent to a
270 // parameter with a default argument shall have default
271 // arguments supplied in this or previous declarations. A
272 // default argument shall not be redefined by a later
273 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000274 //
275 // C++ [dcl.fct.default]p6:
276 // Except for member functions of class templates, the default arguments
277 // in a member function definition that appears outside of the class
278 // definition are added to the set of default arguments provided by the
279 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000280 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
281 ParmVarDecl *OldParam = Old->getParamDecl(p);
282 ParmVarDecl *NewParam = New->getParamDecl(p);
283
Douglas Gregorc732aba2009-09-11 18:44:32 +0000284 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000285 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
286 // hint here. Alternatively, we could walk the type-source information
287 // for NewParam to find the last source location in the type... but it
288 // isn't worth the effort right now. This is the kind of test case that
289 // is hard to get right:
290
291 // int f(int);
292 // void g(int (*fp)(int) = f);
293 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000294 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000295 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000296 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000297
298 // Look for the function declaration where the default argument was
299 // actually written, which may be a declaration prior to Old.
300 for (FunctionDecl *Older = Old->getPreviousDeclaration();
301 Older; Older = Older->getPreviousDeclaration()) {
302 if (!Older->getParamDecl(p)->hasDefaultArg())
303 break;
304
305 OldParam = Older->getParamDecl(p);
306 }
307
308 Diag(OldParam->getLocation(), diag::note_previous_definition)
309 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000310 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000311 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000312 // Merge the old default argument into the new parameter.
313 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000314 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000315 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000316 if (OldParam->hasUninstantiatedDefaultArg())
317 NewParam->setUninstantiatedDefaultArg(
318 OldParam->getUninstantiatedDefaultArg());
319 else
John McCalle61b02b2010-05-04 01:53:42 +0000320 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000321 } else if (NewParam->hasDefaultArg()) {
322 if (New->getDescribedFunctionTemplate()) {
323 // Paragraph 4, quoted above, only applies to non-template functions.
324 Diag(NewParam->getLocation(),
325 diag::err_param_default_argument_template_redecl)
326 << NewParam->getDefaultArgRange();
327 Diag(Old->getLocation(), diag::note_template_prev_declaration)
328 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000329 } else if (New->getTemplateSpecializationKind()
330 != TSK_ImplicitInstantiation &&
331 New->getTemplateSpecializationKind() != TSK_Undeclared) {
332 // C++ [temp.expr.spec]p21:
333 // Default function arguments shall not be specified in a declaration
334 // or a definition for one of the following explicit specializations:
335 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000336 // - the explicit specialization of a member function template;
337 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000338 // template where the class template specialization to which the
339 // member function specialization belongs is implicitly
340 // instantiated.
341 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
342 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
343 << New->getDeclName()
344 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000345 } else if (New->getDeclContext()->isDependentContext()) {
346 // C++ [dcl.fct.default]p6 (DR217):
347 // Default arguments for a member function of a class template shall
348 // be specified on the initial declaration of the member function
349 // within the class template.
350 //
351 // Reading the tea leaves a bit in DR217 and its reference to DR205
352 // leads me to the conclusion that one cannot add default function
353 // arguments for an out-of-line definition of a member function of a
354 // dependent type.
355 int WhichKind = 2;
356 if (CXXRecordDecl *Record
357 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
358 if (Record->getDescribedClassTemplate())
359 WhichKind = 0;
360 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
361 WhichKind = 1;
362 else
363 WhichKind = 2;
364 }
365
366 Diag(NewParam->getLocation(),
367 diag::err_param_default_argument_member_template_redecl)
368 << WhichKind
369 << NewParam->getDefaultArgRange();
370 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000371 }
372 }
373
Douglas Gregorf40863c2010-02-12 07:32:17 +0000374 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000375 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000376
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000377 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000378}
379
380/// CheckCXXDefaultArguments - Verify that the default arguments for a
381/// function declaration are well-formed according to C++
382/// [dcl.fct.default].
383void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
384 unsigned NumParams = FD->getNumParams();
385 unsigned p;
386
387 // Find first parameter with a default argument
388 for (p = 0; p < NumParams; ++p) {
389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000390 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000391 break;
392 }
393
394 // C++ [dcl.fct.default]p4:
395 // In a given function declaration, all parameters
396 // subsequent to a parameter with a default argument shall
397 // have default arguments supplied in this or previous
398 // declarations. A default argument shall not be redefined
399 // by a later declaration (not even to the same value).
400 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000401 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000402 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000403 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000404 if (Param->isInvalidDecl())
405 /* We already complained about this parameter. */;
406 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000407 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000408 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000409 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000410 else
Mike Stump11289f42009-09-09 15:08:12 +0000411 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000412 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner199abbc2008-04-08 05:04:30 +0000414 LastMissingDefaultArg = p;
415 }
416 }
417
418 if (LastMissingDefaultArg > 0) {
419 // Some default arguments were missing. Clear out all of the
420 // default arguments up to (and including) the last missing
421 // default argument, so that we leave the function parameters
422 // in a semantically valid state.
423 for (p = 0; p <= LastMissingDefaultArg; ++p) {
424 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000425 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000426 Param->setDefaultArg(0);
427 }
428 }
429 }
430}
Douglas Gregor556877c2008-04-13 21:30:24 +0000431
Douglas Gregor61956c42008-10-31 09:07:45 +0000432/// isCurrentClassName - Determine whether the identifier II is the
433/// name of the class type currently being defined. In the case of
434/// nested classes, this will only return true if II is the name of
435/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000436bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
437 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000438 assert(getLangOptions().CPlusPlus && "No class names in C!");
439
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000440 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000441 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000442 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000443 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
444 } else
445 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
446
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000447 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000448 return &II == CurDecl->getIdentifier();
449 else
450 return false;
451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000454///
455/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
456/// and returns NULL otherwise.
457CXXBaseSpecifier *
458Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
459 SourceRange SpecifierRange,
460 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000461 TypeSourceInfo *TInfo) {
462 QualType BaseType = TInfo->getType();
463
Douglas Gregor463421d2009-03-03 04:44:36 +0000464 // C++ [class.union]p1:
465 // A union shall not have base classes.
466 if (Class->isUnion()) {
467 Diag(Class->getLocation(), diag::err_base_clause_on_union)
468 << SpecifierRange;
469 return 0;
470 }
471
472 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000473 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000474 Class->getTagKind() == TTK_Class,
475 Access, TInfo);
476
477 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000478
479 // Base specifiers must be record types.
480 if (!BaseType->isRecordType()) {
481 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
482 return 0;
483 }
484
485 // C++ [class.union]p1:
486 // A union shall not be used as a base class.
487 if (BaseType->isUnionType()) {
488 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
489 return 0;
490 }
491
492 // C++ [class.derived]p2:
493 // The class-name in a base-specifier shall not be an incompletely
494 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000495 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000496 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000497 << SpecifierRange)) {
498 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000499 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000500 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000501
Eli Friedmanc96d4962009-08-15 21:55:26 +0000502 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000503 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000504 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000505 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000506 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000507 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
508 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000509
Alexis Hunt96d5c762009-11-21 08:43:09 +0000510 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
511 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
512 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000513 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
514 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000515 return 0;
516 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000517
John McCall3696dcb2010-08-17 07:23:57 +0000518 if (BaseDecl->isInvalidDecl())
519 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000520
521 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000522 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000523 Class->getTagKind() == TTK_Class,
524 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000525}
526
Douglas Gregor556877c2008-04-13 21:30:24 +0000527/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
528/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000529/// example:
530/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000531/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000532BaseResult
John McCall48871652010-08-21 09:40:31 +0000533Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000534 bool Virtual, AccessSpecifier Access,
John McCallba7bf592010-08-24 05:47:05 +0000535 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000536 if (!classdecl)
537 return true;
538
Douglas Gregorc40290e2009-03-09 23:48:35 +0000539 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000541 if (!Class)
542 return true;
543
Nick Lewycky19b9f952010-07-26 16:56:01 +0000544 TypeSourceInfo *TInfo = 0;
545 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000546
547 if (DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
548 UPPC_BaseType))
549 return true;
550
Douglas Gregor463421d2009-03-03 04:44:36 +0000551 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000552 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000553 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000554
Douglas Gregor463421d2009-03-03 04:44:36 +0000555 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000556}
Douglas Gregor556877c2008-04-13 21:30:24 +0000557
Douglas Gregor463421d2009-03-03 04:44:36 +0000558/// \brief Performs the actual work of attaching the given base class
559/// specifiers to a C++ class.
560bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
561 unsigned NumBases) {
562 if (NumBases == 0)
563 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000564
565 // Used to keep track of which base types we have already seen, so
566 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000567 // that the key is always the unqualified canonical type of the base
568 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000569 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
570
571 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000572 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000573 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000574 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000575 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000577 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000578 if (!Class->hasObjectMember()) {
579 if (const RecordType *FDTTy =
580 NewBaseType.getTypePtr()->getAs<RecordType>())
581 if (FDTTy->getDecl()->hasObjectMember())
582 Class->setHasObjectMember(true);
583 }
584
Douglas Gregor29a92472008-10-22 17:49:05 +0000585 if (KnownBaseTypes[NewBaseType]) {
586 // C++ [class.mi]p3:
587 // A class shall not be specified as a direct base class of a
588 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000589 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000590 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000591 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000592 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000593
594 // Delete the duplicate base class specifier; we're going to
595 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000596 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000597
598 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000599 } else {
600 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000601 KnownBaseTypes[NewBaseType] = Bases[idx];
602 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000603 }
604 }
605
606 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000607 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000608
609 // Delete the remaining (good) base class specifiers, since their
610 // data has been copied into the CXXRecordDecl.
611 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000612 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000613
614 return Invalid;
615}
616
617/// ActOnBaseSpecifiers - Attach the given base specifiers to the
618/// class, after checking whether there are any duplicate base
619/// classes.
John McCall48871652010-08-21 09:40:31 +0000620void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 unsigned NumBases) {
622 if (!ClassDecl || !Bases || !NumBases)
623 return;
624
625 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000626 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000627 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000628}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000629
John McCalle78aac42010-03-10 03:28:59 +0000630static CXXRecordDecl *GetClassForType(QualType T) {
631 if (const RecordType *RT = T->getAs<RecordType>())
632 return cast<CXXRecordDecl>(RT->getDecl());
633 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
634 return ICT->getDecl();
635 else
636 return 0;
637}
638
Douglas Gregor36d1b142009-10-06 17:59:45 +0000639/// \brief Determine whether the type \p Derived is a C++ class that is
640/// derived from the type \p Base.
641bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
642 if (!getLangOptions().CPlusPlus)
643 return false;
John McCalle78aac42010-03-10 03:28:59 +0000644
645 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
646 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000647 return false;
648
John McCalle78aac42010-03-10 03:28:59 +0000649 CXXRecordDecl *BaseRD = GetClassForType(Base);
650 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000651 return false;
652
John McCall67da35c2010-02-04 22:26:26 +0000653 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
654 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000655}
656
657/// \brief Determine whether the type \p Derived is a C++ class that is
658/// derived from the type \p Base.
659bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
660 if (!getLangOptions().CPlusPlus)
661 return false;
662
John McCalle78aac42010-03-10 03:28:59 +0000663 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
664 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000665 return false;
666
John McCalle78aac42010-03-10 03:28:59 +0000667 CXXRecordDecl *BaseRD = GetClassForType(Base);
668 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000669 return false;
670
Douglas Gregor36d1b142009-10-06 17:59:45 +0000671 return DerivedRD->isDerivedFrom(BaseRD, Paths);
672}
673
Anders Carlssona70cff62010-04-24 19:06:50 +0000674void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000675 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000676 assert(BasePathArray.empty() && "Base path array must be empty!");
677 assert(Paths.isRecordingPaths() && "Must record paths!");
678
679 const CXXBasePath &Path = Paths.front();
680
681 // We first go backward and check if we have a virtual base.
682 // FIXME: It would be better if CXXBasePath had the base specifier for
683 // the nearest virtual base.
684 unsigned Start = 0;
685 for (unsigned I = Path.size(); I != 0; --I) {
686 if (Path[I - 1].Base->isVirtual()) {
687 Start = I - 1;
688 break;
689 }
690 }
691
692 // Now add all bases.
693 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000694 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000695}
696
Douglas Gregor88d292c2010-05-13 16:44:06 +0000697/// \brief Determine whether the given base path includes a virtual
698/// base class.
John McCallcf142162010-08-07 06:22:56 +0000699bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
700 for (CXXCastPath::const_iterator B = BasePath.begin(),
701 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000702 B != BEnd; ++B)
703 if ((*B)->isVirtual())
704 return true;
705
706 return false;
707}
708
Douglas Gregor36d1b142009-10-06 17:59:45 +0000709/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
710/// conversion (where Derived and Base are class types) is
711/// well-formed, meaning that the conversion is unambiguous (and
712/// that all of the base classes are accessible). Returns true
713/// and emits a diagnostic if the code is ill-formed, returns false
714/// otherwise. Loc is the location where this routine should point to
715/// if there is an error, and Range is the source range to highlight
716/// if there is an error.
717bool
718Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000719 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000720 unsigned AmbigiousBaseConvID,
721 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000722 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000723 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000724 // First, determine whether the path from Derived to Base is
725 // ambiguous. This is slightly more expensive than checking whether
726 // the Derived to Base conversion exists, because here we need to
727 // explore multiple paths to determine if there is an ambiguity.
728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
729 /*DetectVirtual=*/false);
730 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
731 assert(DerivationOkay &&
732 "Can only be used with a derived-to-base conversion");
733 (void)DerivationOkay;
734
735 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000736 if (InaccessibleBaseID) {
737 // Check that the base class can be accessed.
738 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
739 InaccessibleBaseID)) {
740 case AR_inaccessible:
741 return true;
742 case AR_accessible:
743 case AR_dependent:
744 case AR_delayed:
745 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000746 }
John McCall5b0829a2010-02-10 09:31:12 +0000747 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000748
749 // Build a base path if necessary.
750 if (BasePath)
751 BuildBasePathArray(Paths, *BasePath);
752 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000753 }
754
755 // We know that the derived-to-base conversion is ambiguous, and
756 // we're going to produce a diagnostic. Perform the derived-to-base
757 // search just one more time to compute all of the possible paths so
758 // that we can print them out. This is more expensive than any of
759 // the previous derived-to-base checks we've done, but at this point
760 // performance isn't as much of an issue.
761 Paths.clear();
762 Paths.setRecordingPaths(true);
763 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
764 assert(StillOkay && "Can only be used with a derived-to-base conversion");
765 (void)StillOkay;
766
767 // Build up a textual representation of the ambiguous paths, e.g.,
768 // D -> B -> A, that will be used to illustrate the ambiguous
769 // conversions in the diagnostic. We only print one of the paths
770 // to each base class subobject.
771 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
772
773 Diag(Loc, AmbigiousBaseConvID)
774 << Derived << Base << PathDisplayStr << Range << Name;
775 return true;
776}
777
778bool
779Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000780 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000781 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000782 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000783 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000784 IgnoreAccess ? 0
785 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000786 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000787 Loc, Range, DeclarationName(),
788 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000789}
790
791
792/// @brief Builds a string representing ambiguous paths from a
793/// specific derived class to different subobjects of the same base
794/// class.
795///
796/// This function builds a string that can be used in error messages
797/// to show the different paths that one can take through the
798/// inheritance hierarchy to go from the derived class to different
799/// subobjects of a base class. The result looks something like this:
800/// @code
801/// struct D -> struct B -> struct A
802/// struct D -> struct C -> struct A
803/// @endcode
804std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
805 std::string PathDisplayStr;
806 std::set<unsigned> DisplayedPaths;
807 for (CXXBasePaths::paths_iterator Path = Paths.begin();
808 Path != Paths.end(); ++Path) {
809 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
810 // We haven't displayed a path to this particular base
811 // class subobject yet.
812 PathDisplayStr += "\n ";
813 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
814 for (CXXBasePath::const_iterator Element = Path->begin();
815 Element != Path->end(); ++Element)
816 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
817 }
818 }
819
820 return PathDisplayStr;
821}
822
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000823//===----------------------------------------------------------------------===//
824// C++ class member Handling
825//===----------------------------------------------------------------------===//
826
Abramo Bagnarad7340582010-06-05 05:09:32 +0000827/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000828Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
829 SourceLocation ASLoc,
830 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000831 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000832 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000833 ASLoc, ColonLoc);
834 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000835 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000836}
837
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000838/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
839/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
840/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000841/// any.
John McCall48871652010-08-21 09:40:31 +0000842Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000843Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000844 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000845 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
846 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000847 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000848 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
849 DeclarationName Name = NameInfo.getName();
850 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000851
852 // For anonymous bitfields, the location should point to the type.
853 if (Loc.isInvalid())
854 Loc = D.getSourceRange().getBegin();
855
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000856 Expr *BitWidth = static_cast<Expr*>(BW);
857 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000858
John McCallb1cd7da2010-06-04 08:34:12 +0000859 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000860 assert(!DS.isFriendSpecified());
861
John McCallb1cd7da2010-06-04 08:34:12 +0000862 bool isFunc = false;
863 if (D.isFunctionDeclarator())
864 isFunc = true;
865 else if (D.getNumTypeObjects() == 0 &&
866 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000867 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000868 isFunc = TDType->isFunctionType();
869 }
870
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000871 // C++ 9.2p6: A member shall not be declared to have automatic storage
872 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000873 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
874 // data members and cannot be applied to names declared const or static,
875 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876 switch (DS.getStorageClassSpec()) {
877 case DeclSpec::SCS_unspecified:
878 case DeclSpec::SCS_typedef:
879 case DeclSpec::SCS_static:
880 // FALL THROUGH.
881 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000882 case DeclSpec::SCS_mutable:
883 if (isFunc) {
884 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000885 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000886 else
Chris Lattner3b054132008-11-19 05:08:23 +0000887 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Sebastian Redl8071edb2008-11-17 23:24:37 +0000889 // FIXME: It would be nicer if the keyword was ignored only for this
890 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000891 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000892 }
893 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 default:
895 if (DS.getStorageClassSpecLoc().isValid())
896 Diag(DS.getStorageClassSpecLoc(),
897 diag::err_storageclass_invalid_for_member);
898 else
899 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
900 D.getMutableDeclSpec().ClearStorageClassSpecs();
901 }
902
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000903 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
904 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000905 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000906
907 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000908 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000909 CXXScopeSpec &SS = D.getCXXScopeSpec();
910
911
912 if (SS.isSet() && !SS.isInvalid()) {
913 // The user provided a superfluous scope specifier inside a class
914 // definition:
915 //
916 // class X {
917 // int X::member;
918 // };
919 DeclContext *DC = 0;
920 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
921 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
922 << Name << FixItHint::CreateRemoval(SS.getRange());
923 else
924 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
925 << Name << SS.getRange();
926
927 SS.clear();
928 }
929
Douglas Gregor3447e762009-08-20 22:52:58 +0000930 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000931 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
932 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000933 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000934 } else {
John McCall48871652010-08-21 09:40:31 +0000935 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000936 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000937 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000938 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000939
940 // Non-instance-fields can't have a bitfield.
941 if (BitWidth) {
942 if (Member->isInvalidDecl()) {
943 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000944 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000945 // C++ 9.6p3: A bit-field shall not be a static member.
946 // "static member 'A' cannot be a bit-field"
947 Diag(Loc, diag::err_static_not_bitfield)
948 << Name << BitWidth->getSourceRange();
949 } else if (isa<TypedefDecl>(Member)) {
950 // "typedef member 'x' cannot be a bit-field"
951 Diag(Loc, diag::err_typedef_not_bitfield)
952 << Name << BitWidth->getSourceRange();
953 } else {
954 // A function typedef ("typedef int f(); f a;").
955 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
956 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000957 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000958 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattnerd26760a2009-03-05 23:01:03 +0000961 BitWidth = 0;
962 Member->setInvalidDecl();
963 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000964
965 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000966
Douglas Gregor3447e762009-08-20 22:52:58 +0000967 // If we have declared a member function template, set the access of the
968 // templated declaration as well.
969 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
970 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000971 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000972
Douglas Gregor92751d42008-11-17 22:58:34 +0000973 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000974
Douglas Gregor0c880302009-03-11 23:00:04 +0000975 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000976 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000977 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000978 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000979
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000980 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000981 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +0000982 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000983 }
John McCall48871652010-08-21 09:40:31 +0000984 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000985}
986
Douglas Gregor15e77a22009-12-31 09:10:24 +0000987/// \brief Find the direct and/or virtual base specifiers that
988/// correspond to the given base type, for use in base initialization
989/// within a constructor.
990static bool FindBaseInitializer(Sema &SemaRef,
991 CXXRecordDecl *ClassDecl,
992 QualType BaseType,
993 const CXXBaseSpecifier *&DirectBaseSpec,
994 const CXXBaseSpecifier *&VirtualBaseSpec) {
995 // First, check for a direct base class.
996 DirectBaseSpec = 0;
997 for (CXXRecordDecl::base_class_const_iterator Base
998 = ClassDecl->bases_begin();
999 Base != ClassDecl->bases_end(); ++Base) {
1000 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1001 // We found a direct base of this type. That's what we're
1002 // initializing.
1003 DirectBaseSpec = &*Base;
1004 break;
1005 }
1006 }
1007
1008 // Check for a virtual base class.
1009 // FIXME: We might be able to short-circuit this if we know in advance that
1010 // there are no virtual bases.
1011 VirtualBaseSpec = 0;
1012 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1013 // We haven't found a base yet; search the class hierarchy for a
1014 // virtual base class.
1015 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1016 /*DetectVirtual=*/false);
1017 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1018 BaseType, Paths)) {
1019 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1020 Path != Paths.end(); ++Path) {
1021 if (Path->back().Base->isVirtual()) {
1022 VirtualBaseSpec = Path->back().Base;
1023 break;
1024 }
1025 }
1026 }
1027 }
1028
1029 return DirectBaseSpec || VirtualBaseSpec;
1030}
1031
Douglas Gregore8381c02008-11-05 04:29:56 +00001032/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001033MemInitResult
John McCall48871652010-08-21 09:40:31 +00001034Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001035 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001036 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001037 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001038 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001039 SourceLocation IdLoc,
1040 SourceLocation LParenLoc,
1041 ExprTy **Args, unsigned NumArgs,
Douglas Gregore8381c02008-11-05 04:29:56 +00001042 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001043 if (!ConstructorD)
1044 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001045
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001046 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001047
1048 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001049 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001050 if (!Constructor) {
1051 // The user wrote a constructor initializer on a function that is
1052 // not a C++ constructor. Ignore the error for now, because we may
1053 // have more member initializers coming; we'll diagnose it just
1054 // once in ActOnMemInitializers.
1055 return true;
1056 }
1057
1058 CXXRecordDecl *ClassDecl = Constructor->getParent();
1059
1060 // C++ [class.base.init]p2:
1061 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001062 // constructor's class and, if not found in that scope, are looked
1063 // up in the scope containing the constructor's definition.
1064 // [Note: if the constructor's class contains a member with the
1065 // same name as a direct or virtual base class of the class, a
1066 // mem-initializer-id naming the member or base class and composed
1067 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001068 // mem-initializer-id for the hidden base class may be specified
1069 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001070 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001071 // Look for a member, first.
1072 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001073 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001074 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001075 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001076 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001077
Francois Pichetd583da02010-12-04 09:14:42 +00001078 if (Member)
1079 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001080 LParenLoc, RParenLoc);
Francois Pichetd583da02010-12-04 09:14:42 +00001081 // Handle anonymous union case.
1082 if (IndirectFieldDecl* IndirectField
1083 = dyn_cast<IndirectFieldDecl>(*Result.first))
1084 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1085 NumArgs, IdLoc,
1086 LParenLoc, RParenLoc);
1087 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001088 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001089 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001090 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001091 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001092
1093 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001094 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001095 } else {
1096 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1097 LookupParsedName(R, S, &SS);
1098
1099 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1100 if (!TyD) {
1101 if (R.isAmbiguous()) return true;
1102
John McCallda6841b2010-04-09 19:01:14 +00001103 // We don't want access-control diagnostics here.
1104 R.suppressDiagnostics();
1105
Douglas Gregora3b624a2010-01-19 06:46:48 +00001106 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1107 bool NotUnknownSpecialization = false;
1108 DeclContext *DC = computeDeclContext(SS, false);
1109 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1110 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1111
1112 if (!NotUnknownSpecialization) {
1113 // When the scope specifier can refer to a member of an unknown
1114 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001115 BaseType = CheckTypenameType(ETK_None,
1116 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001117 *MemberOrBase, SourceLocation(),
1118 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001119 if (BaseType.isNull())
1120 return true;
1121
Douglas Gregora3b624a2010-01-19 06:46:48 +00001122 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001123 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001124 }
1125 }
1126
Douglas Gregor15e77a22009-12-31 09:10:24 +00001127 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001128 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001129 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1130 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001131 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001132 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001133 // We have found a non-static data member with a similar
1134 // name to what was typed; complain and initialize that
1135 // member.
1136 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1137 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001138 << FixItHint::CreateReplacement(R.getNameLoc(),
1139 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001140 Diag(Member->getLocation(), diag::note_previous_decl)
1141 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001142
1143 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1144 LParenLoc, RParenLoc);
1145 }
1146 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1147 const CXXBaseSpecifier *DirectBaseSpec;
1148 const CXXBaseSpecifier *VirtualBaseSpec;
1149 if (FindBaseInitializer(*this, ClassDecl,
1150 Context.getTypeDeclType(Type),
1151 DirectBaseSpec, VirtualBaseSpec)) {
1152 // We have found a direct or virtual base class with a
1153 // similar name to what was typed; complain and initialize
1154 // that base class.
1155 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1156 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001157 << FixItHint::CreateReplacement(R.getNameLoc(),
1158 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001159
1160 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1161 : VirtualBaseSpec;
1162 Diag(BaseSpec->getSourceRange().getBegin(),
1163 diag::note_base_class_specified_here)
1164 << BaseSpec->getType()
1165 << BaseSpec->getSourceRange();
1166
Douglas Gregor15e77a22009-12-31 09:10:24 +00001167 TyD = Type;
1168 }
1169 }
1170 }
1171
Douglas Gregora3b624a2010-01-19 06:46:48 +00001172 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001173 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1174 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1175 return true;
1176 }
John McCallb5a0d312009-12-21 10:41:20 +00001177 }
1178
Douglas Gregora3b624a2010-01-19 06:46:48 +00001179 if (BaseType.isNull()) {
1180 BaseType = Context.getTypeDeclType(TyD);
1181 if (SS.isSet()) {
1182 NestedNameSpecifier *Qualifier =
1183 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001184
Douglas Gregora3b624a2010-01-19 06:46:48 +00001185 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001186 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001187 }
John McCallb5a0d312009-12-21 10:41:20 +00001188 }
1189 }
Mike Stump11289f42009-09-09 15:08:12 +00001190
John McCallbcd03502009-12-07 02:54:59 +00001191 if (!TInfo)
1192 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001193
John McCallbcd03502009-12-07 02:54:59 +00001194 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001195 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001196}
1197
John McCalle22a04a2009-11-04 23:02:40 +00001198/// Checks an initializer expression for use of uninitialized fields, such as
1199/// containing the field that is being initialized. Returns true if there is an
1200/// uninitialized field was used an updates the SourceLocation parameter; false
1201/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001202static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001203 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001204 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001205 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1206
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001207 if (isa<CallExpr>(S)) {
1208 // Do not descend into function calls or constructors, as the use
1209 // of an uninitialized field may be valid. One would have to inspect
1210 // the contents of the function/ctor to determine if it is safe or not.
1211 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1212 // may be safe, depending on what the function/ctor does.
1213 return false;
1214 }
1215 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1216 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001217
1218 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1219 // The member expression points to a static data member.
1220 assert(VD->isStaticDataMember() &&
1221 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001222 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001223 return false;
1224 }
1225
1226 if (isa<EnumConstantDecl>(RhsField)) {
1227 // The member expression points to an enum.
1228 return false;
1229 }
1230
John McCalle22a04a2009-11-04 23:02:40 +00001231 if (RhsField == LhsField) {
1232 // Initializing a field with itself. Throw a warning.
1233 // But wait; there are exceptions!
1234 // Exception #1: The field may not belong to this record.
1235 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001236 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001237 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1238 // Even though the field matches, it does not belong to this record.
1239 return false;
1240 }
1241 // None of the exceptions triggered; return true to indicate an
1242 // uninitialized field was used.
1243 *L = ME->getMemberLoc();
1244 return true;
1245 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001246 } else if (isa<SizeOfAlignOfExpr>(S)) {
1247 // sizeof/alignof doesn't reference contents, do not warn.
1248 return false;
1249 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1250 // address-of doesn't reference contents (the pointer may be dereferenced
1251 // in the same expression but it would be rare; and weird).
1252 if (UOE->getOpcode() == UO_AddrOf)
1253 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001254 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001255 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1256 it != e; ++it) {
1257 if (!*it) {
1258 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001259 continue;
1260 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001261 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1262 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001263 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001264 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001265}
1266
John McCallfaf5fb42010-08-26 23:41:50 +00001267MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001268Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001269 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001270 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001271 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001272 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1273 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1274 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001275 "Member must be a FieldDecl or IndirectFieldDecl");
1276
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001277 if (Member->isInvalidDecl())
1278 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001279
John McCalle22a04a2009-11-04 23:02:40 +00001280 // Diagnose value-uses of fields to initialize themselves, e.g.
1281 // foo(foo)
1282 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001283 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001284 for (unsigned i = 0; i < NumArgs; ++i) {
1285 SourceLocation L;
1286 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1287 // FIXME: Return true in the case when other fields are used before being
1288 // uninitialized. For example, let this field be the i'th field. When
1289 // initializing the i'th field, throw a warning if any of the >= i'th
1290 // fields are used, as they are not yet initialized.
1291 // Right now we are only handling the case where the i'th field uses
1292 // itself in its initializer.
1293 Diag(L, diag::warn_field_is_uninit);
1294 }
1295 }
1296
Eli Friedman8e1433b2009-07-29 19:44:27 +00001297 bool HasDependentArg = false;
1298 for (unsigned i = 0; i < NumArgs; i++)
1299 HasDependentArg |= Args[i]->isTypeDependent();
1300
Chandler Carruthd44c3102010-12-06 09:23:57 +00001301 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001302 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001303 // Can't check initialization for a member of dependent type or when
1304 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001305 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1306 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001307
1308 // Erase any temporaries within this evaluation context; we're not
1309 // going to track them in the AST, since we'll be rebuilding the
1310 // ASTs during template instantiation.
1311 ExprTemporaries.erase(
1312 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1313 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001314 } else {
1315 // Initialize the member.
1316 InitializedEntity MemberEntity =
1317 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1318 : InitializedEntity::InitializeMember(IndirectMember, 0);
1319 InitializationKind Kind =
1320 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001321
Chandler Carruthd44c3102010-12-06 09:23:57 +00001322 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1323
1324 ExprResult MemberInit =
1325 InitSeq.Perform(*this, MemberEntity, Kind,
1326 MultiExprArg(*this, Args, NumArgs), 0);
1327 if (MemberInit.isInvalid())
1328 return true;
1329
1330 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1331
1332 // C++0x [class.base.init]p7:
1333 // The initialization of each base and member constitutes a
1334 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001335 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001336 if (MemberInit.isInvalid())
1337 return true;
1338
1339 // If we are in a dependent context, template instantiation will
1340 // perform this type-checking again. Just save the arguments that we
1341 // received in a ParenListExpr.
1342 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1343 // of the information that we have about the member
1344 // initializer. However, deconstructing the ASTs is a dicey process,
1345 // and this approach is far more likely to get the corner cases right.
1346 if (CurContext->isDependentContext())
1347 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1348 RParenLoc);
1349 else
1350 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001351 }
1352
Chandler Carruthd44c3102010-12-06 09:23:57 +00001353 if (DirectMember) {
1354 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember,
1355 IdLoc, LParenLoc, Init,
1356 RParenLoc);
1357 } else {
1358 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember,
1359 IdLoc, LParenLoc, Init,
1360 RParenLoc);
1361 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001362}
1363
John McCallfaf5fb42010-08-26 23:41:50 +00001364MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001365Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001366 Expr **Args, unsigned NumArgs,
1367 SourceLocation LParenLoc, SourceLocation RParenLoc,
1368 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001369 bool HasDependentArg = false;
1370 for (unsigned i = 0; i < NumArgs; i++)
1371 HasDependentArg |= Args[i]->isTypeDependent();
1372
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001373 SourceLocation BaseLoc
1374 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1375
1376 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1377 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1378 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1379
1380 // C++ [class.base.init]p2:
1381 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001382 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001383 // of that class, the mem-initializer is ill-formed. A
1384 // mem-initializer-list can initialize a base class using any
1385 // name that denotes that base class type.
1386 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1387
1388 // Check for direct and virtual base classes.
1389 const CXXBaseSpecifier *DirectBaseSpec = 0;
1390 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1391 if (!Dependent) {
1392 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1393 VirtualBaseSpec);
1394
1395 // C++ [base.class.init]p2:
1396 // Unless the mem-initializer-id names a nonstatic data member of the
1397 // constructor's class or a direct or virtual base of that class, the
1398 // mem-initializer is ill-formed.
1399 if (!DirectBaseSpec && !VirtualBaseSpec) {
1400 // If the class has any dependent bases, then it's possible that
1401 // one of those types will resolve to the same type as
1402 // BaseType. Therefore, just treat this as a dependent base
1403 // class initialization. FIXME: Should we try to check the
1404 // initialization anyway? It seems odd.
1405 if (ClassDecl->hasAnyDependentBases())
1406 Dependent = true;
1407 else
1408 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1409 << BaseType << Context.getTypeDeclType(ClassDecl)
1410 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1411 }
1412 }
1413
1414 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415 // Can't check initialization for a base of dependent type or when
1416 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001417 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001418 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1419 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001420
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001421 // Erase any temporaries within this evaluation context; we're not
1422 // going to track them in the AST, since we'll be rebuilding the
1423 // ASTs during template instantiation.
1424 ExprTemporaries.erase(
1425 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1426 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001427
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001428 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001429 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001430 LParenLoc,
1431 BaseInit.takeAs<Expr>(),
1432 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001433 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001434
1435 // C++ [base.class.init]p2:
1436 // If a mem-initializer-id is ambiguous because it designates both
1437 // a direct non-virtual base class and an inherited virtual base
1438 // class, the mem-initializer is ill-formed.
1439 if (DirectBaseSpec && VirtualBaseSpec)
1440 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001441 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001442
1443 CXXBaseSpecifier *BaseSpec
1444 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1445 if (!BaseSpec)
1446 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1447
1448 // Initialize the base.
1449 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001450 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001451 InitializationKind Kind =
1452 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1453
1454 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1455
John McCalldadc5752010-08-24 06:29:42 +00001456 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001457 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001458 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001459 if (BaseInit.isInvalid())
1460 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001461
1462 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001463
1464 // C++0x [class.base.init]p7:
1465 // The initialization of each base and member constitutes a
1466 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001467 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001468 if (BaseInit.isInvalid())
1469 return true;
1470
1471 // If we are in a dependent context, template instantiation will
1472 // perform this type-checking again. Just save the arguments that we
1473 // received in a ParenListExpr.
1474 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1475 // of the information that we have about the base
1476 // initializer. However, deconstructing the ASTs is a dicey process,
1477 // and this approach is far more likely to get the corner cases right.
1478 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001479 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001480 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1481 RParenLoc));
1482 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001483 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001484 LParenLoc,
1485 Init.takeAs<Expr>(),
1486 RParenLoc);
1487 }
1488
1489 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001490 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001491 LParenLoc,
1492 BaseInit.takeAs<Expr>(),
1493 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001494}
1495
Anders Carlsson1b00e242010-04-23 03:10:23 +00001496/// ImplicitInitializerKind - How an implicit base or member initializer should
1497/// initialize its base or member.
1498enum ImplicitInitializerKind {
1499 IIK_Default,
1500 IIK_Copy,
1501 IIK_Move
1502};
1503
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001504static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001505BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001506 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001507 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001508 bool IsInheritedVirtualBase,
1509 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001510 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001511 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1512 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001513
John McCalldadc5752010-08-24 06:29:42 +00001514 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001515
1516 switch (ImplicitInitKind) {
1517 case IIK_Default: {
1518 InitializationKind InitKind
1519 = InitializationKind::CreateDefault(Constructor->getLocation());
1520 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1521 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001522 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001523 break;
1524 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001525
Anders Carlsson1b00e242010-04-23 03:10:23 +00001526 case IIK_Copy: {
1527 ParmVarDecl *Param = Constructor->getParamDecl(0);
1528 QualType ParamType = Param->getType().getNonReferenceType();
1529
1530 Expr *CopyCtorArg =
1531 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001532 Constructor->getLocation(), ParamType,
1533 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001534
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001535 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001536 QualType ArgTy =
1537 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1538 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001539
1540 CXXCastPath BasePath;
1541 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001542 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001543 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001544 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001545
Anders Carlsson1b00e242010-04-23 03:10:23 +00001546 InitializationKind InitKind
1547 = InitializationKind::CreateDirect(Constructor->getLocation(),
1548 SourceLocation(), SourceLocation());
1549 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1550 &CopyCtorArg, 1);
1551 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001552 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001553 break;
1554 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001555
Anders Carlsson1b00e242010-04-23 03:10:23 +00001556 case IIK_Move:
1557 assert(false && "Unhandled initializer kind!");
1558 }
John McCallb268a282010-08-23 23:25:46 +00001559
Douglas Gregora40433a2010-12-07 00:41:46 +00001560 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001561 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001562 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001563
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001564 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001565 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1566 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1567 SourceLocation()),
1568 BaseSpec->isVirtual(),
1569 SourceLocation(),
1570 BaseInit.takeAs<Expr>(),
1571 SourceLocation());
1572
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001573 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001574}
1575
Anders Carlsson3c1db572010-04-23 02:15:47 +00001576static bool
1577BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001578 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001579 FieldDecl *Field,
1580 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001581 if (Field->isInvalidDecl())
1582 return true;
1583
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001584 SourceLocation Loc = Constructor->getLocation();
1585
Anders Carlsson423f5d82010-04-23 16:04:08 +00001586 if (ImplicitInitKind == IIK_Copy) {
1587 ParmVarDecl *Param = Constructor->getParamDecl(0);
1588 QualType ParamType = Param->getType().getNonReferenceType();
1589
1590 Expr *MemberExprBase =
1591 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001592 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001593
1594 // Build a reference to this field within the parameter.
1595 CXXScopeSpec SS;
1596 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1597 Sema::LookupMemberName);
1598 MemberLookup.addDecl(Field, AS_public);
1599 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001600 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001601 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001602 ParamType, Loc,
1603 /*IsArrow=*/false,
1604 SS,
1605 /*FirstQualifierInScope=*/0,
1606 MemberLookup,
1607 /*TemplateArgs=*/0);
1608 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001609 return true;
1610
Douglas Gregor94f9a482010-05-05 05:51:00 +00001611 // When the field we are copying is an array, create index variables for
1612 // each dimension of the array. We use these index variables to subscript
1613 // the source array, and other clients (e.g., CodeGen) will perform the
1614 // necessary iteration with these index variables.
1615 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1616 QualType BaseType = Field->getType();
1617 QualType SizeType = SemaRef.Context.getSizeType();
1618 while (const ConstantArrayType *Array
1619 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1620 // Create the iteration variable for this array index.
1621 IdentifierInfo *IterationVarName = 0;
1622 {
1623 llvm::SmallString<8> Str;
1624 llvm::raw_svector_ostream OS(Str);
1625 OS << "__i" << IndexVariables.size();
1626 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1627 }
1628 VarDecl *IterationVar
1629 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1630 IterationVarName, SizeType,
1631 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001632 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001633 IndexVariables.push_back(IterationVar);
1634
1635 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001636 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001637 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001638 assert(!IterationVarRef.isInvalid() &&
1639 "Reference to invented variable cannot fail!");
1640
1641 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001642 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001643 Loc,
John McCallb268a282010-08-23 23:25:46 +00001644 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001645 Loc);
1646 if (CopyCtorArg.isInvalid())
1647 return true;
1648
1649 BaseType = Array->getElementType();
1650 }
1651
1652 // Construct the entity that we will be initializing. For an array, this
1653 // will be first element in the array, which may require several levels
1654 // of array-subscript entities.
1655 llvm::SmallVector<InitializedEntity, 4> Entities;
1656 Entities.reserve(1 + IndexVariables.size());
1657 Entities.push_back(InitializedEntity::InitializeMember(Field));
1658 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1659 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1660 0,
1661 Entities.back()));
1662
1663 // Direct-initialize to use the copy constructor.
1664 InitializationKind InitKind =
1665 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1666
1667 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1668 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1669 &CopyCtorArgE, 1);
1670
John McCalldadc5752010-08-24 06:29:42 +00001671 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001672 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001673 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001674 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001675 if (MemberInit.isInvalid())
1676 return true;
1677
1678 CXXMemberInit
1679 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1680 MemberInit.takeAs<Expr>(), Loc,
1681 IndexVariables.data(),
1682 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001683 return false;
1684 }
1685
Anders Carlsson423f5d82010-04-23 16:04:08 +00001686 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1687
Anders Carlsson3c1db572010-04-23 02:15:47 +00001688 QualType FieldBaseElementType =
1689 SemaRef.Context.getBaseElementType(Field->getType());
1690
Anders Carlsson3c1db572010-04-23 02:15:47 +00001691 if (FieldBaseElementType->isRecordType()) {
1692 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001693 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001694 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001695
1696 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001697 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001698 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001699
Douglas Gregora40433a2010-12-07 00:41:46 +00001700 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001701 if (MemberInit.isInvalid())
1702 return true;
1703
1704 CXXMemberInit =
1705 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001706 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001707 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001708 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001709 return false;
1710 }
Anders Carlssondca6be02010-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 Carlsson3c1db572010-04-23 02:15:47 +00001731
1732 // Nothing to initialize.
1733 CXXMemberInit = 0;
1734 return false;
1735}
John McCallbc83b3f2010-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 Carruth139e9622010-06-30 02:59:29 +00001760 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001761 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001762 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-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 McCallbc83b3f2010-05-20 23:23:51 +00001769 CXXRecordDecl *FieldClassDecl
1770 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-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 Pichetd583da02010-12-04 09:14:42 +00001782 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-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 Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001787 } else if ((*FA)->isAnonymousStructOrUnion()) {
1788 if (CollectFieldInitializer(Info, Top, *FA))
1789 return true;
Chandler Carruth139e9622010-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 McCallbc83b3f2010-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 McCallbc83b3f2010-05-20 23:23:51 +00001818
Francois Pichetd583da02010-12-04 09:14:42 +00001819 if (Init)
1820 Info.AllToInit.push_back(Init);
1821
John McCallbc83b3f2010-05-20 23:23:51 +00001822 return false;
1823}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001824
Eli Friedman9cf6b592009-11-09 19:20:36 +00001825bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001826Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001827 CXXBaseOrMemberInitializer **Initializers,
1828 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001829 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001830 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-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 McCallbc83b3f2010-05-20 23:23:51 +00001845 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001846
Fariborz Jahanian3501bce2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00001849 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001850 if (!ClassDecl)
1851 return true;
1852
Eli Friedman9cf6b592009-11-09 19:20:36 +00001853 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001854
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001855 for (unsigned i = 0; i < NumInitializers; i++) {
1856 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001857
1858 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001859 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001860 else
Francois Pichetd583da02010-12-04 09:14:42 +00001861 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001862 }
1863
Anders Carlsson43c64af2010-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 Carlssondb0a9652010-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 McCallbc83b3f2010-05-20 23:23:51 +00001877 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1878 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001879 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001880 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001881 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001882 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001883 VBase, IsInheritedVirtualBase,
1884 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001885 HadError = true;
1886 continue;
1887 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001888
John McCallbc83b3f2010-05-20 23:23:51 +00001889 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001890 }
1891 }
Mike Stump11289f42009-09-09 15:08:12 +00001892
John McCallbc83b3f2010-05-20 23:23:51 +00001893 // Non-virtual bases.
Anders Carlssondb0a9652010-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 Stump11289f42009-09-09 15:08:12 +00001899
Anders Carlssondb0a9652010-04-02 06:26:44 +00001900 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001901 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1902 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001903 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001904 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001905 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001906 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001907 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001908 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001909 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001910 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001911
John McCallbc83b3f2010-05-20 23:23:51 +00001912 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001913 }
1914 }
Mike Stump11289f42009-09-09 15:08:12 +00001915
John McCallbc83b3f2010-05-20 23:23:51 +00001916 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001917 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-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 McCallbc83b3f2010-05-20 23:23:51 +00001924 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001925 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001926 }
Mike Stump11289f42009-09-09 15:08:12 +00001927
John McCallbc83b3f2010-05-20 23:23:51 +00001928 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001929 if (NumInitializers > 0) {
1930 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1931 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1932 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001933 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001934 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001935 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001936
John McCalla6309952010-03-16 21:39:52 +00001937 // Constructors implicitly reference the base and member
1938 // destructors.
1939 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1940 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001941 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001942
1943 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001944}
1945
Eli Friedman952c15d2009-07-21 19:28:10 +00001946static void *GetKeyForTopLevelField(FieldDecl *Field) {
1947 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001948 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00001955static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1956 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001957}
1958
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001959static void *GetKeyForMember(ASTContext &Context,
Francois Pichetd583da02010-12-04 09:14:42 +00001960 CXXBaseOrMemberInitializer *Member) {
1961 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001962 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001963
Eli Friedman952c15d2009-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 Pichetd583da02010-12-04 09:14:42 +00001966 FieldDecl *Field = Member->getAnyMember();
1967
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00001970 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00001980 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Anders Carlssona942dcd2010-03-30 15:39:27 +00001983 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001984}
1985
Anders Carlssone857b292010-04-02 03:37:03 +00001986static void
1987DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001988 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001989 CXXBaseOrMemberInitializer **Inits,
1990 unsigned NumInits) {
1991 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001992 return;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001994 // Don't check initializers order unless the warning is enabled at the
1995 // location of at least one initializer.
1996 bool ShouldCheckOrder = false;
1997 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1998 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1999 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2000 Init->getSourceLocation())
2001 != Diagnostic::Ignored) {
2002 ShouldCheckOrder = true;
2003 break;
2004 }
2005 }
2006 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002007 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002008
John McCallbb7b6582010-04-10 07:37:23 +00002009 // Build the list of bases and members in the order that they'll
2010 // actually be initialized. The explicit initializers should be in
2011 // this same order but may be missing things.
2012 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002013
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002014 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2015
John McCallbb7b6582010-04-10 07:37:23 +00002016 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002017 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002018 ClassDecl->vbases_begin(),
2019 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002020 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002021
John McCallbb7b6582010-04-10 07:37:23 +00002022 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002023 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002024 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002025 if (Base->isVirtual())
2026 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002027 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
John McCallbb7b6582010-04-10 07:37:23 +00002030 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002031 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2032 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002033 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCallbb7b6582010-04-10 07:37:23 +00002035 unsigned NumIdealInits = IdealInitKeys.size();
2036 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002037
John McCallbb7b6582010-04-10 07:37:23 +00002038 CXXBaseOrMemberInitializer *PrevInit = 0;
2039 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2040 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002041 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002042
2043 // Scan forward to try to find this initializer in the idealized
2044 // initializers list.
2045 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2046 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002047 break;
John McCallbb7b6582010-04-10 07:37:23 +00002048
2049 // If we didn't find this initializer, it must be because we
2050 // scanned past it on a previous iteration. That can only
2051 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002052 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002053 Sema::SemaDiagnosticBuilder D =
2054 SemaRef.Diag(PrevInit->getSourceLocation(),
2055 diag::warn_initializer_out_of_order);
2056
Francois Pichetd583da02010-12-04 09:14:42 +00002057 if (PrevInit->isAnyMemberInitializer())
2058 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002059 else
2060 D << 1 << PrevInit->getBaseClassInfo()->getType();
2061
Francois Pichetd583da02010-12-04 09:14:42 +00002062 if (Init->isAnyMemberInitializer())
2063 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002064 else
2065 D << 1 << Init->getBaseClassInfo()->getType();
2066
2067 // Move back to the initializer's location in the ideal list.
2068 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2069 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002070 break;
John McCallbb7b6582010-04-10 07:37:23 +00002071
2072 assert(IdealIndex != NumIdealInits &&
2073 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002074 }
John McCallbb7b6582010-04-10 07:37:23 +00002075
2076 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002077 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002078}
2079
John McCall23eebd92010-04-10 09:28:51 +00002080namespace {
2081bool CheckRedundantInit(Sema &S,
2082 CXXBaseOrMemberInitializer *Init,
2083 CXXBaseOrMemberInitializer *&PrevInit) {
2084 if (!PrevInit) {
2085 PrevInit = Init;
2086 return false;
2087 }
2088
2089 if (FieldDecl *Field = Init->getMember())
2090 S.Diag(Init->getSourceLocation(),
2091 diag::err_multiple_mem_initialization)
2092 << Field->getDeclName()
2093 << Init->getSourceRange();
2094 else {
2095 Type *BaseClass = Init->getBaseClass();
2096 assert(BaseClass && "neither field nor base");
2097 S.Diag(Init->getSourceLocation(),
2098 diag::err_multiple_base_initialization)
2099 << QualType(BaseClass, 0)
2100 << Init->getSourceRange();
2101 }
2102 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2103 << 0 << PrevInit->getSourceRange();
2104
2105 return true;
2106}
2107
2108typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2109typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2110
2111bool CheckRedundantUnionInit(Sema &S,
2112 CXXBaseOrMemberInitializer *Init,
2113 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002114 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002115 RecordDecl *Parent = Field->getParent();
2116 if (!Parent->isAnonymousStructOrUnion())
2117 return false;
2118
2119 NamedDecl *Child = Field;
2120 do {
2121 if (Parent->isUnion()) {
2122 UnionEntry &En = Unions[Parent];
2123 if (En.first && En.first != Child) {
2124 S.Diag(Init->getSourceLocation(),
2125 diag::err_multiple_mem_union_initialization)
2126 << Field->getDeclName()
2127 << Init->getSourceRange();
2128 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2129 << 0 << En.second->getSourceRange();
2130 return true;
2131 } else if (!En.first) {
2132 En.first = Child;
2133 En.second = Init;
2134 }
2135 }
2136
2137 Child = Parent;
2138 Parent = cast<RecordDecl>(Parent->getDeclContext());
2139 } while (Parent->isAnonymousStructOrUnion());
2140
2141 return false;
2142}
2143}
2144
Anders Carlssone857b292010-04-02 03:37:03 +00002145/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002146void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002147 SourceLocation ColonLoc,
2148 MemInitTy **meminits, unsigned NumMemInits,
2149 bool AnyErrors) {
2150 if (!ConstructorDecl)
2151 return;
2152
2153 AdjustDeclIfTemplate(ConstructorDecl);
2154
2155 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002156 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002157
2158 if (!Constructor) {
2159 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2160 return;
2161 }
2162
2163 CXXBaseOrMemberInitializer **MemInits =
2164 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002165
2166 // Mapping for the duplicate initializers check.
2167 // For member initializers, this is keyed with a FieldDecl*.
2168 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002169 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002170
2171 // Mapping for the inconsistent anonymous-union initializers check.
2172 RedundantUnionMap MemberUnions;
2173
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002174 bool HadError = false;
2175 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002176 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002177
Abramo Bagnara341d7832010-05-26 18:09:23 +00002178 // Set the source order index.
2179 Init->setSourceOrder(i);
2180
Francois Pichetd583da02010-12-04 09:14:42 +00002181 if (Init->isAnyMemberInitializer()) {
2182 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002183 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2184 CheckRedundantUnionInit(*this, Init, MemberUnions))
2185 HadError = true;
2186 } else {
2187 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2188 if (CheckRedundantInit(*this, Init, Members[Key]))
2189 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002190 }
Anders Carlssone857b292010-04-02 03:37:03 +00002191 }
2192
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002193 if (HadError)
2194 return;
2195
Anders Carlssone857b292010-04-02 03:37:03 +00002196 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002197
2198 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002199}
2200
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002201void
John McCalla6309952010-03-16 21:39:52 +00002202Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2203 CXXRecordDecl *ClassDecl) {
2204 // Ignore dependent contexts.
2205 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002206 return;
John McCall1064d7e2010-03-16 05:22:47 +00002207
2208 // FIXME: all the access-control diagnostics are positioned on the
2209 // field/base declaration. That's probably good; that said, the
2210 // user might reasonably want to know why the destructor is being
2211 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002212
Anders Carlssondee9a302009-11-17 04:44:12 +00002213 // Non-static data members.
2214 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2215 E = ClassDecl->field_end(); I != E; ++I) {
2216 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002217 if (Field->isInvalidDecl())
2218 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002219 QualType FieldType = Context.getBaseElementType(Field->getType());
2220
2221 const RecordType* RT = FieldType->getAs<RecordType>();
2222 if (!RT)
2223 continue;
2224
2225 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2226 if (FieldClassDecl->hasTrivialDestructor())
2227 continue;
2228
Douglas Gregore71edda2010-07-01 22:47:18 +00002229 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002230 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002231 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002232 << Field->getDeclName()
2233 << FieldType);
2234
John McCalla6309952010-03-16 21:39:52 +00002235 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002236 }
2237
John McCall1064d7e2010-03-16 05:22:47 +00002238 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2239
Anders Carlssondee9a302009-11-17 04:44:12 +00002240 // Bases.
2241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2242 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002243 // Bases are always records in a well-formed non-dependent class.
2244 const RecordType *RT = Base->getType()->getAs<RecordType>();
2245
2246 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002247 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002248 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002249
2250 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002251 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002252 if (BaseClassDecl->hasTrivialDestructor())
2253 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002254
Douglas Gregore71edda2010-07-01 22:47:18 +00002255 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002256
2257 // FIXME: caret should be on the start of the class name
2258 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002259 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002260 << Base->getType()
2261 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002262
John McCalla6309952010-03-16 21:39:52 +00002263 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002264 }
2265
2266 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002267 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2268 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002269
2270 // Bases are always records in a well-formed non-dependent class.
2271 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2272
2273 // Ignore direct virtual bases.
2274 if (DirectVirtualBases.count(RT))
2275 continue;
2276
Anders Carlssondee9a302009-11-17 04:44:12 +00002277 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002278 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002279 if (BaseClassDecl->hasTrivialDestructor())
2280 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002281
Douglas Gregore71edda2010-07-01 22:47:18 +00002282 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002283 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002284 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002285 << VBase->getType());
2286
John McCalla6309952010-03-16 21:39:52 +00002287 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002288 }
2289}
2290
John McCall48871652010-08-21 09:40:31 +00002291void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002292 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002293 return;
Mike Stump11289f42009-09-09 15:08:12 +00002294
Mike Stump11289f42009-09-09 15:08:12 +00002295 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002296 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002297 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002298}
2299
Mike Stump11289f42009-09-09 15:08:12 +00002300bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002301 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002302 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002303 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002304 else
John McCall02db245d2010-08-18 09:41:07 +00002305 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002306}
2307
Anders Carlssoneabf7702009-08-27 00:13:57 +00002308bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002309 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002310 if (!getLangOptions().CPlusPlus)
2311 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002312
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002313 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002314 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002316 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002317 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002318 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002319 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002320
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002321 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002322 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002323 }
Mike Stump11289f42009-09-09 15:08:12 +00002324
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002325 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002326 if (!RT)
2327 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002328
John McCall67da35c2010-02-04 22:26:26 +00002329 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002330
John McCall02db245d2010-08-18 09:41:07 +00002331 // We can't answer whether something is abstract until it has a
2332 // definition. If it's currently being defined, we'll walk back
2333 // over all the declarations when we have a full definition.
2334 const CXXRecordDecl *Def = RD->getDefinition();
2335 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002336 return false;
2337
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002338 if (!RD->isAbstract())
2339 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002340
Anders Carlssoneabf7702009-08-27 00:13:57 +00002341 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002342 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002343
John McCall02db245d2010-08-18 09:41:07 +00002344 return true;
2345}
2346
2347void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2348 // Check if we've already emitted the list of pure virtual functions
2349 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002350 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002351 return;
Mike Stump11289f42009-09-09 15:08:12 +00002352
Douglas Gregor4165bd62010-03-23 23:47:56 +00002353 CXXFinalOverriderMap FinalOverriders;
2354 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002355
Anders Carlssona2f74f32010-06-03 01:00:02 +00002356 // Keep a set of seen pure methods so we won't diagnose the same method
2357 // more than once.
2358 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2359
Douglas Gregor4165bd62010-03-23 23:47:56 +00002360 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2361 MEnd = FinalOverriders.end();
2362 M != MEnd;
2363 ++M) {
2364 for (OverridingMethods::iterator SO = M->second.begin(),
2365 SOEnd = M->second.end();
2366 SO != SOEnd; ++SO) {
2367 // C++ [class.abstract]p4:
2368 // A class is abstract if it contains or inherits at least one
2369 // pure virtual function for which the final overrider is pure
2370 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002371
Douglas Gregor4165bd62010-03-23 23:47:56 +00002372 //
2373 if (SO->second.size() != 1)
2374 continue;
2375
2376 if (!SO->second.front().Method->isPure())
2377 continue;
2378
Anders Carlssona2f74f32010-06-03 01:00:02 +00002379 if (!SeenPureMethods.insert(SO->second.front().Method))
2380 continue;
2381
Douglas Gregor4165bd62010-03-23 23:47:56 +00002382 Diag(SO->second.front().Method->getLocation(),
2383 diag::note_pure_virtual_function)
2384 << SO->second.front().Method->getDeclName();
2385 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002386 }
2387
2388 if (!PureVirtualClassDiagSet)
2389 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2390 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002391}
2392
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002393namespace {
John McCall02db245d2010-08-18 09:41:07 +00002394struct AbstractUsageInfo {
2395 Sema &S;
2396 CXXRecordDecl *Record;
2397 CanQualType AbstractType;
2398 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002399
John McCall02db245d2010-08-18 09:41:07 +00002400 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2401 : S(S), Record(Record),
2402 AbstractType(S.Context.getCanonicalType(
2403 S.Context.getTypeDeclType(Record))),
2404 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002405
John McCall02db245d2010-08-18 09:41:07 +00002406 void DiagnoseAbstractType() {
2407 if (Invalid) return;
2408 S.DiagnoseAbstractType(Record);
2409 Invalid = true;
2410 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002411
John McCall02db245d2010-08-18 09:41:07 +00002412 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2413};
2414
2415struct CheckAbstractUsage {
2416 AbstractUsageInfo &Info;
2417 const NamedDecl *Ctx;
2418
2419 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2420 : Info(Info), Ctx(Ctx) {}
2421
2422 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2423 switch (TL.getTypeLocClass()) {
2424#define ABSTRACT_TYPELOC(CLASS, PARENT)
2425#define TYPELOC(CLASS, PARENT) \
2426 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2427#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002428 }
John McCall02db245d2010-08-18 09:41:07 +00002429 }
Mike Stump11289f42009-09-09 15:08:12 +00002430
John McCall02db245d2010-08-18 09:41:07 +00002431 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2432 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2433 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2434 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2435 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002436 }
John McCall02db245d2010-08-18 09:41:07 +00002437 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002438
John McCall02db245d2010-08-18 09:41:07 +00002439 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2440 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
John McCall02db245d2010-08-18 09:41:07 +00002443 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2444 // Visit the type parameters from a permissive context.
2445 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2446 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2447 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2448 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2449 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2450 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002451 }
John McCall02db245d2010-08-18 09:41:07 +00002452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453
John McCall02db245d2010-08-18 09:41:07 +00002454 // Visit pointee types from a permissive context.
2455#define CheckPolymorphic(Type) \
2456 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2457 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2458 }
2459 CheckPolymorphic(PointerTypeLoc)
2460 CheckPolymorphic(ReferenceTypeLoc)
2461 CheckPolymorphic(MemberPointerTypeLoc)
2462 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002463
John McCall02db245d2010-08-18 09:41:07 +00002464 /// Handle all the types we haven't given a more specific
2465 /// implementation for above.
2466 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2467 // Every other kind of type that we haven't called out already
2468 // that has an inner type is either (1) sugar or (2) contains that
2469 // inner type in some way as a subobject.
2470 if (TypeLoc Next = TL.getNextTypeLoc())
2471 return Visit(Next, Sel);
2472
2473 // If there's no inner type and we're in a permissive context,
2474 // don't diagnose.
2475 if (Sel == Sema::AbstractNone) return;
2476
2477 // Check whether the type matches the abstract type.
2478 QualType T = TL.getType();
2479 if (T->isArrayType()) {
2480 Sel = Sema::AbstractArrayType;
2481 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002482 }
John McCall02db245d2010-08-18 09:41:07 +00002483 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2484 if (CT != Info.AbstractType) return;
2485
2486 // It matched; do some magic.
2487 if (Sel == Sema::AbstractArrayType) {
2488 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2489 << T << TL.getSourceRange();
2490 } else {
2491 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2492 << Sel << T << TL.getSourceRange();
2493 }
2494 Info.DiagnoseAbstractType();
2495 }
2496};
2497
2498void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2499 Sema::AbstractDiagSelID Sel) {
2500 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2501}
2502
2503}
2504
2505/// Check for invalid uses of an abstract type in a method declaration.
2506static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2507 CXXMethodDecl *MD) {
2508 // No need to do the check on definitions, which require that
2509 // the return/param types be complete.
2510 if (MD->isThisDeclarationADefinition())
2511 return;
2512
2513 // For safety's sake, just ignore it if we don't have type source
2514 // information. This should never happen for non-implicit methods,
2515 // but...
2516 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2517 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2518}
2519
2520/// Check for invalid uses of an abstract type within a class definition.
2521static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2522 CXXRecordDecl *RD) {
2523 for (CXXRecordDecl::decl_iterator
2524 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2525 Decl *D = *I;
2526 if (D->isImplicit()) continue;
2527
2528 // Methods and method templates.
2529 if (isa<CXXMethodDecl>(D)) {
2530 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2531 } else if (isa<FunctionTemplateDecl>(D)) {
2532 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2533 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2534
2535 // Fields and static variables.
2536 } else if (isa<FieldDecl>(D)) {
2537 FieldDecl *FD = cast<FieldDecl>(D);
2538 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2539 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2540 } else if (isa<VarDecl>(D)) {
2541 VarDecl *VD = cast<VarDecl>(D);
2542 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2543 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2544
2545 // Nested classes and class templates.
2546 } else if (isa<CXXRecordDecl>(D)) {
2547 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2548 } else if (isa<ClassTemplateDecl>(D)) {
2549 CheckAbstractClassUsage(Info,
2550 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2551 }
2552 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002553}
2554
Douglas Gregorc99f1552009-12-03 18:33:45 +00002555/// \brief Perform semantic checks on a class definition that has been
2556/// completing, introducing implicitly-declared members, checking for
2557/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002558void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002559 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002560 return;
2561
John McCall02db245d2010-08-18 09:41:07 +00002562 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2563 AbstractUsageInfo Info(*this, Record);
2564 CheckAbstractClassUsage(Info, Record);
2565 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002566
2567 // If this is not an aggregate type and has no user-declared constructor,
2568 // complain about any non-static data members of reference or const scalar
2569 // type, since they will never get initializers.
2570 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2571 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2572 bool Complained = false;
2573 for (RecordDecl::field_iterator F = Record->field_begin(),
2574 FEnd = Record->field_end();
2575 F != FEnd; ++F) {
2576 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002577 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002578 if (!Complained) {
2579 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2580 << Record->getTagKind() << Record;
2581 Complained = true;
2582 }
2583
2584 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2585 << F->getType()->isReferenceType()
2586 << F->getDeclName();
2587 }
2588 }
2589 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002590
2591 if (Record->isDynamicClass())
2592 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002593
2594 if (Record->getIdentifier()) {
2595 // C++ [class.mem]p13:
2596 // If T is the name of a class, then each of the following shall have a
2597 // name different from T:
2598 // - every member of every anonymous union that is a member of class T.
2599 //
2600 // C++ [class.mem]p14:
2601 // In addition, if class T has a user-declared constructor (12.1), every
2602 // non-static data member of class T shall have a name different from T.
2603 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002604 R.first != R.second; ++R.first) {
2605 NamedDecl *D = *R.first;
2606 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2607 isa<IndirectFieldDecl>(D)) {
2608 Diag(D->getLocation(), diag::err_member_name_of_class)
2609 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002610 break;
2611 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002612 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002613 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002614}
2615
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002616void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002617 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002618 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002619 SourceLocation RBrac,
2620 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002621 if (!TagDecl)
2622 return;
Mike Stump11289f42009-09-09 15:08:12 +00002623
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002624 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002625
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002626 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002627 // strict aliasing violation!
2628 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002629 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002630
Douglas Gregor0be31a22010-07-02 17:43:08 +00002631 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002632 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002633}
2634
Douglas Gregor95755162010-07-01 05:10:53 +00002635namespace {
2636 /// \brief Helper class that collects exception specifications for
2637 /// implicitly-declared special member functions.
2638 class ImplicitExceptionSpecification {
2639 ASTContext &Context;
2640 bool AllowsAllExceptions;
2641 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2642 llvm::SmallVector<QualType, 4> Exceptions;
2643
2644 public:
2645 explicit ImplicitExceptionSpecification(ASTContext &Context)
2646 : Context(Context), AllowsAllExceptions(false) { }
2647
2648 /// \brief Whether the special member function should have any
2649 /// exception specification at all.
2650 bool hasExceptionSpecification() const {
2651 return !AllowsAllExceptions;
2652 }
2653
2654 /// \brief Whether the special member function should have a
2655 /// throw(...) exception specification (a Microsoft extension).
2656 bool hasAnyExceptionSpecification() const {
2657 return false;
2658 }
2659
2660 /// \brief The number of exceptions in the exception specification.
2661 unsigned size() const { return Exceptions.size(); }
2662
2663 /// \brief The set of exceptions in the exception specification.
2664 const QualType *data() const { return Exceptions.data(); }
2665
2666 /// \brief Note that
2667 void CalledDecl(CXXMethodDecl *Method) {
2668 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002669 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002670 return;
2671
2672 const FunctionProtoType *Proto
2673 = Method->getType()->getAs<FunctionProtoType>();
2674
2675 // If this function can throw any exceptions, make a note of that.
2676 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2677 AllowsAllExceptions = true;
2678 ExceptionsSeen.clear();
2679 Exceptions.clear();
2680 return;
2681 }
2682
2683 // Record the exceptions in this function's exception specification.
2684 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2685 EEnd = Proto->exception_end();
2686 E != EEnd; ++E)
2687 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2688 Exceptions.push_back(*E);
2689 }
2690 };
2691}
2692
2693
Douglas Gregor05379422008-11-03 17:51:48 +00002694/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2695/// special functions, such as the default constructor, copy
2696/// constructor, or destructor, to the given C++ class (C++
2697/// [special]p1). This routine can only be executed just before the
2698/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002699void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002700 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002701 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002702
Douglas Gregor54be3392010-07-01 17:57:27 +00002703 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002704 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002705
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002706 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2707 ++ASTContext::NumImplicitCopyAssignmentOperators;
2708
2709 // If we have a dynamic class, then the copy assignment operator may be
2710 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2711 // it shows up in the right place in the vtable and that we diagnose
2712 // problems with the implicit exception specification.
2713 if (ClassDecl->isDynamicClass())
2714 DeclareImplicitCopyAssignment(ClassDecl);
2715 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002716
Douglas Gregor7454c562010-07-02 20:37:36 +00002717 if (!ClassDecl->hasUserDeclaredDestructor()) {
2718 ++ASTContext::NumImplicitDestructors;
2719
2720 // If we have a dynamic class, then the destructor may be virtual, so we
2721 // have to declare the destructor immediately. This ensures that, e.g., it
2722 // shows up in the right place in the vtable and that we diagnose problems
2723 // with the implicit exception specification.
2724 if (ClassDecl->isDynamicClass())
2725 DeclareImplicitDestructor(ClassDecl);
2726 }
Douglas Gregor05379422008-11-03 17:51:48 +00002727}
2728
John McCall48871652010-08-21 09:40:31 +00002729void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002730 if (!D)
2731 return;
2732
2733 TemplateParameterList *Params = 0;
2734 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2735 Params = Template->getTemplateParameters();
2736 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2737 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2738 Params = PartialSpec->getTemplateParameters();
2739 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002740 return;
2741
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002742 for (TemplateParameterList::iterator Param = Params->begin(),
2743 ParamEnd = Params->end();
2744 Param != ParamEnd; ++Param) {
2745 NamedDecl *Named = cast<NamedDecl>(*Param);
2746 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002747 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002748 IdResolver.AddDecl(Named);
2749 }
2750 }
2751}
2752
John McCall48871652010-08-21 09:40:31 +00002753void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002754 if (!RecordD) return;
2755 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002756 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002757 PushDeclContext(S, Record);
2758}
2759
John McCall48871652010-08-21 09:40:31 +00002760void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002761 if (!RecordD) return;
2762 PopDeclContext();
2763}
2764
Douglas Gregor4d87df52008-12-16 21:30:33 +00002765/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2766/// parsing a top-level (non-nested) C++ class, and we are now
2767/// parsing those parts of the given Method declaration that could
2768/// not be parsed earlier (C++ [class.mem]p2), such as default
2769/// arguments. This action should enter the scope of the given
2770/// Method declaration as if we had just parsed the qualified method
2771/// name. However, it should not bring the parameters into scope;
2772/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002773void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002774}
2775
2776/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2777/// C++ method declaration. We're (re-)introducing the given
2778/// function parameter into scope for use in parsing later parts of
2779/// the method declaration. For example, we could see an
2780/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002781void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002782 if (!ParamD)
2783 return;
Mike Stump11289f42009-09-09 15:08:12 +00002784
John McCall48871652010-08-21 09:40:31 +00002785 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002786
2787 // If this parameter has an unparsed default argument, clear it out
2788 // to make way for the parsed default argument.
2789 if (Param->hasUnparsedDefaultArg())
2790 Param->setDefaultArg(0);
2791
John McCall48871652010-08-21 09:40:31 +00002792 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002793 if (Param->getDeclName())
2794 IdResolver.AddDecl(Param);
2795}
2796
2797/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2798/// processing the delayed method declaration for Method. The method
2799/// declaration is now considered finished. There may be a separate
2800/// ActOnStartOfFunctionDef action later (not necessarily
2801/// immediately!) for this method, if it was also defined inside the
2802/// class body.
John McCall48871652010-08-21 09:40:31 +00002803void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002804 if (!MethodD)
2805 return;
Mike Stump11289f42009-09-09 15:08:12 +00002806
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002807 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002808
John McCall48871652010-08-21 09:40:31 +00002809 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002810
2811 // Now that we have our default arguments, check the constructor
2812 // again. It could produce additional diagnostics or affect whether
2813 // the class has implicitly-declared destructors, among other
2814 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002815 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2816 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002817
2818 // Check the default arguments, which we may have added.
2819 if (!Method->isInvalidDecl())
2820 CheckCXXDefaultArguments(Method);
2821}
2822
Douglas Gregor831c93f2008-11-05 20:51:48 +00002823/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002824/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002825/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002826/// emit diagnostics and set the invalid bit to true. In any case, the type
2827/// will be updated to reflect a well-formed type for the constructor and
2828/// returned.
2829QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002830 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002831 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002832
2833 // C++ [class.ctor]p3:
2834 // A constructor shall not be virtual (10.3) or static (9.4). A
2835 // constructor can be invoked for a const, volatile or const
2836 // volatile object. A constructor shall not be declared const,
2837 // volatile, or const volatile (9.3.2).
2838 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002839 if (!D.isInvalidType())
2840 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2841 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2842 << SourceRange(D.getIdentifierLoc());
2843 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002844 }
John McCall8e7d6562010-08-26 03:08:43 +00002845 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002846 if (!D.isInvalidType())
2847 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2848 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2849 << SourceRange(D.getIdentifierLoc());
2850 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002851 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002852 }
Mike Stump11289f42009-09-09 15:08:12 +00002853
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002854 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002855 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002856 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002857 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2858 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002859 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002860 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2861 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002862 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002863 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2864 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002865 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002866 }
Mike Stump11289f42009-09-09 15:08:12 +00002867
Douglas Gregor831c93f2008-11-05 20:51:48 +00002868 // Rebuild the function type "R" without any type qualifiers (in
2869 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002870 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002871 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002872 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2873 return R;
2874
2875 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2876 EPI.TypeQuals = 0;
2877
Chris Lattner38378bf2009-04-25 08:28:21 +00002878 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002879 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002880}
2881
Douglas Gregor4d87df52008-12-16 21:30:33 +00002882/// CheckConstructor - Checks a fully-formed constructor for
2883/// well-formedness, issuing any diagnostics required. Returns true if
2884/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002885void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002886 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002887 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2888 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002889 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002890
2891 // C++ [class.copy]p3:
2892 // A declaration of a constructor for a class X is ill-formed if
2893 // its first parameter is of type (optionally cv-qualified) X and
2894 // either there are no other parameters or else all other
2895 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002896 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002897 ((Constructor->getNumParams() == 1) ||
2898 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002899 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2900 Constructor->getTemplateSpecializationKind()
2901 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002902 QualType ParamType = Constructor->getParamDecl(0)->getType();
2903 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2904 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002905 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002906 const char *ConstRef
2907 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2908 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002909 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002910 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002911
2912 // FIXME: Rather that making the constructor invalid, we should endeavor
2913 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002914 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002915 }
2916 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002917}
2918
John McCalldeb646e2010-08-04 01:04:25 +00002919/// CheckDestructor - Checks a fully-formed destructor definition for
2920/// well-formedness, issuing any diagnostics required. Returns true
2921/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002922bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002923 CXXRecordDecl *RD = Destructor->getParent();
2924
2925 if (Destructor->isVirtual()) {
2926 SourceLocation Loc;
2927
2928 if (!Destructor->isImplicit())
2929 Loc = Destructor->getLocation();
2930 else
2931 Loc = RD->getLocation();
2932
2933 // If we have a virtual destructor, look up the deallocation function
2934 FunctionDecl *OperatorDelete = 0;
2935 DeclarationName Name =
2936 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002937 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002938 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002939
2940 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002941
2942 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002943 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002944
2945 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002946}
2947
Mike Stump11289f42009-09-09 15:08:12 +00002948static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002949FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2950 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2951 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002952 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002953}
2954
Douglas Gregor831c93f2008-11-05 20:51:48 +00002955/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2956/// the well-formednes of the destructor declarator @p D with type @p
2957/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002958/// emit diagnostics and set the declarator to invalid. Even if this happens,
2959/// will be updated to reflect a well-formed type for the destructor and
2960/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002961QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002962 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002963 // C++ [class.dtor]p1:
2964 // [...] A typedef-name that names a class is a class-name
2965 // (7.1.3); however, a typedef-name that names a class shall not
2966 // be used as the identifier in the declarator for a destructor
2967 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002968 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002969 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002970 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002971 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002972
2973 // C++ [class.dtor]p2:
2974 // A destructor is used to destroy objects of its class type. A
2975 // destructor takes no parameters, and no return type can be
2976 // specified for it (not even void). The address of a destructor
2977 // shall not be taken. A destructor shall not be static. A
2978 // destructor can be invoked for a const, volatile or const
2979 // volatile object. A destructor shall not be declared const,
2980 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002981 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002982 if (!D.isInvalidType())
2983 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2984 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002985 << SourceRange(D.getIdentifierLoc())
2986 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2987
John McCall8e7d6562010-08-26 03:08:43 +00002988 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002989 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002990 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002991 // Destructors don't have return types, but the parser will
2992 // happily parse something like:
2993 //
2994 // class X {
2995 // float ~X();
2996 // };
2997 //
2998 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002999 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3000 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3001 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003004 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003005 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003006 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003007 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3008 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003009 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003010 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3011 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003012 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003013 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3014 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003015 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003016 }
3017
3018 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003019 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003020 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3021
3022 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003023 FTI.freeArgs();
3024 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003025 }
3026
Mike Stump11289f42009-09-09 15:08:12 +00003027 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003028 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003029 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003030 D.setInvalidType();
3031 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003032
3033 // Rebuild the function type "R" without any type qualifiers or
3034 // parameters (in case any of the errors above fired) and with
3035 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003036 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003037 if (!D.isInvalidType())
3038 return R;
3039
Douglas Gregor95755162010-07-01 05:10:53 +00003040 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003041 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3042 EPI.Variadic = false;
3043 EPI.TypeQuals = 0;
3044 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003045}
3046
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003047/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3048/// well-formednes of the conversion function declarator @p D with
3049/// type @p R. If there are any errors in the declarator, this routine
3050/// will emit diagnostics and return true. Otherwise, it will return
3051/// false. Either way, the type @p R will be updated to reflect a
3052/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003053void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003054 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003055 // C++ [class.conv.fct]p1:
3056 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003057 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003058 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003059 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003060 if (!D.isInvalidType())
3061 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3062 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3063 << SourceRange(D.getIdentifierLoc());
3064 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003065 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003066 }
John McCall212fa2e2010-04-13 00:04:31 +00003067
3068 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3069
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003070 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003071 // Conversion functions don't have return types, but the parser will
3072 // happily parse something like:
3073 //
3074 // class X {
3075 // float operator bool();
3076 // };
3077 //
3078 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003079 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3080 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3081 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003082 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003083 }
3084
John McCall212fa2e2010-04-13 00:04:31 +00003085 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3086
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003087 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003088 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003089 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3090
3091 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003092 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003093 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003094 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003095 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003096 D.setInvalidType();
3097 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003098
John McCall212fa2e2010-04-13 00:04:31 +00003099 // Diagnose "&operator bool()" and other such nonsense. This
3100 // is actually a gcc extension which we don't support.
3101 if (Proto->getResultType() != ConvType) {
3102 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3103 << Proto->getResultType();
3104 D.setInvalidType();
3105 ConvType = Proto->getResultType();
3106 }
3107
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003108 // C++ [class.conv.fct]p4:
3109 // The conversion-type-id shall not represent a function type nor
3110 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003111 if (ConvType->isArrayType()) {
3112 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3113 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003114 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003115 } else if (ConvType->isFunctionType()) {
3116 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3117 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003118 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003119 }
3120
3121 // Rebuild the function type "R" without any parameters (in case any
3122 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003123 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003124 if (D.isInvalidType())
3125 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003126
Douglas Gregor5fb53972009-01-14 15:45:31 +00003127 // C++0x explicit conversion operators.
3128 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003129 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003130 diag::warn_explicit_conversion_functions)
3131 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003132}
3133
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003134/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3135/// the declaration of the given C++ conversion function. This routine
3136/// is responsible for recording the conversion function in the C++
3137/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003138Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003139 assert(Conversion && "Expected to receive a conversion function declaration");
3140
Douglas Gregor4287b372008-12-12 08:25:50 +00003141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003142
3143 // Make sure we aren't redeclaring the conversion function.
3144 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003145
3146 // C++ [class.conv.fct]p1:
3147 // [...] A conversion function is never used to convert a
3148 // (possibly cv-qualified) object to the (possibly cv-qualified)
3149 // same object type (or a reference to it), to a (possibly
3150 // cv-qualified) base class of that type (or a reference to it),
3151 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003152 // FIXME: Suppress this warning if the conversion function ends up being a
3153 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003154 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003155 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003156 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003157 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003158 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3159 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003160 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003161 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003162 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3163 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003164 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003165 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003166 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003167 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003168 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003169 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003170 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003171 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003172 }
3173
Douglas Gregor457104e2010-09-29 04:25:11 +00003174 if (FunctionTemplateDecl *ConversionTemplate
3175 = Conversion->getDescribedFunctionTemplate())
3176 return ConversionTemplate;
3177
John McCall48871652010-08-21 09:40:31 +00003178 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003179}
3180
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003181//===----------------------------------------------------------------------===//
3182// Namespace Handling
3183//===----------------------------------------------------------------------===//
3184
John McCallb1be5232010-08-26 09:15:37 +00003185
3186
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003187/// ActOnStartNamespaceDef - This is called at the start of a namespace
3188/// definition.
John McCall48871652010-08-21 09:40:31 +00003189Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003190 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003191 SourceLocation IdentLoc,
3192 IdentifierInfo *II,
3193 SourceLocation LBrace,
3194 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003195 // anonymous namespace starts at its left brace
3196 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3197 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003198 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003199 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003200
3201 Scope *DeclRegionScope = NamespcScope->getParent();
3202
Anders Carlssona7bcade2010-02-07 01:09:23 +00003203 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3204
John McCall2faf32c2010-12-10 02:59:44 +00003205 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3206 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003207
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003208 if (II) {
3209 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003210 // The identifier in an original-namespace-definition shall not
3211 // have been previously defined in the declarative region in
3212 // which the original-namespace-definition appears. The
3213 // identifier in an original-namespace-definition is the name of
3214 // the namespace. Subsequently in that declarative region, it is
3215 // treated as an original-namespace-name.
3216 //
3217 // Since namespace names are unique in their scope, and we don't
3218 // look through using directives, just
3219 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3220 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Douglas Gregor91f84212008-12-11 16:49:14 +00003222 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3223 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003224 if (Namespc->isInline() != OrigNS->isInline()) {
3225 // inline-ness must match
3226 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3227 << Namespc->isInline();
3228 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3229 Namespc->setInvalidDecl();
3230 // Recover by ignoring the new namespace's inline status.
3231 Namespc->setInline(OrigNS->isInline());
3232 }
3233
Douglas Gregor91f84212008-12-11 16:49:14 +00003234 // Attach this namespace decl to the chain of extended namespace
3235 // definitions.
3236 OrigNS->setNextNamespace(Namespc);
3237 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003238
Mike Stump11289f42009-09-09 15:08:12 +00003239 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003240 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003241 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003242 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003243 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003244 } else if (PrevDecl) {
3245 // This is an invalid name redefinition.
3246 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3247 << Namespc->getDeclName();
3248 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3249 Namespc->setInvalidDecl();
3250 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003251 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003252 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003253 // This is the first "real" definition of the namespace "std", so update
3254 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003255 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003256 // We had already defined a dummy namespace "std". Link this new
3257 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003258 StdNS->setNextNamespace(Namespc);
3259 StdNS->setLocation(IdentLoc);
3260 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003261 }
3262
3263 // Make our StdNamespace cache point at the first real definition of the
3264 // "std" namespace.
3265 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003266 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003267
3268 PushOnScopeChains(Namespc, DeclRegionScope);
3269 } else {
John McCall4fa53422009-10-01 00:25:31 +00003270 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003271 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003272
3273 // Link the anonymous namespace into its parent.
3274 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003275 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003276 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3277 PrevDecl = TU->getAnonymousNamespace();
3278 TU->setAnonymousNamespace(Namespc);
3279 } else {
3280 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3281 PrevDecl = ND->getAnonymousNamespace();
3282 ND->setAnonymousNamespace(Namespc);
3283 }
3284
3285 // Link the anonymous namespace with its previous declaration.
3286 if (PrevDecl) {
3287 assert(PrevDecl->isAnonymousNamespace());
3288 assert(!PrevDecl->getNextNamespace());
3289 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3290 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003291
3292 if (Namespc->isInline() != PrevDecl->isInline()) {
3293 // inline-ness must match
3294 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3295 << Namespc->isInline();
3296 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3297 Namespc->setInvalidDecl();
3298 // Recover by ignoring the new namespace's inline status.
3299 Namespc->setInline(PrevDecl->isInline());
3300 }
John McCall0db42252009-12-16 02:06:49 +00003301 }
John McCall4fa53422009-10-01 00:25:31 +00003302
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003303 CurContext->addDecl(Namespc);
3304
John McCall4fa53422009-10-01 00:25:31 +00003305 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3306 // behaves as if it were replaced by
3307 // namespace unique { /* empty body */ }
3308 // using namespace unique;
3309 // namespace unique { namespace-body }
3310 // where all occurrences of 'unique' in a translation unit are
3311 // replaced by the same identifier and this identifier differs
3312 // from all other identifiers in the entire program.
3313
3314 // We just create the namespace with an empty name and then add an
3315 // implicit using declaration, just like the standard suggests.
3316 //
3317 // CodeGen enforces the "universally unique" aspect by giving all
3318 // declarations semantically contained within an anonymous
3319 // namespace internal linkage.
3320
John McCall0db42252009-12-16 02:06:49 +00003321 if (!PrevDecl) {
3322 UsingDirectiveDecl* UD
3323 = UsingDirectiveDecl::Create(Context, CurContext,
3324 /* 'using' */ LBrace,
3325 /* 'namespace' */ SourceLocation(),
3326 /* qualifier */ SourceRange(),
3327 /* NNS */ NULL,
3328 /* identifier */ SourceLocation(),
3329 Namespc,
3330 /* Ancestor */ CurContext);
3331 UD->setImplicit();
3332 CurContext->addDecl(UD);
3333 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003334 }
3335
3336 // Although we could have an invalid decl (i.e. the namespace name is a
3337 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003338 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3339 // for the namespace has the declarations that showed up in that particular
3340 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003341 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003342 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003343}
3344
Sebastian Redla6602e92009-11-23 15:34:23 +00003345/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3346/// is a namespace alias, returns the namespace it points to.
3347static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3348 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3349 return AD->getNamespace();
3350 return dyn_cast_or_null<NamespaceDecl>(D);
3351}
3352
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003353/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3354/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003355void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003356 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3357 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3358 Namespc->setRBracLoc(RBrace);
3359 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003360 if (Namespc->hasAttr<VisibilityAttr>())
3361 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003362}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003363
John McCall28a0cf72010-08-25 07:42:41 +00003364CXXRecordDecl *Sema::getStdBadAlloc() const {
3365 return cast_or_null<CXXRecordDecl>(
3366 StdBadAlloc.get(Context.getExternalSource()));
3367}
3368
3369NamespaceDecl *Sema::getStdNamespace() const {
3370 return cast_or_null<NamespaceDecl>(
3371 StdNamespace.get(Context.getExternalSource()));
3372}
3373
Douglas Gregorcdf87022010-06-29 17:53:46 +00003374/// \brief Retrieve the special "std" namespace, which may require us to
3375/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003376NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003377 if (!StdNamespace) {
3378 // The "std" namespace has not yet been defined, so build one implicitly.
3379 StdNamespace = NamespaceDecl::Create(Context,
3380 Context.getTranslationUnitDecl(),
3381 SourceLocation(),
3382 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003383 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003384 }
3385
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003386 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003387}
3388
John McCall48871652010-08-21 09:40:31 +00003389Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003390 SourceLocation UsingLoc,
3391 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003392 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003393 SourceLocation IdentLoc,
3394 IdentifierInfo *NamespcName,
3395 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003396 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3397 assert(NamespcName && "Invalid NamespcName.");
3398 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003399
3400 // This can only happen along a recovery path.
3401 while (S->getFlags() & Scope::TemplateParamScope)
3402 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003403 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003404
Douglas Gregor889ceb72009-02-03 19:21:40 +00003405 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003406 NestedNameSpecifier *Qualifier = 0;
3407 if (SS.isSet())
3408 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3409
Douglas Gregor34074322009-01-14 22:20:51 +00003410 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003411 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3412 LookupParsedName(R, S, &SS);
3413 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003414 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003415
Douglas Gregorcdf87022010-06-29 17:53:46 +00003416 if (R.empty()) {
3417 // Allow "using namespace std;" or "using namespace ::std;" even if
3418 // "std" hasn't been defined yet, for GCC compatibility.
3419 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3420 NamespcName->isStr("std")) {
3421 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003422 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003423 R.resolveKind();
3424 }
3425 // Otherwise, attempt typo correction.
3426 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3427 CTC_NoKeywords, 0)) {
3428 if (R.getAsSingle<NamespaceDecl>() ||
3429 R.getAsSingle<NamespaceAliasDecl>()) {
3430 if (DeclContext *DC = computeDeclContext(SS, false))
3431 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3432 << NamespcName << DC << Corrected << SS.getRange()
3433 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3434 else
3435 Diag(IdentLoc, diag::err_using_directive_suggest)
3436 << NamespcName << Corrected
3437 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3438 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3439 << Corrected;
3440
3441 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003442 } else {
3443 R.clear();
3444 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003445 }
3446 }
3447 }
3448
John McCall9f3059a2009-10-09 21:13:30 +00003449 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003450 NamedDecl *Named = R.getFoundDecl();
3451 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3452 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003453 // C++ [namespace.udir]p1:
3454 // A using-directive specifies that the names in the nominated
3455 // namespace can be used in the scope in which the
3456 // using-directive appears after the using-directive. During
3457 // unqualified name lookup (3.4.1), the names appear as if they
3458 // were declared in the nearest enclosing namespace which
3459 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003460 // namespace. [Note: in this context, "contains" means "contains
3461 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003462
3463 // Find enclosing context containing both using-directive and
3464 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003465 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003466 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3467 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3468 CommonAncestor = CommonAncestor->getParent();
3469
Sebastian Redla6602e92009-11-23 15:34:23 +00003470 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003471 SS.getRange(),
3472 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003473 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003474 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003475 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003476 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003477 }
3478
Douglas Gregor889ceb72009-02-03 19:21:40 +00003479 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003480 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003481}
3482
3483void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3484 // If scope has associated entity, then using directive is at namespace
3485 // or translation unit scope. We add UsingDirectiveDecls, into
3486 // it's lookup structure.
3487 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003488 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003489 else
3490 // Otherwise it is block-sope. using-directives will affect lookup
3491 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003492 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003493}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003494
Douglas Gregorfec52632009-06-20 00:51:54 +00003495
John McCall48871652010-08-21 09:40:31 +00003496Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003497 AccessSpecifier AS,
3498 bool HasUsingKeyword,
3499 SourceLocation UsingLoc,
3500 CXXScopeSpec &SS,
3501 UnqualifiedId &Name,
3502 AttributeList *AttrList,
3503 bool IsTypeName,
3504 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003505 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003506
Douglas Gregor220f4272009-11-04 16:30:06 +00003507 switch (Name.getKind()) {
3508 case UnqualifiedId::IK_Identifier:
3509 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003510 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003511 case UnqualifiedId::IK_ConversionFunctionId:
3512 break;
3513
3514 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003515 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003516 // C++0x inherited constructors.
3517 if (getLangOptions().CPlusPlus0x) break;
3518
Douglas Gregor220f4272009-11-04 16:30:06 +00003519 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3520 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003521 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003522
3523 case UnqualifiedId::IK_DestructorName:
3524 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3525 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003526 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003527
3528 case UnqualifiedId::IK_TemplateId:
3529 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3530 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003531 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003532 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003533
3534 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3535 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003536 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003537 return 0;
John McCall3969e302009-12-08 07:46:18 +00003538
John McCalla0097262009-12-11 02:10:03 +00003539 // Warn about using declarations.
3540 // TODO: store that the declaration was written without 'using' and
3541 // talk about access decls instead of using decls in the
3542 // diagnostics.
3543 if (!HasUsingKeyword) {
3544 UsingLoc = Name.getSourceRange().getBegin();
3545
3546 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003547 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003548 }
3549
John McCall3f746822009-11-17 05:59:44 +00003550 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003551 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003552 /* IsInstantiation */ false,
3553 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003554 if (UD)
3555 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003556
John McCall48871652010-08-21 09:40:31 +00003557 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003558}
3559
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003560/// \brief Determine whether a using declaration considers the given
3561/// declarations as "equivalent", e.g., if they are redeclarations of
3562/// the same entity or are both typedefs of the same type.
3563static bool
3564IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3565 bool &SuppressRedeclaration) {
3566 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3567 SuppressRedeclaration = false;
3568 return true;
3569 }
3570
3571 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3572 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3573 SuppressRedeclaration = true;
3574 return Context.hasSameType(TD1->getUnderlyingType(),
3575 TD2->getUnderlyingType());
3576 }
3577
3578 return false;
3579}
3580
3581
John McCall84d87672009-12-10 09:41:52 +00003582/// Determines whether to create a using shadow decl for a particular
3583/// decl, given the set of decls existing prior to this using lookup.
3584bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3585 const LookupResult &Previous) {
3586 // Diagnose finding a decl which is not from a base class of the
3587 // current class. We do this now because there are cases where this
3588 // function will silently decide not to build a shadow decl, which
3589 // will pre-empt further diagnostics.
3590 //
3591 // We don't need to do this in C++0x because we do the check once on
3592 // the qualifier.
3593 //
3594 // FIXME: diagnose the following if we care enough:
3595 // struct A { int foo; };
3596 // struct B : A { using A::foo; };
3597 // template <class T> struct C : A {};
3598 // template <class T> struct D : C<T> { using B::foo; } // <---
3599 // This is invalid (during instantiation) in C++03 because B::foo
3600 // resolves to the using decl in B, which is not a base class of D<T>.
3601 // We can't diagnose it immediately because C<T> is an unknown
3602 // specialization. The UsingShadowDecl in D<T> then points directly
3603 // to A::foo, which will look well-formed when we instantiate.
3604 // The right solution is to not collapse the shadow-decl chain.
3605 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3606 DeclContext *OrigDC = Orig->getDeclContext();
3607
3608 // Handle enums and anonymous structs.
3609 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3610 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3611 while (OrigRec->isAnonymousStructOrUnion())
3612 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3613
3614 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3615 if (OrigDC == CurContext) {
3616 Diag(Using->getLocation(),
3617 diag::err_using_decl_nested_name_specifier_is_current_class)
3618 << Using->getNestedNameRange();
3619 Diag(Orig->getLocation(), diag::note_using_decl_target);
3620 return true;
3621 }
3622
3623 Diag(Using->getNestedNameRange().getBegin(),
3624 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3625 << Using->getTargetNestedNameDecl()
3626 << cast<CXXRecordDecl>(CurContext)
3627 << Using->getNestedNameRange();
3628 Diag(Orig->getLocation(), diag::note_using_decl_target);
3629 return true;
3630 }
3631 }
3632
3633 if (Previous.empty()) return false;
3634
3635 NamedDecl *Target = Orig;
3636 if (isa<UsingShadowDecl>(Target))
3637 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3638
John McCalla17e83e2009-12-11 02:33:26 +00003639 // If the target happens to be one of the previous declarations, we
3640 // don't have a conflict.
3641 //
3642 // FIXME: but we might be increasing its access, in which case we
3643 // should redeclare it.
3644 NamedDecl *NonTag = 0, *Tag = 0;
3645 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3646 I != E; ++I) {
3647 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003648 bool Result;
3649 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3650 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003651
3652 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3653 }
3654
John McCall84d87672009-12-10 09:41:52 +00003655 if (Target->isFunctionOrFunctionTemplate()) {
3656 FunctionDecl *FD;
3657 if (isa<FunctionTemplateDecl>(Target))
3658 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3659 else
3660 FD = cast<FunctionDecl>(Target);
3661
3662 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003663 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003664 case Ovl_Overload:
3665 return false;
3666
3667 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003668 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003669 break;
3670
3671 // We found a decl with the exact signature.
3672 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003673 // If we're in a record, we want to hide the target, so we
3674 // return true (without a diagnostic) to tell the caller not to
3675 // build a shadow decl.
3676 if (CurContext->isRecord())
3677 return true;
3678
3679 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003680 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003681 break;
3682 }
3683
3684 Diag(Target->getLocation(), diag::note_using_decl_target);
3685 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3686 return true;
3687 }
3688
3689 // Target is not a function.
3690
John McCall84d87672009-12-10 09:41:52 +00003691 if (isa<TagDecl>(Target)) {
3692 // No conflict between a tag and a non-tag.
3693 if (!Tag) return false;
3694
John McCalle29c5cd2009-12-10 19:51:03 +00003695 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003696 Diag(Target->getLocation(), diag::note_using_decl_target);
3697 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3698 return true;
3699 }
3700
3701 // No conflict between a tag and a non-tag.
3702 if (!NonTag) return false;
3703
John McCalle29c5cd2009-12-10 19:51:03 +00003704 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003705 Diag(Target->getLocation(), diag::note_using_decl_target);
3706 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3707 return true;
3708}
3709
John McCall3f746822009-11-17 05:59:44 +00003710/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003711UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003712 UsingDecl *UD,
3713 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003714
3715 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003716 NamedDecl *Target = Orig;
3717 if (isa<UsingShadowDecl>(Target)) {
3718 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3719 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003720 }
3721
3722 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003723 = UsingShadowDecl::Create(Context, CurContext,
3724 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003725 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003726
3727 Shadow->setAccess(UD->getAccess());
3728 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3729 Shadow->setInvalidDecl();
3730
John McCall3f746822009-11-17 05:59:44 +00003731 if (S)
John McCall3969e302009-12-08 07:46:18 +00003732 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003733 else
John McCall3969e302009-12-08 07:46:18 +00003734 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003735
John McCall3969e302009-12-08 07:46:18 +00003736
John McCall84d87672009-12-10 09:41:52 +00003737 return Shadow;
3738}
John McCall3969e302009-12-08 07:46:18 +00003739
John McCall84d87672009-12-10 09:41:52 +00003740/// Hides a using shadow declaration. This is required by the current
3741/// using-decl implementation when a resolvable using declaration in a
3742/// class is followed by a declaration which would hide or override
3743/// one or more of the using decl's targets; for example:
3744///
3745/// struct Base { void foo(int); };
3746/// struct Derived : Base {
3747/// using Base::foo;
3748/// void foo(int);
3749/// };
3750///
3751/// The governing language is C++03 [namespace.udecl]p12:
3752///
3753/// When a using-declaration brings names from a base class into a
3754/// derived class scope, member functions in the derived class
3755/// override and/or hide member functions with the same name and
3756/// parameter types in a base class (rather than conflicting).
3757///
3758/// There are two ways to implement this:
3759/// (1) optimistically create shadow decls when they're not hidden
3760/// by existing declarations, or
3761/// (2) don't create any shadow decls (or at least don't make them
3762/// visible) until we've fully parsed/instantiated the class.
3763/// The problem with (1) is that we might have to retroactively remove
3764/// a shadow decl, which requires several O(n) operations because the
3765/// decl structures are (very reasonably) not designed for removal.
3766/// (2) avoids this but is very fiddly and phase-dependent.
3767void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003768 if (Shadow->getDeclName().getNameKind() ==
3769 DeclarationName::CXXConversionFunctionName)
3770 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3771
John McCall84d87672009-12-10 09:41:52 +00003772 // Remove it from the DeclContext...
3773 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003774
John McCall84d87672009-12-10 09:41:52 +00003775 // ...and the scope, if applicable...
3776 if (S) {
John McCall48871652010-08-21 09:40:31 +00003777 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003778 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003779 }
3780
John McCall84d87672009-12-10 09:41:52 +00003781 // ...and the using decl.
3782 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3783
3784 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003785 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003786}
3787
John McCalle61f2ba2009-11-18 02:36:19 +00003788/// Builds a using declaration.
3789///
3790/// \param IsInstantiation - Whether this call arises from an
3791/// instantiation of an unresolved using declaration. We treat
3792/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003793NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3794 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003795 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003796 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003797 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003798 bool IsInstantiation,
3799 bool IsTypeName,
3800 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003801 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003802 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003803 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003804
Anders Carlssonf038fc22009-08-28 05:49:21 +00003805 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003806
Anders Carlsson59140b32009-08-28 03:16:11 +00003807 if (SS.isEmpty()) {
3808 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003809 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003810 }
Mike Stump11289f42009-09-09 15:08:12 +00003811
John McCall84d87672009-12-10 09:41:52 +00003812 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003813 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003814 ForRedeclaration);
3815 Previous.setHideTags(false);
3816 if (S) {
3817 LookupName(Previous, S);
3818
3819 // It is really dumb that we have to do this.
3820 LookupResult::Filter F = Previous.makeFilter();
3821 while (F.hasNext()) {
3822 NamedDecl *D = F.next();
3823 if (!isDeclInScope(D, CurContext, S))
3824 F.erase();
3825 }
3826 F.done();
3827 } else {
3828 assert(IsInstantiation && "no scope in non-instantiation");
3829 assert(CurContext->isRecord() && "scope not record in instantiation");
3830 LookupQualifiedName(Previous, CurContext);
3831 }
3832
Mike Stump11289f42009-09-09 15:08:12 +00003833 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003834 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3835
John McCall84d87672009-12-10 09:41:52 +00003836 // Check for invalid redeclarations.
3837 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3838 return 0;
3839
3840 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003841 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3842 return 0;
3843
John McCall84c16cf2009-11-12 03:15:40 +00003844 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003845 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003846 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003847 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003848 // FIXME: not all declaration name kinds are legal here
3849 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3850 UsingLoc, TypenameLoc,
3851 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003852 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003853 } else {
3854 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003855 UsingLoc, SS.getRange(),
3856 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003857 }
John McCallb96ec562009-12-04 22:46:56 +00003858 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003859 D = UsingDecl::Create(Context, CurContext,
3860 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003861 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003862 }
John McCallb96ec562009-12-04 22:46:56 +00003863 D->setAccess(AS);
3864 CurContext->addDecl(D);
3865
3866 if (!LookupContext) return D;
3867 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003868
John McCall0b66eb32010-05-01 00:40:08 +00003869 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003870 UD->setInvalidDecl();
3871 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003872 }
3873
John McCall3969e302009-12-08 07:46:18 +00003874 // Look up the target name.
3875
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003876 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003877
John McCall3969e302009-12-08 07:46:18 +00003878 // Unlike most lookups, we don't always want to hide tag
3879 // declarations: tag names are visible through the using declaration
3880 // even if hidden by ordinary names, *except* in a dependent context
3881 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003882 if (!IsInstantiation)
3883 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003884
John McCall27b18f82009-11-17 02:14:36 +00003885 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003886
John McCall9f3059a2009-10-09 21:13:30 +00003887 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003888 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003889 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003890 UD->setInvalidDecl();
3891 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003892 }
3893
John McCallb96ec562009-12-04 22:46:56 +00003894 if (R.isAmbiguous()) {
3895 UD->setInvalidDecl();
3896 return UD;
3897 }
Mike Stump11289f42009-09-09 15:08:12 +00003898
John McCalle61f2ba2009-11-18 02:36:19 +00003899 if (IsTypeName) {
3900 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003901 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003902 Diag(IdentLoc, diag::err_using_typename_non_type);
3903 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3904 Diag((*I)->getUnderlyingDecl()->getLocation(),
3905 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003906 UD->setInvalidDecl();
3907 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003908 }
3909 } else {
3910 // If we asked for a non-typename and we got a type, error out,
3911 // but only if this is an instantiation of an unresolved using
3912 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003913 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003914 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3915 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003916 UD->setInvalidDecl();
3917 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003918 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003919 }
3920
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003921 // C++0x N2914 [namespace.udecl]p6:
3922 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003923 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003924 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3925 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003926 UD->setInvalidDecl();
3927 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003928 }
Mike Stump11289f42009-09-09 15:08:12 +00003929
John McCall84d87672009-12-10 09:41:52 +00003930 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3931 if (!CheckUsingShadowDecl(UD, *I, Previous))
3932 BuildUsingShadowDecl(S, UD, *I);
3933 }
John McCall3f746822009-11-17 05:59:44 +00003934
3935 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003936}
3937
John McCall84d87672009-12-10 09:41:52 +00003938/// Checks that the given using declaration is not an invalid
3939/// redeclaration. Note that this is checking only for the using decl
3940/// itself, not for any ill-formedness among the UsingShadowDecls.
3941bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3942 bool isTypeName,
3943 const CXXScopeSpec &SS,
3944 SourceLocation NameLoc,
3945 const LookupResult &Prev) {
3946 // C++03 [namespace.udecl]p8:
3947 // C++0x [namespace.udecl]p10:
3948 // A using-declaration is a declaration and can therefore be used
3949 // repeatedly where (and only where) multiple declarations are
3950 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003951 //
John McCall032092f2010-11-29 18:01:58 +00003952 // That's in non-member contexts.
3953 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003954 return false;
3955
3956 NestedNameSpecifier *Qual
3957 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3958
3959 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3960 NamedDecl *D = *I;
3961
3962 bool DTypename;
3963 NestedNameSpecifier *DQual;
3964 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3965 DTypename = UD->isTypeName();
3966 DQual = UD->getTargetNestedNameDecl();
3967 } else if (UnresolvedUsingValueDecl *UD
3968 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3969 DTypename = false;
3970 DQual = UD->getTargetNestedNameSpecifier();
3971 } else if (UnresolvedUsingTypenameDecl *UD
3972 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3973 DTypename = true;
3974 DQual = UD->getTargetNestedNameSpecifier();
3975 } else continue;
3976
3977 // using decls differ if one says 'typename' and the other doesn't.
3978 // FIXME: non-dependent using decls?
3979 if (isTypeName != DTypename) continue;
3980
3981 // using decls differ if they name different scopes (but note that
3982 // template instantiation can cause this check to trigger when it
3983 // didn't before instantiation).
3984 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3985 Context.getCanonicalNestedNameSpecifier(DQual))
3986 continue;
3987
3988 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003989 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003990 return true;
3991 }
3992
3993 return false;
3994}
3995
John McCall3969e302009-12-08 07:46:18 +00003996
John McCallb96ec562009-12-04 22:46:56 +00003997/// Checks that the given nested-name qualifier used in a using decl
3998/// in the current context is appropriately related to the current
3999/// scope. If an error is found, diagnoses it and returns true.
4000bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4001 const CXXScopeSpec &SS,
4002 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004003 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004004
John McCall3969e302009-12-08 07:46:18 +00004005 if (!CurContext->isRecord()) {
4006 // C++03 [namespace.udecl]p3:
4007 // C++0x [namespace.udecl]p8:
4008 // A using-declaration for a class member shall be a member-declaration.
4009
4010 // If we weren't able to compute a valid scope, it must be a
4011 // dependent class scope.
4012 if (!NamedContext || NamedContext->isRecord()) {
4013 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4014 << SS.getRange();
4015 return true;
4016 }
4017
4018 // Otherwise, everything is known to be fine.
4019 return false;
4020 }
4021
4022 // The current scope is a record.
4023
4024 // If the named context is dependent, we can't decide much.
4025 if (!NamedContext) {
4026 // FIXME: in C++0x, we can diagnose if we can prove that the
4027 // nested-name-specifier does not refer to a base class, which is
4028 // still possible in some cases.
4029
4030 // Otherwise we have to conservatively report that things might be
4031 // okay.
4032 return false;
4033 }
4034
4035 if (!NamedContext->isRecord()) {
4036 // Ideally this would point at the last name in the specifier,
4037 // but we don't have that level of source info.
4038 Diag(SS.getRange().getBegin(),
4039 diag::err_using_decl_nested_name_specifier_is_not_class)
4040 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4041 return true;
4042 }
4043
4044 if (getLangOptions().CPlusPlus0x) {
4045 // C++0x [namespace.udecl]p3:
4046 // In a using-declaration used as a member-declaration, the
4047 // nested-name-specifier shall name a base class of the class
4048 // being defined.
4049
4050 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4051 cast<CXXRecordDecl>(NamedContext))) {
4052 if (CurContext == NamedContext) {
4053 Diag(NameLoc,
4054 diag::err_using_decl_nested_name_specifier_is_current_class)
4055 << SS.getRange();
4056 return true;
4057 }
4058
4059 Diag(SS.getRange().getBegin(),
4060 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4061 << (NestedNameSpecifier*) SS.getScopeRep()
4062 << cast<CXXRecordDecl>(CurContext)
4063 << SS.getRange();
4064 return true;
4065 }
4066
4067 return false;
4068 }
4069
4070 // C++03 [namespace.udecl]p4:
4071 // A using-declaration used as a member-declaration shall refer
4072 // to a member of a base class of the class being defined [etc.].
4073
4074 // Salient point: SS doesn't have to name a base class as long as
4075 // lookup only finds members from base classes. Therefore we can
4076 // diagnose here only if we can prove that that can't happen,
4077 // i.e. if the class hierarchies provably don't intersect.
4078
4079 // TODO: it would be nice if "definitely valid" results were cached
4080 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4081 // need to be repeated.
4082
4083 struct UserData {
4084 llvm::DenseSet<const CXXRecordDecl*> Bases;
4085
4086 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4087 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4088 Data->Bases.insert(Base);
4089 return true;
4090 }
4091
4092 bool hasDependentBases(const CXXRecordDecl *Class) {
4093 return !Class->forallBases(collect, this);
4094 }
4095
4096 /// Returns true if the base is dependent or is one of the
4097 /// accumulated base classes.
4098 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4099 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4100 return !Data->Bases.count(Base);
4101 }
4102
4103 bool mightShareBases(const CXXRecordDecl *Class) {
4104 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4105 }
4106 };
4107
4108 UserData Data;
4109
4110 // Returns false if we find a dependent base.
4111 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4112 return false;
4113
4114 // Returns false if the class has a dependent base or if it or one
4115 // of its bases is present in the base set of the current context.
4116 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4117 return false;
4118
4119 Diag(SS.getRange().getBegin(),
4120 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4121 << (NestedNameSpecifier*) SS.getScopeRep()
4122 << cast<CXXRecordDecl>(CurContext)
4123 << SS.getRange();
4124
4125 return true;
John McCallb96ec562009-12-04 22:46:56 +00004126}
4127
John McCall48871652010-08-21 09:40:31 +00004128Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004129 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004130 SourceLocation AliasLoc,
4131 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004132 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004133 SourceLocation IdentLoc,
4134 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004135
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004136 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004137 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4138 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004139
Anders Carlssondca83c42009-03-28 06:23:46 +00004140 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004141 NamedDecl *PrevDecl
4142 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4143 ForRedeclaration);
4144 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4145 PrevDecl = 0;
4146
4147 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004148 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004149 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004150 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004151 // FIXME: At some point, we'll want to create the (redundant)
4152 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004153 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004154 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004155 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004156 }
Mike Stump11289f42009-09-09 15:08:12 +00004157
Anders Carlssondca83c42009-03-28 06:23:46 +00004158 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4159 diag::err_redefinition_different_kind;
4160 Diag(AliasLoc, DiagID) << Alias;
4161 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004162 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004163 }
4164
John McCall27b18f82009-11-17 02:14:36 +00004165 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004166 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004167
John McCall9f3059a2009-10-09 21:13:30 +00004168 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004169 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4170 CTC_NoKeywords, 0)) {
4171 if (R.getAsSingle<NamespaceDecl>() ||
4172 R.getAsSingle<NamespaceAliasDecl>()) {
4173 if (DeclContext *DC = computeDeclContext(SS, false))
4174 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4175 << Ident << DC << Corrected << SS.getRange()
4176 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4177 else
4178 Diag(IdentLoc, diag::err_using_directive_suggest)
4179 << Ident << Corrected
4180 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4181
4182 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4183 << Corrected;
4184
4185 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004186 } else {
4187 R.clear();
4188 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004189 }
4190 }
4191
4192 if (R.empty()) {
4193 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004194 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004195 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004196 }
Mike Stump11289f42009-09-09 15:08:12 +00004197
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004198 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004199 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4200 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004201 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004202 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCalld8d0d432010-02-16 06:53:13 +00004204 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004205 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004206}
4207
Douglas Gregora57478e2010-05-01 15:04:51 +00004208namespace {
4209 /// \brief Scoped object used to handle the state changes required in Sema
4210 /// to implicitly define the body of a C++ member function;
4211 class ImplicitlyDefinedFunctionScope {
4212 Sema &S;
4213 DeclContext *PreviousContext;
4214
4215 public:
4216 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4217 : S(S), PreviousContext(S.CurContext)
4218 {
4219 S.CurContext = Method;
4220 S.PushFunctionScope();
4221 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4222 }
4223
4224 ~ImplicitlyDefinedFunctionScope() {
4225 S.PopExpressionEvaluationContext();
4226 S.PopFunctionOrBlockScope();
4227 S.CurContext = PreviousContext;
4228 }
4229 };
4230}
4231
Sebastian Redlc15c3262010-09-13 22:02:47 +00004232static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4233 CXXRecordDecl *D) {
4234 ASTContext &Context = Self.Context;
4235 QualType ClassType = Context.getTypeDeclType(D);
4236 DeclarationName ConstructorName
4237 = Context.DeclarationNames.getCXXConstructorName(
4238 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4239
4240 DeclContext::lookup_const_iterator Con, ConEnd;
4241 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4242 Con != ConEnd; ++Con) {
4243 // FIXME: In C++0x, a constructor template can be a default constructor.
4244 if (isa<FunctionTemplateDecl>(*Con))
4245 continue;
4246
4247 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4248 if (Constructor->isDefaultConstructor())
4249 return Constructor;
4250 }
4251 return 0;
4252}
4253
Douglas Gregor0be31a22010-07-02 17:43:08 +00004254CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4255 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004256 // C++ [class.ctor]p5:
4257 // A default constructor for a class X is a constructor of class X
4258 // that can be called without an argument. If there is no
4259 // user-declared constructor for class X, a default constructor is
4260 // implicitly declared. An implicitly-declared default constructor
4261 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004262 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4263 "Should not build implicit default constructor!");
4264
Douglas Gregor6d880b12010-07-01 22:31:05 +00004265 // C++ [except.spec]p14:
4266 // An implicitly declared special member function (Clause 12) shall have an
4267 // exception-specification. [...]
4268 ImplicitExceptionSpecification ExceptSpec(Context);
4269
4270 // Direct base-class destructors.
4271 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4272 BEnd = ClassDecl->bases_end();
4273 B != BEnd; ++B) {
4274 if (B->isVirtual()) // Handled below.
4275 continue;
4276
Douglas Gregor9672f922010-07-03 00:47:00 +00004277 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4278 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4279 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4280 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004281 else if (CXXConstructorDecl *Constructor
4282 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004283 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004284 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004285 }
4286
4287 // Virtual base-class destructors.
4288 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4289 BEnd = ClassDecl->vbases_end();
4290 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004291 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4292 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4293 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4294 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4295 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004296 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004297 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004298 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004299 }
4300
4301 // Field destructors.
4302 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4303 FEnd = ClassDecl->field_end();
4304 F != FEnd; ++F) {
4305 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004306 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4307 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4308 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4309 ExceptSpec.CalledDecl(
4310 DeclareImplicitDefaultConstructor(FieldClassDecl));
4311 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004312 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004313 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004314 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004315 }
John McCalldb40c7f2010-12-14 08:05:40 +00004316
4317 FunctionProtoType::ExtProtoInfo EPI;
4318 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4319 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4320 EPI.NumExceptions = ExceptSpec.size();
4321 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004322
4323 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004324 CanQualType ClassType
4325 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4326 DeclarationName Name
4327 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004328 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004329 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004330 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004331 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004332 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004333 /*TInfo=*/0,
4334 /*isExplicit=*/false,
4335 /*isInline=*/true,
4336 /*isImplicitlyDeclared=*/true);
4337 DefaultCon->setAccess(AS_public);
4338 DefaultCon->setImplicit();
4339 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004340
4341 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004342 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4343
Douglas Gregor0be31a22010-07-02 17:43:08 +00004344 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004345 PushOnScopeChains(DefaultCon, S, false);
4346 ClassDecl->addDecl(DefaultCon);
4347
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004348 return DefaultCon;
4349}
4350
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004351void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4352 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004353 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004354 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004355 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004356
Anders Carlsson423f5d82010-04-23 16:04:08 +00004357 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004358 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004359
Douglas Gregora57478e2010-05-01 15:04:51 +00004360 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004361 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor54818f02010-05-12 16:39:35 +00004362 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4363 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004364 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004365 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004366 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004367 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004368 }
Douglas Gregor73193272010-09-20 16:48:21 +00004369
4370 SourceLocation Loc = Constructor->getLocation();
4371 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4372
4373 Constructor->setUsed();
4374 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004375}
4376
Douglas Gregor0be31a22010-07-02 17:43:08 +00004377CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004378 // C++ [class.dtor]p2:
4379 // If a class has no user-declared destructor, a destructor is
4380 // declared implicitly. An implicitly-declared destructor is an
4381 // inline public member of its class.
4382
4383 // C++ [except.spec]p14:
4384 // An implicitly declared special member function (Clause 12) shall have
4385 // an exception-specification.
4386 ImplicitExceptionSpecification ExceptSpec(Context);
4387
4388 // Direct base-class destructors.
4389 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4390 BEnd = ClassDecl->bases_end();
4391 B != BEnd; ++B) {
4392 if (B->isVirtual()) // Handled below.
4393 continue;
4394
4395 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4396 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004397 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004398 }
4399
4400 // Virtual base-class destructors.
4401 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4402 BEnd = ClassDecl->vbases_end();
4403 B != BEnd; ++B) {
4404 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4405 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004406 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004407 }
4408
4409 // Field destructors.
4410 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4411 FEnd = ClassDecl->field_end();
4412 F != FEnd; ++F) {
4413 if (const RecordType *RecordTy
4414 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4415 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004416 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004417 }
4418
Douglas Gregor7454c562010-07-02 20:37:36 +00004419 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004420 FunctionProtoType::ExtProtoInfo EPI;
4421 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4422 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4423 EPI.NumExceptions = ExceptSpec.size();
4424 EPI.Exceptions = ExceptSpec.data();
4425 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004426
4427 CanQualType ClassType
4428 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4429 DeclarationName Name
4430 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004431 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004432 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004433 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004434 /*isInline=*/true,
4435 /*isImplicitlyDeclared=*/true);
4436 Destructor->setAccess(AS_public);
4437 Destructor->setImplicit();
4438 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004439
4440 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004441 ++ASTContext::NumImplicitDestructorsDeclared;
4442
4443 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004444 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004445 PushOnScopeChains(Destructor, S, false);
4446 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004447
4448 // This could be uniqued if it ever proves significant.
4449 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4450
4451 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004452
Douglas Gregorf1203042010-07-01 19:09:28 +00004453 return Destructor;
4454}
4455
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004456void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004457 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004458 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004459 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004460 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004461 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004462
Douglas Gregor54818f02010-05-12 16:39:35 +00004463 if (Destructor->isInvalidDecl())
4464 return;
4465
Douglas Gregora57478e2010-05-01 15:04:51 +00004466 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004467
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004468 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004469 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4470 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregor54818f02010-05-12 16:39:35 +00004472 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004473 Diag(CurrentLocation, diag::note_member_synthesized_at)
4474 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4475
4476 Destructor->setInvalidDecl();
4477 return;
4478 }
4479
Douglas Gregor73193272010-09-20 16:48:21 +00004480 SourceLocation Loc = Destructor->getLocation();
4481 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4482
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004483 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004484 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004485}
4486
Douglas Gregorb139cd52010-05-01 20:49:11 +00004487/// \brief Builds a statement that copies the given entity from \p From to
4488/// \c To.
4489///
4490/// This routine is used to copy the members of a class with an
4491/// implicitly-declared copy assignment operator. When the entities being
4492/// copied are arrays, this routine builds for loops to copy them.
4493///
4494/// \param S The Sema object used for type-checking.
4495///
4496/// \param Loc The location where the implicit copy is being generated.
4497///
4498/// \param T The type of the expressions being copied. Both expressions must
4499/// have this type.
4500///
4501/// \param To The expression we are copying to.
4502///
4503/// \param From The expression we are copying from.
4504///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004505/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4506/// Otherwise, it's a non-static member subobject.
4507///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004508/// \param Depth Internal parameter recording the depth of the recursion.
4509///
4510/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004511static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004512BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004513 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004514 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004515 // C++0x [class.copy]p30:
4516 // Each subobject is assigned in the manner appropriate to its type:
4517 //
4518 // - if the subobject is of class type, the copy assignment operator
4519 // for the class is used (as if by explicit qualification; that is,
4520 // ignoring any possible virtual overriding functions in more derived
4521 // classes);
4522 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4523 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4524
4525 // Look for operator=.
4526 DeclarationName Name
4527 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4528 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4529 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4530
4531 // Filter out any result that isn't a copy-assignment operator.
4532 LookupResult::Filter F = OpLookup.makeFilter();
4533 while (F.hasNext()) {
4534 NamedDecl *D = F.next();
4535 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4536 if (Method->isCopyAssignmentOperator())
4537 continue;
4538
4539 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004540 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004541 F.done();
4542
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004543 // Suppress the protected check (C++ [class.protected]) for each of the
4544 // assignment operators we found. This strange dance is required when
4545 // we're assigning via a base classes's copy-assignment operator. To
4546 // ensure that we're getting the right base class subobject (without
4547 // ambiguities), we need to cast "this" to that subobject type; to
4548 // ensure that we don't go through the virtual call mechanism, we need
4549 // to qualify the operator= name with the base class (see below). However,
4550 // this means that if the base class has a protected copy assignment
4551 // operator, the protected member access check will fail. So, we
4552 // rewrite "protected" access to "public" access in this case, since we
4553 // know by construction that we're calling from a derived class.
4554 if (CopyingBaseSubobject) {
4555 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4556 L != LEnd; ++L) {
4557 if (L.getAccess() == AS_protected)
4558 L.setAccess(AS_public);
4559 }
4560 }
4561
Douglas Gregorb139cd52010-05-01 20:49:11 +00004562 // Create the nested-name-specifier that will be used to qualify the
4563 // reference to operator=; this is required to suppress the virtual
4564 // call mechanism.
4565 CXXScopeSpec SS;
4566 SS.setRange(Loc);
4567 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4568 T.getTypePtr()));
4569
4570 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004571 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004572 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004573 /*FirstQualifierInScope=*/0, OpLookup,
4574 /*TemplateArgs=*/0,
4575 /*SuppressQualifierCheck=*/true);
4576 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004577 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004578
4579 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004580
John McCalldadc5752010-08-24 06:29:42 +00004581 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004582 OpEqualRef.takeAs<Expr>(),
4583 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004584 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004585 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004586
4587 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004588 }
John McCallab8c2732010-03-16 06:11:48 +00004589
Douglas Gregorb139cd52010-05-01 20:49:11 +00004590 // - if the subobject is of scalar type, the built-in assignment
4591 // operator is used.
4592 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4593 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004594 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004595 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004596 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004597
4598 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004599 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004600
4601 // - if the subobject is an array, each element is assigned, in the
4602 // manner appropriate to the element type;
4603
4604 // Construct a loop over the array bounds, e.g.,
4605 //
4606 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4607 //
4608 // that will copy each of the array elements.
4609 QualType SizeType = S.Context.getSizeType();
4610
4611 // Create the iteration variable.
4612 IdentifierInfo *IterationVarName = 0;
4613 {
4614 llvm::SmallString<8> Str;
4615 llvm::raw_svector_ostream OS(Str);
4616 OS << "__i" << Depth;
4617 IterationVarName = &S.Context.Idents.get(OS.str());
4618 }
4619 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4620 IterationVarName, SizeType,
4621 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004622 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004623
4624 // Initialize the iteration variable to zero.
4625 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004626 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004627
4628 // Create a reference to the iteration variable; we'll use this several
4629 // times throughout.
4630 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004631 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004632 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4633
4634 // Create the DeclStmt that holds the iteration variable.
4635 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4636
4637 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004638 llvm::APInt Upper
4639 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004640 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004641 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004642 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4643 BO_NE, S.Context.BoolTy,
4644 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004645
4646 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004647 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004648 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4649 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004650
4651 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004652 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4653 IterationVarRef, Loc));
4654 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4655 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004656
4657 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004658 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4659 To, From, CopyingBaseSubobject,
4660 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004661 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004662 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004663
4664 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004665 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004666 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004667 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004668 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004669}
4670
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004671/// \brief Determine whether the given class has a copy assignment operator
4672/// that accepts a const-qualified argument.
4673static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4674 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4675
4676 if (!Class->hasDeclaredCopyAssignment())
4677 S.DeclareImplicitCopyAssignment(Class);
4678
4679 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4680 DeclarationName OpName
4681 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4682
4683 DeclContext::lookup_const_iterator Op, OpEnd;
4684 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4685 // C++ [class.copy]p9:
4686 // A user-declared copy assignment operator is a non-static non-template
4687 // member function of class X with exactly one parameter of type X, X&,
4688 // const X&, volatile X& or const volatile X&.
4689 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4690 if (!Method)
4691 continue;
4692
4693 if (Method->isStatic())
4694 continue;
4695 if (Method->getPrimaryTemplate())
4696 continue;
4697 const FunctionProtoType *FnType =
4698 Method->getType()->getAs<FunctionProtoType>();
4699 assert(FnType && "Overloaded operator has no prototype.");
4700 // Don't assert on this; an invalid decl might have been left in the AST.
4701 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4702 continue;
4703 bool AcceptsConst = true;
4704 QualType ArgType = FnType->getArgType(0);
4705 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4706 ArgType = Ref->getPointeeType();
4707 // Is it a non-const lvalue reference?
4708 if (!ArgType.isConstQualified())
4709 AcceptsConst = false;
4710 }
4711 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4712 continue;
4713
4714 // We have a single argument of type cv X or cv X&, i.e. we've found the
4715 // copy assignment operator. Return whether it accepts const arguments.
4716 return AcceptsConst;
4717 }
4718 assert(Class->isInvalidDecl() &&
4719 "No copy assignment operator declared in valid code.");
4720 return false;
4721}
4722
Douglas Gregor0be31a22010-07-02 17:43:08 +00004723CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004724 // Note: The following rules are largely analoguous to the copy
4725 // constructor rules. Note that virtual bases are not taken into account
4726 // for determining the argument type of the operator. Note also that
4727 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004728
4729
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004730 // C++ [class.copy]p10:
4731 // If the class definition does not explicitly declare a copy
4732 // assignment operator, one is declared implicitly.
4733 // The implicitly-defined copy assignment operator for a class X
4734 // will have the form
4735 //
4736 // X& X::operator=(const X&)
4737 //
4738 // if
4739 bool HasConstCopyAssignment = true;
4740
4741 // -- each direct base class B of X has a copy assignment operator
4742 // whose parameter is of type const B&, const volatile B& or B,
4743 // and
4744 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4745 BaseEnd = ClassDecl->bases_end();
4746 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4747 assert(!Base->getType()->isDependentType() &&
4748 "Cannot generate implicit members for class with dependent bases.");
4749 const CXXRecordDecl *BaseClassDecl
4750 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004751 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004752 }
4753
4754 // -- for all the nonstatic data members of X that are of a class
4755 // type M (or array thereof), each such class type has a copy
4756 // assignment operator whose parameter is of type const M&,
4757 // const volatile M& or M.
4758 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4759 FieldEnd = ClassDecl->field_end();
4760 HasConstCopyAssignment && Field != FieldEnd;
4761 ++Field) {
4762 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4763 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4764 const CXXRecordDecl *FieldClassDecl
4765 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004766 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004767 }
4768 }
4769
4770 // Otherwise, the implicitly declared copy assignment operator will
4771 // have the form
4772 //
4773 // X& X::operator=(X&)
4774 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4775 QualType RetType = Context.getLValueReferenceType(ArgType);
4776 if (HasConstCopyAssignment)
4777 ArgType = ArgType.withConst();
4778 ArgType = Context.getLValueReferenceType(ArgType);
4779
Douglas Gregor68e11362010-07-01 17:48:08 +00004780 // C++ [except.spec]p14:
4781 // An implicitly declared special member function (Clause 12) shall have an
4782 // exception-specification. [...]
4783 ImplicitExceptionSpecification ExceptSpec(Context);
4784 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4785 BaseEnd = ClassDecl->bases_end();
4786 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004787 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004788 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004789
4790 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4791 DeclareImplicitCopyAssignment(BaseClassDecl);
4792
Douglas Gregor68e11362010-07-01 17:48:08 +00004793 if (CXXMethodDecl *CopyAssign
4794 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4795 ExceptSpec.CalledDecl(CopyAssign);
4796 }
4797 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4798 FieldEnd = ClassDecl->field_end();
4799 Field != FieldEnd;
4800 ++Field) {
4801 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4802 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004803 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004804 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004805
4806 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4807 DeclareImplicitCopyAssignment(FieldClassDecl);
4808
Douglas Gregor68e11362010-07-01 17:48:08 +00004809 if (CXXMethodDecl *CopyAssign
4810 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4811 ExceptSpec.CalledDecl(CopyAssign);
4812 }
4813 }
4814
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004815 // An implicitly-declared copy assignment operator is an inline public
4816 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004817 FunctionProtoType::ExtProtoInfo EPI;
4818 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4819 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4820 EPI.NumExceptions = ExceptSpec.size();
4821 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004822 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004823 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004824 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004825 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004826 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004827 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004828 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004829 /*isInline=*/true);
4830 CopyAssignment->setAccess(AS_public);
4831 CopyAssignment->setImplicit();
4832 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004833
4834 // Add the parameter to the operator.
4835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4836 ClassDecl->getLocation(),
4837 /*Id=*/0,
4838 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004839 SC_None,
4840 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004841 CopyAssignment->setParams(&FromParam, 1);
4842
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004843 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004844 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4845
Douglas Gregor0be31a22010-07-02 17:43:08 +00004846 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004847 PushOnScopeChains(CopyAssignment, S, false);
4848 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004849
4850 AddOverriddenMethods(ClassDecl, CopyAssignment);
4851 return CopyAssignment;
4852}
4853
Douglas Gregorb139cd52010-05-01 20:49:11 +00004854void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4855 CXXMethodDecl *CopyAssignOperator) {
4856 assert((CopyAssignOperator->isImplicit() &&
4857 CopyAssignOperator->isOverloadedOperator() &&
4858 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004859 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004860 "DefineImplicitCopyAssignment called for wrong function");
4861
4862 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4863
4864 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4865 CopyAssignOperator->setInvalidDecl();
4866 return;
4867 }
4868
4869 CopyAssignOperator->setUsed();
4870
4871 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004872 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004873
4874 // C++0x [class.copy]p30:
4875 // The implicitly-defined or explicitly-defaulted copy assignment operator
4876 // for a non-union class X performs memberwise copy assignment of its
4877 // subobjects. The direct base classes of X are assigned first, in the
4878 // order of their declaration in the base-specifier-list, and then the
4879 // immediate non-static data members of X are assigned, in the order in
4880 // which they were declared in the class definition.
4881
4882 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004883 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004884
4885 // The parameter for the "other" object, which we are copying from.
4886 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4887 Qualifiers OtherQuals = Other->getType().getQualifiers();
4888 QualType OtherRefType = Other->getType();
4889 if (const LValueReferenceType *OtherRef
4890 = OtherRefType->getAs<LValueReferenceType>()) {
4891 OtherRefType = OtherRef->getPointeeType();
4892 OtherQuals = OtherRefType.getQualifiers();
4893 }
4894
4895 // Our location for everything implicitly-generated.
4896 SourceLocation Loc = CopyAssignOperator->getLocation();
4897
4898 // Construct a reference to the "other" object. We'll be using this
4899 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00004900 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004901 assert(OtherRef && "Reference to parameter cannot fail!");
4902
4903 // Construct the "this" pointer. We'll be using this throughout the generated
4904 // ASTs.
4905 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4906 assert(This && "Reference to this cannot fail!");
4907
4908 // Assign base classes.
4909 bool Invalid = false;
4910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4911 E = ClassDecl->bases_end(); Base != E; ++Base) {
4912 // Form the assignment:
4913 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4914 QualType BaseType = Base->getType().getUnqualifiedType();
4915 CXXRecordDecl *BaseClassDecl = 0;
4916 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4917 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4918 else {
4919 Invalid = true;
4920 continue;
4921 }
4922
John McCallcf142162010-08-07 06:22:56 +00004923 CXXCastPath BasePath;
4924 BasePath.push_back(Base);
4925
Douglas Gregorb139cd52010-05-01 20:49:11 +00004926 // Construct the "from" expression, which is an implicit cast to the
4927 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00004928 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004929 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004930 CK_UncheckedDerivedToBase,
4931 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004932
4933 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004934 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004935
4936 // Implicitly cast "this" to the appropriately-qualified base type.
4937 Expr *ToE = To.takeAs<Expr>();
4938 ImpCastExprToType(ToE,
4939 Context.getCVRQualifiedType(BaseType,
4940 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004941 CK_UncheckedDerivedToBase,
4942 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004943 To = Owned(ToE);
4944
4945 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004946 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004947 To.get(), From,
4948 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004949 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004950 Diag(CurrentLocation, diag::note_member_synthesized_at)
4951 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4952 CopyAssignOperator->setInvalidDecl();
4953 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004954 }
4955
4956 // Success! Record the copy.
4957 Statements.push_back(Copy.takeAs<Expr>());
4958 }
4959
4960 // \brief Reference to the __builtin_memcpy function.
4961 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004962 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004963 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004964
4965 // Assign non-static members.
4966 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4967 FieldEnd = ClassDecl->field_end();
4968 Field != FieldEnd; ++Field) {
4969 // Check for members of reference type; we can't copy those.
4970 if (Field->getType()->isReferenceType()) {
4971 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4972 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4973 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004974 Diag(CurrentLocation, diag::note_member_synthesized_at)
4975 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004976 Invalid = true;
4977 continue;
4978 }
4979
4980 // Check for members of const-qualified, non-class type.
4981 QualType BaseType = Context.getBaseElementType(Field->getType());
4982 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4983 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4984 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4985 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004986 Diag(CurrentLocation, diag::note_member_synthesized_at)
4987 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004988 Invalid = true;
4989 continue;
4990 }
4991
4992 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004993 if (FieldType->isIncompleteArrayType()) {
4994 assert(ClassDecl->hasFlexibleArrayMember() &&
4995 "Incomplete array type is not valid");
4996 continue;
4997 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004998
4999 // Build references to the field in the object we're copying from and to.
5000 CXXScopeSpec SS; // Intentionally empty
5001 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5002 LookupMemberName);
5003 MemberLookup.addDecl(*Field);
5004 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005005 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005006 Loc, /*IsArrow=*/false,
5007 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005008 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005009 Loc, /*IsArrow=*/true,
5010 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005011 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5012 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5013
5014 // If the field should be copied with __builtin_memcpy rather than via
5015 // explicit assignments, do so. This optimization only applies for arrays
5016 // of scalars and arrays of class type with trivial copy-assignment
5017 // operators.
5018 if (FieldType->isArrayType() &&
5019 (!BaseType->isRecordType() ||
5020 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5021 ->hasTrivialCopyAssignment())) {
5022 // Compute the size of the memory buffer to be copied.
5023 QualType SizeType = Context.getSizeType();
5024 llvm::APInt Size(Context.getTypeSize(SizeType),
5025 Context.getTypeSizeInChars(BaseType).getQuantity());
5026 for (const ConstantArrayType *Array
5027 = Context.getAsConstantArrayType(FieldType);
5028 Array;
5029 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005030 llvm::APInt ArraySize
5031 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005032 Size *= ArraySize;
5033 }
5034
5035 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005036 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5037 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005038
5039 bool NeedsCollectableMemCpy =
5040 (BaseType->isRecordType() &&
5041 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5042
5043 if (NeedsCollectableMemCpy) {
5044 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005045 // Create a reference to the __builtin_objc_memmove_collectable function.
5046 LookupResult R(*this,
5047 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005048 Loc, LookupOrdinaryName);
5049 LookupName(R, TUScope, true);
5050
5051 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5052 if (!CollectableMemCpy) {
5053 // Something went horribly wrong earlier, and we will have
5054 // complained about it.
5055 Invalid = true;
5056 continue;
5057 }
5058
5059 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5060 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005061 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005062 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5063 }
5064 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005065 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005066 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005067 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5068 LookupOrdinaryName);
5069 LookupName(R, TUScope, true);
5070
5071 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5072 if (!BuiltinMemCpy) {
5073 // Something went horribly wrong earlier, and we will have complained
5074 // about it.
5075 Invalid = true;
5076 continue;
5077 }
5078
5079 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5080 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005081 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005082 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5083 }
5084
John McCall37ad5512010-08-23 06:44:23 +00005085 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005086 CallArgs.push_back(To.takeAs<Expr>());
5087 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005088 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005089 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005090 if (NeedsCollectableMemCpy)
5091 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005092 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005093 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005094 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005095 else
5096 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005097 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005098 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005099 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005100
Douglas Gregorb139cd52010-05-01 20:49:11 +00005101 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5102 Statements.push_back(Call.takeAs<Expr>());
5103 continue;
5104 }
5105
5106 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005107 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005108 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005109 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005110 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005111 Diag(CurrentLocation, diag::note_member_synthesized_at)
5112 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5113 CopyAssignOperator->setInvalidDecl();
5114 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005115 }
5116
5117 // Success! Record the copy.
5118 Statements.push_back(Copy.takeAs<Stmt>());
5119 }
5120
5121 if (!Invalid) {
5122 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005123 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005124
John McCalldadc5752010-08-24 06:29:42 +00005125 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005126 if (Return.isInvalid())
5127 Invalid = true;
5128 else {
5129 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005130
5131 if (Trap.hasErrorOccurred()) {
5132 Diag(CurrentLocation, diag::note_member_synthesized_at)
5133 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5134 Invalid = true;
5135 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005136 }
5137 }
5138
5139 if (Invalid) {
5140 CopyAssignOperator->setInvalidDecl();
5141 return;
5142 }
5143
John McCalldadc5752010-08-24 06:29:42 +00005144 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005145 /*isStmtExpr=*/false);
5146 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5147 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005148}
5149
Douglas Gregor0be31a22010-07-02 17:43:08 +00005150CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5151 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005152 // C++ [class.copy]p4:
5153 // If the class definition does not explicitly declare a copy
5154 // constructor, one is declared implicitly.
5155
Douglas Gregor54be3392010-07-01 17:57:27 +00005156 // C++ [class.copy]p5:
5157 // The implicitly-declared copy constructor for a class X will
5158 // have the form
5159 //
5160 // X::X(const X&)
5161 //
5162 // if
5163 bool HasConstCopyConstructor = true;
5164
5165 // -- each direct or virtual base class B of X has a copy
5166 // constructor whose first parameter is of type const B& or
5167 // const volatile B&, and
5168 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5169 BaseEnd = ClassDecl->bases_end();
5170 HasConstCopyConstructor && Base != BaseEnd;
5171 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005172 // Virtual bases are handled below.
5173 if (Base->isVirtual())
5174 continue;
5175
Douglas Gregora6d69502010-07-02 23:41:54 +00005176 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005177 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005178 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5179 DeclareImplicitCopyConstructor(BaseClassDecl);
5180
Douglas Gregorcfe68222010-07-01 18:27:03 +00005181 HasConstCopyConstructor
5182 = BaseClassDecl->hasConstCopyConstructor(Context);
5183 }
5184
5185 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5186 BaseEnd = ClassDecl->vbases_end();
5187 HasConstCopyConstructor && Base != BaseEnd;
5188 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005189 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005190 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005191 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5192 DeclareImplicitCopyConstructor(BaseClassDecl);
5193
Douglas Gregor54be3392010-07-01 17:57:27 +00005194 HasConstCopyConstructor
5195 = BaseClassDecl->hasConstCopyConstructor(Context);
5196 }
5197
5198 // -- for all the nonstatic data members of X that are of a
5199 // class type M (or array thereof), each such class type
5200 // has a copy constructor whose first parameter is of type
5201 // const M& or const volatile M&.
5202 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5203 FieldEnd = ClassDecl->field_end();
5204 HasConstCopyConstructor && Field != FieldEnd;
5205 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005206 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005207 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005208 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005209 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005210 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5211 DeclareImplicitCopyConstructor(FieldClassDecl);
5212
Douglas Gregor54be3392010-07-01 17:57:27 +00005213 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005214 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005215 }
5216 }
5217
5218 // Otherwise, the implicitly declared copy constructor will have
5219 // the form
5220 //
5221 // X::X(X&)
5222 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5223 QualType ArgType = ClassType;
5224 if (HasConstCopyConstructor)
5225 ArgType = ArgType.withConst();
5226 ArgType = Context.getLValueReferenceType(ArgType);
5227
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005228 // C++ [except.spec]p14:
5229 // An implicitly declared special member function (Clause 12) shall have an
5230 // exception-specification. [...]
5231 ImplicitExceptionSpecification ExceptSpec(Context);
5232 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5233 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5234 BaseEnd = ClassDecl->bases_end();
5235 Base != BaseEnd;
5236 ++Base) {
5237 // Virtual bases are handled below.
5238 if (Base->isVirtual())
5239 continue;
5240
Douglas Gregora6d69502010-07-02 23:41:54 +00005241 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005242 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005243 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5244 DeclareImplicitCopyConstructor(BaseClassDecl);
5245
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005246 if (CXXConstructorDecl *CopyConstructor
5247 = BaseClassDecl->getCopyConstructor(Context, Quals))
5248 ExceptSpec.CalledDecl(CopyConstructor);
5249 }
5250 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5251 BaseEnd = ClassDecl->vbases_end();
5252 Base != BaseEnd;
5253 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005254 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005255 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005256 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5257 DeclareImplicitCopyConstructor(BaseClassDecl);
5258
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005259 if (CXXConstructorDecl *CopyConstructor
5260 = BaseClassDecl->getCopyConstructor(Context, Quals))
5261 ExceptSpec.CalledDecl(CopyConstructor);
5262 }
5263 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5264 FieldEnd = ClassDecl->field_end();
5265 Field != FieldEnd;
5266 ++Field) {
5267 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5268 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005269 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005270 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005271 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5272 DeclareImplicitCopyConstructor(FieldClassDecl);
5273
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005274 if (CXXConstructorDecl *CopyConstructor
5275 = FieldClassDecl->getCopyConstructor(Context, Quals))
5276 ExceptSpec.CalledDecl(CopyConstructor);
5277 }
5278 }
5279
Douglas Gregor54be3392010-07-01 17:57:27 +00005280 // An implicitly-declared copy constructor is an inline public
5281 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005282 FunctionProtoType::ExtProtoInfo EPI;
5283 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5284 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5285 EPI.NumExceptions = ExceptSpec.size();
5286 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005287 DeclarationName Name
5288 = Context.DeclarationNames.getCXXConstructorName(
5289 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005290 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005291 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005292 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005293 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005294 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005295 /*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 Gregora6d69502010-07-02 23:41:54 +00005303 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005304 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5305
Douglas Gregor54be3392010-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 McCall8e7d6562010-08-26 03:08:43 +00005311 SC_None,
5312 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005313 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005314 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005315 PushOnScopeChains(CopyConstructor, S, false);
5316 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005317
5318 return CopyConstructor;
5319}
5320
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005321void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5322 CXXConstructorDecl *CopyConstructor,
5323 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005324 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005325 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005326 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005327 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005328
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005329 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005330 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005331
Douglas Gregora57478e2010-05-01 15:04:51 +00005332 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005333 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005334
Douglas Gregor54818f02010-05-12 16:39:35 +00005335 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5336 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005337 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005338 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005339 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-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 Carlsson53e1ba92010-04-25 00:52:09 +00005346 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005347
5348 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005349}
5350
John McCalldadc5752010-08-24 06:29:42 +00005351ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005352Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005353 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005354 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005355 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005356 unsigned ConstructKind,
5357 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005358 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005359
Douglas Gregor45cf7e32010-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 McCall7a626f62010-09-15 10:14:12 +00005370 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5371 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005372 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005373 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005374 }
Mike Stump11289f42009-09-09 15:08:12 +00005375
5376 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005377 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005378 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005379}
5380
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005381/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5382/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005383ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005384Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5385 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005386 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005387 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005388 unsigned ConstructKind,
5389 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005390 unsigned NumExprs = ExprArgs.size();
5391 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005392
Douglas Gregor27381f32009-11-23 12:27:39 +00005393 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005394 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005395 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005396 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005397 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5398 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005399}
5400
Mike Stump11289f42009-09-09 15:08:12 +00005401bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005402 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005403 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005404 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005405 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005406 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005407 move(Exprs), false, CXXConstructExpr::CK_Complete,
5408 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005409 if (TempResult.isInvalid())
5410 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005411
Anders Carlsson6eb55572009-08-25 05:12:04 +00005412 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005413 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005414 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005415 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005416 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005417
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005418 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005419}
5420
John McCall03c48482010-02-02 09:10:11 +00005421void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5422 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005423 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005424 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005425 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005426 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005427 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005428 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005429 << VD->getDeclName()
5430 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005431
John McCall386dfc72010-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 McCall47e40932010-08-01 20:20:59 +00005434 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005435 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005436}
5437
Mike Stump11289f42009-09-09 15:08:12 +00005438/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005439/// ActOnDeclarator, when a C++ direct initializer is present.
5440/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005441void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005442 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005443 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005444 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005445 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005446
5447 // If there is no declaration, there was an error parsing it. Just ignore
5448 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005449 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005450 return;
Mike Stump11289f42009-09-09 15:08:12 +00005451
Argyrios Kyrtzidis9a1191c2008-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 Gregor402250f2009-08-26 21:14:46 +00005459 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005460 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-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 Kyrtzidis153d9672008-10-06 18:37:09 +00005468
Argyrios Kyrtzidis9a1191c2008-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 Kyrtzidis153d9672008-10-06 18:37:09 +00005472 // class type.
5473
Douglas Gregor50dc2192010-02-11 22:55:30 +00005474 if (!VDecl->getType()->isDependentType() &&
5475 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005476 diag::err_typecheck_decl_incomplete_type)) {
5477 VDecl->setInvalidDecl();
5478 return;
5479 }
5480
Douglas Gregorb6ea6082009-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 Redl5ca79842010-02-01 20:16:42 +00005487 const VarDecl *Def;
5488 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-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 Kyrtzidis153d9672008-10-06 18:37:09 +00005493 return;
5494 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005495
Douglas Gregorf0f83692010-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 Gregor50dc2192010-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 Gregorb6ea6082009-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 McCallb268a282010-08-23 23:25:46 +00005541 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005542 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005543 if (Result.isInvalid()) {
5544 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005545 return;
5546 }
John McCallacf0ee52010-10-08 02:01:28 +00005547
5548 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005549
Douglas Gregora40433a2010-12-07 00:41:46 +00005550 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005551 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005552 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005553
John McCall8b0f4ff2010-08-02 21:13:48 +00005554 if (!VDecl->isInvalidDecl() &&
5555 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005556 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-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 McCall03c48482010-02-02 09:10:11 +00005562 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5563 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005564}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005565
Douglas Gregor5d3507d2009-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 McCall37ad5512010-08-23 06:44:23 +00005575 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-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 Gregor5d3507d2009-09-09 23:08:42 +00005584
5585 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005586 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005587 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005588 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005589 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-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 Gregorc28b57d2008-11-03 20:45:27 +00005600}
5601
Anders Carlssone363c8e2009-12-12 00:32:00 +00005602static inline bool
5603CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5604 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005605 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-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 McCall8e7d6562010-08-26 03:08:43 +00005613 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-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 Carlsson60659a82009-12-12 02:43:16 +00005619 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005620}
5621
Anders Carlsson7e0b2072009-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 Gregor684d7bd2009-12-22 23:42:49 +00005662 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-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 Carlsson12308f42009-12-11 23:23:22 +00005670static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005671CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-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 Carlsson7e0b2072009-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 Carlsson22f443f2009-12-12 00:26:23 +00005694 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005695 diag::err_operator_new_default_arg)
5696 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5697
5698 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005699}
5700
5701static bool
Anders Carlsson12308f42009-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 Carlssone363c8e2009-12-12 00:32:00 +00005707 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5708 return true;
Anders Carlsson12308f42009-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 Carlsson7e0b2072009-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 Carlsson12308f42009-12-11 23:23:22 +00005718
Anders Carlsson12308f42009-12-11 23:23:22 +00005719 return false;
5720}
5721
Douglas Gregor11d0c4c2008-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 Gregord69246b2008-11-17 16:14:12 +00005726 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005727 "Expected an overloaded operator declaration");
5728
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005729 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5730
Mike Stump11289f42009-09-09 15:08:12 +00005731 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-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 Carlssonf1f46952009-12-11 23:31:21 +00005737 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005738 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005739
Anders Carlsson22f443f2009-12-12 00:26:23 +00005740 if (Op == OO_New || Op == OO_Array_New)
5741 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-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 Gregord69246b2008-11-17 16:14:12 +00005748 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5749 if (MethodDecl->isStatic())
5750 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005751 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005752 } else {
5753 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-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 Friedman173e0b7a2009-06-27 05:59:59 +00005758 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5759 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005760 ClassOrEnumParam = true;
5761 break;
5762 }
5763 }
5764
Douglas Gregord69246b2008-11-17 16:14:12 +00005765 if (!ClassOrEnumParam)
5766 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005767 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005768 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-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 Stump11289f42009-09-09 15:08:12 +00005775 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-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 Carlsson7e0b2072009-12-13 17:53:43 +00005780 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005781 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005782 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005783 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005784 }
5785 }
5786
Douglas Gregor6cf08062008-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 Gregor11d0c4c2008-11-06 22:13:31 +00005793
Douglas Gregor6cf08062008-11-10 13:38:07 +00005794 bool CanBeUnaryOperator = OperatorUses[Op][0];
5795 bool CanBeBinaryOperator = OperatorUses[Op][1];
5796 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-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 Stump11289f42009-09-09 15:08:12 +00005802 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005803 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-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 Lattnerc5bab9f2008-11-21 07:57:12 +00005809 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005810 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005811 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005812 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005813 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005814 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005815 assert(CanBeBinaryOperator &&
5816 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005817 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005818 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005819
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005820 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005821 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005822 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005823
Douglas Gregord69246b2008-11-17 16:14:12 +00005824 // Overloaded operators other than operator() cannot be variadic.
5825 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005826 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005827 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005828 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005829 }
5830
5831 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005832 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5833 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005834 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005835 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-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 McCall9dd450b2009-09-21 23:43:11 +00005851 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005852 ParamIsInt = BT->getKind() == BuiltinType::Int;
5853
Chris Lattner2b786902008-11-21 07:50:02 +00005854 if (!ParamIsInt)
5855 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005856 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005857 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005858 }
5859
Douglas Gregord69246b2008-11-17 16:14:12 +00005860 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005861}
Chris Lattner3b024a32008-12-17 07:09:26 +00005862
Alexis Huntc88db062010-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
Alexis Hunt7dd26172010-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));
Alexis Huntc88db062010-01-13 09:01:02 +00005887
Alexis Hunt7dd26172010-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 {
Alexis Huntc88db062010-01-13 09:01:02 +00005897 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005898 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5899
Alexis Huntc88db062010-01-13 09:01:02 +00005900 QualType T = (*Param)->getType();
5901
Alexis Hunt079a6f72010-04-07 22:57:35 +00005902 // unsigned long long int, long double, and any character type are allowed
5903 // as the only parameters.
Alexis Huntc88db062010-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
Alexis Hunt079a6f72010-04-07 22:57:35 +00005915 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-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 Gregor07665a62009-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 Lattner8ea64422010-11-09 20:15:55 +00005967Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5968 SourceLocation LangLoc,
5969 llvm::StringRef Lang,
5970 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005971 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005972 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005973 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005974 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005975 Language = LinkageSpecDecl::lang_cxx;
5976 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005977 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00005978 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00005979 }
Mike Stump11289f42009-09-09 15:08:12 +00005980
Chris Lattner438e5012008-12-17 07:13:27 +00005981 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005982
Douglas Gregor07665a62009-01-05 19:45:36 +00005983 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005984 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005985 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005986 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005987 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00005988 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00005989}
5990
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00005991/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-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 McCall48871652010-08-21 09:40:31 +00005995Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
5996 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00005997 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005998 if (LinkageSpec)
5999 PopDeclContext();
6000 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006001}
6002
Douglas Gregor5e16fbe2009-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 Gregor9f0e1aa2010-09-09 17:09:21 +00006006VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006007 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006008 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006009 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006010 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006011 QualType ExDeclType = TInfo->getType();
6012
Sebastian Redl54c04d42008-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 Redlb28b4072009-03-22 23:49:27 +00006022 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006023 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006024 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006025 Invalid = true;
6026 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006027
Douglas Gregor104ee002010-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 Redl54c04d42008-12-22 19:15:10 +00006031 QualType BaseType = ExDeclType;
6032 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006033 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006034 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006035 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006036 BaseType = Ptr->getPointeeType();
6037 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006038 DK = diag::ext_catch_incomplete_ptr;
6039 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006040 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006041 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006042 BaseType = Ref->getPointeeType();
6043 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006044 DK = diag::ext_catch_incomplete_ref;
6045 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006046 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006047 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006048 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6049 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006050 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006051
Mike Stump11289f42009-09-09 15:08:12 +00006052 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006053 RequireNonAbstractType(Loc, ExDeclType,
6054 diag::err_abstract_type_in_decl,
6055 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006056 Invalid = true;
6057
John McCall2ca705e2010-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 Stump11289f42009-09-09 15:08:12 +00006079 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006080 Name, ExDeclType, TInfo, SC_None,
6081 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006082 ExDecl->setExceptionVariable(true);
6083
Douglas Gregor6de584c2010-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 McCall7decc9e2010-11-18 06:31:45 +00006097 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006098 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6099 SourceLocation());
6100 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006101 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006102 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006103 if (Result.isInvalid())
6104 Invalid = true;
6105 else
6106 FinalizeVarWithDestructor(ExDecl, RecordTy);
6107 }
6108 }
6109
Douglas Gregor5e16fbe2009-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 McCall48871652010-08-21 09:40:31 +00006118Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6120 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006121
6122 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006123 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006124 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006125 LookupOrdinaryName,
6126 ForRedeclaration)) {
Sebastian Redl54c04d42008-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 McCall48871652010-08-21 09:40:31 +00006129 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-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 Redl54c04d42008-12-22 19:15:10 +00006133 }
6134 }
6135
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006136 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006137 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6138 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006139 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006140 }
6141
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006142 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006143 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006144 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006145
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006146 if (Invalid)
6147 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006148
Sebastian Redl54c04d42008-12-22 19:15:10 +00006149 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006150 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006151 PushOnScopeChains(ExDecl, S);
6152 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006153 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006154
Douglas Gregor758a8692009-06-17 21:51:59 +00006155 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006156 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006157}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006158
John McCall48871652010-08-21 09:40:31 +00006159Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006160 Expr *AssertExpr,
6161 Expr *AssertMessageExpr_) {
6162 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006163
Anders Carlsson54b26982009-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 McCall48871652010-08-21 09:40:31 +00006169 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006170 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006171
Anders Carlsson54b26982009-03-14 00:33:21 +00006172 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006173 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006174 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006175 }
6176 }
Mike Stump11289f42009-09-09 15:08:12 +00006177
Mike Stump11289f42009-09-09 15:08:12 +00006178 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006179 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006180
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006181 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006182 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006183}
Sebastian Redlf769df52009-03-24 22:27:57 +00006184
Douglas Gregorafb9bc12010-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 Bagnara1108e7b2010-05-20 10:00:11 +00006193 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006194
Douglas Gregor3b4abb62010-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 Gregorafb9bc12010-04-07 16:53:43 +00006225 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006226 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006227 }
6228 }
6229
Douglas Gregor3b4abb62010-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 Gregorafb9bc12010-04-07 16:53:43 +00006237
6238 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6239}
6240
John McCallace48cd2010-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 McCall11083da2009-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 McCall48871652010-08-21 09:40:31 +00006362Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006363 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006364 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006365
6366 assert(DS.isFriendSpecified());
6367 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6368
John McCall11083da2009-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 Lattner1fb66f42009-10-25 17:47:27 +00006372 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006373 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6374 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006375 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006376 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006377
John McCall11083da2009-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 Gregore677daf2010-03-31 22:19:08 +00006392 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006393 Diag(Loc, diag::err_tagless_friend_type_template)
6394 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006395 return 0;
John McCall11083da2009-09-16 22:47:08 +00006396 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006397
John McCallaa74a0c2009-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 McCall463e10c2009-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 McCall15ad0962010-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 McCallaa74a0c2009-08-28 07:59:38 +00006408
John McCall11083da2009-09-16 22:47:08 +00006409 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006410 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006411 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006412 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006413 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006414 TSI,
John McCall11083da2009-09-16 22:47:08 +00006415 DS.getFriendSpecLoc());
6416 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006417 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6418
6419 if (!D)
John McCall48871652010-08-21 09:40:31 +00006420 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006421
John McCall11083da2009-09-16 22:47:08 +00006422 D->setAccess(AS_public);
6423 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006424
John McCall48871652010-08-21 09:40:31 +00006425 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006426}
6427
John McCallde3fd222010-10-12 23:13:28 +00006428Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6429 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-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 McCall8cb7bdf2010-06-04 23:28:52 +00006436 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6437 QualType T = TInfo->getType();
John McCall07e91c02009-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 McCallaa74a0c2009-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 McCall07e91c02009-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 McCall48871652010-08-21 09:40:31 +00006454 return 0;
John McCall07e91c02009-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 McCallde3fd222010-10-12 23:13:28 +00006472 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006473 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6474 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006475 assert(Name);
6476
John McCall07e91c02009-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 McCallccbc0322010-10-13 06:22:15 +00006480 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006481 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006482 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006483
John McCallde3fd222010-10-12 23:13:28 +00006484 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006485
John McCallde3fd222010-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 McCallf7cfb222010-10-13 05:45:15 +00006488 // appropriate scope and look for a function or function template
John McCallde3fd222010-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 McCallf7cfb222010-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 McCallf4776592010-10-14 22:22:28 +00006506 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006507
John McCallf7cfb222010-10-13 05:45:15 +00006508 // Find the appropriate context according to the above.
John McCall07e91c02009-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 Gregora29a3ff2009-09-28 00:08:27 +00006518 while (DC->isRecord())
6519 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006520
John McCall1f82f242009-11-18 22:49:29 +00006521 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006522
6523 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006524 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006525 break;
John McCallf7cfb222010-10-13 05:45:15 +00006526
John McCallf4776592010-10-14 22:22:28 +00006527 if (isTemplateId) {
6528 if (isa<TranslationUnitDecl>(DC)) break;
6529 } else {
6530 if (DC->isFileContext()) break;
6531 }
John McCall07e91c02009-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 McCall93343b92009-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 McCall1f82f242009-11-18 22:49:29 +00006540 if (!Previous.empty() && DC->Equals(CurContext)
6541 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006542 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006543
John McCallccbc0322010-10-13 06:22:15 +00006544 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006545
John McCallde3fd222010-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 McCall07e91c02009-08-06 02:15:43 +00006588 }
6589
John McCallf7cfb222010-10-13 05:45:15 +00006590 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006591 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-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 McCall07e91c02009-08-06 02:15:43 +00006595 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006596 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6597 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006598 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006599 }
John McCall07e91c02009-08-06 02:15:43 +00006600 }
6601
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006602 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006603 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006604 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006605 IsDefinition,
6606 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006607 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006608
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006609 assert(ND->getDeclContext() == DC);
6610 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006611
John McCall759e32b2009-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 Stump11289f42009-09-09 15:08:12 +00006615 //
John McCall759e32b2009-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 Redl50c68252010-08-31 00:36:30 +00006619 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006620 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006621 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006622 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006623 }
John McCallaa74a0c2009-08-28 07:59:38 +00006624
6625 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006626 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006627 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006628 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006629 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006630
John McCallde3fd222010-10-12 23:13:28 +00006631 if (ND->isInvalidDecl())
6632 FrD->setInvalidDecl();
John McCall2c2eb122010-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 McCallde3fd222010-10-12 23:13:28 +00006644
John McCall48871652010-08-21 09:40:31 +00006645 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006646}
6647
John McCall48871652010-08-21 09:40:31 +00006648void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6649 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006650
Sebastian Redlf769df52009-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 Redl4c018662009-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 Carlssonf2a2e332009-05-14 01:09:04 +00006685
Mike Stump11289f42009-09-09 15:08:12 +00006686bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006687 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006688 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6689 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006690
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006691 if (Context.hasSameType(NewTy, OldTy) ||
6692 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006693 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006694
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006695 // Check if the return types are covariant
6696 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006697
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006698 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006699 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6700 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006701 NewClassTy = NewPT->getPointeeType();
6702 OldClassTy = OldPT->getPointeeType();
6703 }
Anders Carlsson7caa4cb2010-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 Carlsson8fb0b8a2009-05-14 19:52:19 +00006710 }
6711 }
Mike Stump11289f42009-09-09 15:08:12 +00006712
Anders Carlsson8fb0b8a2009-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 Stump11289f42009-09-09 15:08:12 +00006715 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-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 Stump11289f42009-09-09 15:08:12 +00006719
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006720 return true;
6721 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006722
Anders Carlssone60365b2009-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 Carlsson0c9dd842009-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 Carlssone60365b2009-12-31 18:34:24 +00006732 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006733 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006734
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006735 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-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 Stump11289f42009-09-09 15:08:12 +00006744
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006745 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006746 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-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 Carlsson8fb0b8a2009-05-14 19:52:19 +00006751 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6752 return true;
6753 }
6754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006756 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006757 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006758 Diag(New->getLocation(),
6759 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006760 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006761 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6762 return true;
6763 };
Mike Stump11289f42009-09-09 15:08:12 +00006764
Anders Carlsson8fb0b8a2009-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 Stump11289f42009-09-09 15:08:12 +00006774
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006775 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006776}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006777
Alexis Hunt96d5c762009-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 Gregor21920e372009-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 Gregor21920e372009-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 McCall1f4ee7b2009-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 Kyrtzidis3df19782009-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 McCall48871652010-08-21 09:40:31 +00006815void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006816 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006817 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006818
John McCall1f4ee7b2009-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 McCall6df5fef2009-12-19 10:49:29 +00006822 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006823}
6824
6825/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006826/// initializer for the out-of-line declaration 'D'.
6827void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006828 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006829 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006830
John McCall1f4ee7b2009-12-19 09:28:58 +00006831 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006832 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006833}
Douglas Gregor7bab5ff2009-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 McCall48871652010-08-21 09:40:31 +00006838DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-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 Gregor7bab5ff2009-11-25 00:27:52 +00006846 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006847 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6848 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-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 McCall48871652010-08-21 09:40:31 +00006861 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006862 if (!Dcl)
6863 return DeclResult();
6864
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006865 return Dcl;
6866}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006867
Douglas Gregor88d292c2010-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 Espindolae7113ca2010-03-10 02:19:29 +00006875 return;
6876
Douglas Gregor88d292c2010-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 Dunbar53217762010-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 Gregor88d292c2010-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 Dunbar0547ad32010-05-11 21:32:35 +00006898 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006899 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006900}
6901
Douglas Gregor88d292c2010-05-13 16:44:06 +00006902bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006903 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006904 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00006905
Douglas Gregor88d292c2010-05-13 16:44:06 +00006906 // Note: The VTableUses vector could grow as a result of marking
6907 // the members of a class as "used", so we check the size each
6908 // time through the loop and prefer indices (with are stable) to
6909 // iterators (which are not).
6910 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006911 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006912 if (!Class)
6913 continue;
6914
6915 SourceLocation Loc = VTableUses[I].second;
6916
6917 // If this class has a key function, but that key function is
6918 // defined in another translation unit, we don't need to emit the
6919 // vtable even though we're using it.
6920 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006921 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006922 switch (KeyFunction->getTemplateSpecializationKind()) {
6923 case TSK_Undeclared:
6924 case TSK_ExplicitSpecialization:
6925 case TSK_ExplicitInstantiationDeclaration:
6926 // The key function is in another translation unit.
6927 continue;
6928
6929 case TSK_ExplicitInstantiationDefinition:
6930 case TSK_ImplicitInstantiation:
6931 // We will be instantiating the key function.
6932 break;
6933 }
6934 } else if (!KeyFunction) {
6935 // If we have a class with no key function that is the subject
6936 // of an explicit instantiation declaration, suppress the
6937 // vtable; it will live with the explicit instantiation
6938 // definition.
6939 bool IsExplicitInstantiationDeclaration
6940 = Class->getTemplateSpecializationKind()
6941 == TSK_ExplicitInstantiationDeclaration;
6942 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6943 REnd = Class->redecls_end();
6944 R != REnd; ++R) {
6945 TemplateSpecializationKind TSK
6946 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6947 if (TSK == TSK_ExplicitInstantiationDeclaration)
6948 IsExplicitInstantiationDeclaration = true;
6949 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6950 IsExplicitInstantiationDeclaration = false;
6951 break;
6952 }
6953 }
6954
6955 if (IsExplicitInstantiationDeclaration)
6956 continue;
6957 }
6958
6959 // Mark all of the virtual members of this class as referenced, so
6960 // that we can build a vtable. Then, tell the AST consumer that a
6961 // vtable for this class is required.
6962 MarkVirtualMembersReferenced(Loc, Class);
6963 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6964 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6965
6966 // Optionally warn if we're emitting a weak vtable.
6967 if (Class->getLinkage() == ExternalLinkage &&
6968 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006969 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006970 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6971 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006972 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006973 VTableUses.clear();
6974
Anders Carlsson82fccd02009-12-07 08:24:59 +00006975 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006976}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006977
Rafael Espindola5b334082010-03-26 00:36:59 +00006978void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6979 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006980 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6981 e = RD->method_end(); i != e; ++i) {
6982 CXXMethodDecl *MD = *i;
6983
6984 // C++ [basic.def.odr]p2:
6985 // [...] A virtual member function is used if it is not pure. [...]
6986 if (MD->isVirtual() && !MD->isPure())
6987 MarkDeclarationReferenced(Loc, MD);
6988 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006989
6990 // Only classes that have virtual bases need a VTT.
6991 if (RD->getNumVBases() == 0)
6992 return;
6993
6994 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6995 e = RD->bases_end(); i != e; ++i) {
6996 const CXXRecordDecl *Base =
6997 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00006998 if (Base->getNumVBases() == 0)
6999 continue;
7000 MarkVirtualMembersReferenced(Loc, Base);
7001 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007002}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007003
7004/// SetIvarInitializers - This routine builds initialization ASTs for the
7005/// Objective-C implementation whose ivars need be initialized.
7006void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7007 if (!getLangOptions().CPlusPlus)
7008 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007009 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007010 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7011 CollectIvarsToConstructOrDestruct(OID, ivars);
7012 if (ivars.empty())
7013 return;
7014 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7015 for (unsigned i = 0; i < ivars.size(); i++) {
7016 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007017 if (Field->isInvalidDecl())
7018 continue;
7019
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007020 CXXBaseOrMemberInitializer *Member;
7021 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7022 InitializationKind InitKind =
7023 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7024
7025 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007026 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007027 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007028 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007029 // Note, MemberInit could actually come back empty if no initialization
7030 // is required (e.g., because it would call a trivial default constructor)
7031 if (!MemberInit.get() || MemberInit.isInvalid())
7032 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007033
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007034 Member =
7035 new (Context) CXXBaseOrMemberInitializer(Context,
7036 Field, SourceLocation(),
7037 SourceLocation(),
7038 MemberInit.takeAs<Expr>(),
7039 SourceLocation());
7040 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007041
7042 // Be sure that the destructor is accessible and is marked as referenced.
7043 if (const RecordType *RecordTy
7044 = Context.getBaseElementType(Field->getType())
7045 ->getAs<RecordType>()) {
7046 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007047 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007048 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7049 CheckDestructorAccess(Field->getLocation(), Destructor,
7050 PDiag(diag::err_access_dtor_ivar)
7051 << Context.getBaseElementType(Field->getType()));
7052 }
7053 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007054 }
7055 ObjCImplementation->setIvarInitializers(Context,
7056 AllToInit.data(), AllToInit.size());
7057 }
7058}