blob: 370def568e21ea6ec45049fe8a5db16b8ba3c81c [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000066 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000068 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000069 }
70
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitDeclRefExpr - Visit a reference to a declaration, to
72 /// determine whether this declaration can be used in the default
73 /// argument expression.
74 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000075 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000076 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
77 // C++ [dcl.fct.default]p9
78 // Default arguments are evaluated each time the function is
79 // called. The order of evaluation of function arguments is
80 // unspecified. Consequently, parameters of a function shall not
81 // be used in default argument expressions, even if they are not
82 // evaluated. Parameters of a function declared before a default
83 // argument expression are in scope and can hide namespace and
84 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000085 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000087 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000088 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000089 // C++ [dcl.fct.default]p7
90 // Local variables shall not be used in default argument
91 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000092 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000093 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000096 }
Chris Lattner8123a952008-04-10 02:22:51 +000097
Douglas Gregor3996f232008-11-04 13:41:56 +000098 return false;
99 }
Chris Lattner9e979552008-04-12 23:52:44 +0000100
Douglas Gregor796da182008-11-04 14:32:21 +0000101 /// VisitCXXThisExpr - Visit a C++ "this" expression.
102 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
103 // C++ [dcl.fct.default]p8:
104 // The keyword this shall not be used in a default argument of a
105 // member function.
106 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000107 diag::err_param_default_argument_references_this)
108 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000109 }
Chris Lattner8123a952008-04-10 02:22:51 +0000110}
111
Anders Carlssoned961f92009-08-25 02:29:20 +0000112bool
John McCall9ae2f072010-08-23 23:25:46 +0000113Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000114 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000115 if (RequireCompleteType(Param->getLocation(), Param->getType(),
116 diag::err_typecheck_decl_incomplete_type)) {
117 Param->setInvalidDecl();
118 return true;
119 }
120
Anders Carlssoned961f92009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
128 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000131 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000132 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000133 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000137
John McCallb4eb64d2010-10-08 02:01:28 +0000138 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000139 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 // Okay: add the default argument to the parameter
142 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000144 // We have already instantiated this parameter; provide each of the
145 // instantiations with the uninstantiated default argument.
146 UnparsedDefaultArgInstantiationsMap::iterator InstPos
147 = UnparsedDefaultArgInstantiations.find(Param);
148 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
149 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
150 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
151
152 // We're done tracking this parameter's instantiations.
153 UnparsedDefaultArgInstantiations.erase(InstPos);
154 }
155
Anders Carlsson9351c172009-08-25 03:18:48 +0000156 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000157}
158
Chris Lattner8123a952008-04-10 02:22:51 +0000159/// ActOnParamDefaultArgument - Check whether the default argument
160/// provided for a function parameter is well-formed. If so, attach it
161/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000162void
John McCalld226f652010-08-21 09:40:31 +0000163Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000164 Expr *DefaultArg) {
165 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000166 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000167
John McCalld226f652010-08-21 09:40:31 +0000168 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000169 UnparsedDefaultArgLocs.erase(Param);
170
Chris Lattner3d1cee32008-04-08 05:04:30 +0000171 // Default arguments are only permitted in C++
172 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000173 Diag(EqualLoc, diag::err_param_default_argument)
174 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000175 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176 return;
177 }
178
Douglas Gregor6f526752010-12-16 08:48:57 +0000179 // Check for unexpanded parameter packs.
180 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
181 Param->setInvalidDecl();
182 return;
183 }
184
Anders Carlsson66e30672009-08-25 01:02:06 +0000185 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000186 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
187 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000188 Param->setInvalidDecl();
189 return;
190 }
Mike Stump1eb44332009-09-09 15:08:12 +0000191
John McCall9ae2f072010-08-23 23:25:46 +0000192 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000193}
194
Douglas Gregor61366e92008-12-24 00:01:03 +0000195/// ActOnParamUnparsedDefaultArgument - We've seen a default
196/// argument for a function parameter, but we can't parse it yet
197/// because we're inside a class definition. Note that this default
198/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000199void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000200 SourceLocation EqualLoc,
201 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000202 if (!param)
203 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
John McCalld226f652010-08-21 09:40:31 +0000205 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000206 if (Param)
207 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Anders Carlsson5e300d12009-06-12 16:51:40 +0000209 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000210}
211
Douglas Gregor72b505b2008-12-16 21:30:33 +0000212/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
213/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000214void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000215 if (!param)
216 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000217
John McCalld226f652010-08-21 09:40:31 +0000218 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Anders Carlsson5e300d12009-06-12 16:51:40 +0000220 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Anders Carlsson5e300d12009-06-12 16:51:40 +0000222 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223}
224
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000225/// CheckExtraCXXDefaultArguments - Check for any extra default
226/// arguments in the declarator, which is not a function declaration
227/// or definition and therefore is not permitted to have default
228/// arguments. This routine should be invoked for every declarator
229/// that is not a function declaration or definition.
230void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
231 // C++ [dcl.fct.default]p3
232 // A default argument expression shall be specified only in the
233 // parameter-declaration-clause of a function declaration or in a
234 // template-parameter (14.1). It shall not be specified for a
235 // parameter pack. If it is specified in a
236 // parameter-declaration-clause, it shall not occur within a
237 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000238 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000239 DeclaratorChunk &chunk = D.getTypeObject(i);
240 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000241 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
242 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000243 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000244 if (Param->hasUnparsedDefaultArg()) {
245 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
248 delete Toks;
249 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000250 } else if (Param->getDefaultArg()) {
251 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
252 << Param->getDefaultArg()->getSourceRange();
253 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000254 }
255 }
256 }
257 }
258}
259
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260// MergeCXXFunctionDecl - Merge two declarations of the same C++
261// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000262// type. Subroutine of MergeFunctionDecl. Returns true if there was an
263// error, false otherwise.
264bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
265 bool Invalid = false;
266
Chris Lattner3d1cee32008-04-08 05:04:30 +0000267 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 // For non-template functions, default arguments can be added in
269 // later declarations of a function in the same
270 // scope. Declarations in different scopes have completely
271 // distinct sets of default arguments. That is, declarations in
272 // inner scopes do not acquire default arguments from
273 // declarations in outer scopes, and vice versa. In a given
274 // function declaration, all parameters subsequent to a
275 // parameter with a default argument shall have default
276 // arguments supplied in this or previous declarations. A
277 // default argument shall not be redefined by a later
278 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000279 //
280 // C++ [dcl.fct.default]p6:
281 // Except for member functions of class templates, the default arguments
282 // in a member function definition that appears outside of the class
283 // definition are added to the set of default arguments provided by the
284 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000285 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
286 ParmVarDecl *OldParam = Old->getParamDecl(p);
287 ParmVarDecl *NewParam = New->getParamDecl(p);
288
Douglas Gregor6cc15182009-09-11 18:44:32 +0000289 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000290 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
291 // hint here. Alternatively, we could walk the type-source information
292 // for NewParam to find the last source location in the type... but it
293 // isn't worth the effort right now. This is the kind of test case that
294 // is hard to get right:
295
296 // int f(int);
297 // void g(int (*fp)(int) = f);
298 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000299 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000300 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000301 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000302
303 // Look for the function declaration where the default argument was
304 // actually written, which may be a declaration prior to Old.
305 for (FunctionDecl *Older = Old->getPreviousDeclaration();
306 Older; Older = Older->getPreviousDeclaration()) {
307 if (!Older->getParamDecl(p)->hasDefaultArg())
308 break;
309
310 OldParam = Older->getParamDecl(p);
311 }
312
313 Diag(OldParam->getLocation(), diag::note_previous_definition)
314 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000315 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000316 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000317 // Merge the old default argument into the new parameter.
318 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000319 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000320 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000321 if (OldParam->hasUninstantiatedDefaultArg())
322 NewParam->setUninstantiatedDefaultArg(
323 OldParam->getUninstantiatedDefaultArg());
324 else
John McCall3d6c1782010-05-04 01:53:42 +0000325 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000326 } else if (NewParam->hasDefaultArg()) {
327 if (New->getDescribedFunctionTemplate()) {
328 // Paragraph 4, quoted above, only applies to non-template functions.
329 Diag(NewParam->getLocation(),
330 diag::err_param_default_argument_template_redecl)
331 << NewParam->getDefaultArgRange();
332 Diag(Old->getLocation(), diag::note_template_prev_declaration)
333 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000334 } else if (New->getTemplateSpecializationKind()
335 != TSK_ImplicitInstantiation &&
336 New->getTemplateSpecializationKind() != TSK_Undeclared) {
337 // C++ [temp.expr.spec]p21:
338 // Default function arguments shall not be specified in a declaration
339 // or a definition for one of the following explicit specializations:
340 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000341 // - the explicit specialization of a member function template;
342 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000343 // template where the class template specialization to which the
344 // member function specialization belongs is implicitly
345 // instantiated.
346 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
347 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
348 << New->getDeclName()
349 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000350 } else if (New->getDeclContext()->isDependentContext()) {
351 // C++ [dcl.fct.default]p6 (DR217):
352 // Default arguments for a member function of a class template shall
353 // be specified on the initial declaration of the member function
354 // within the class template.
355 //
356 // Reading the tea leaves a bit in DR217 and its reference to DR205
357 // leads me to the conclusion that one cannot add default function
358 // arguments for an out-of-line definition of a member function of a
359 // dependent type.
360 int WhichKind = 2;
361 if (CXXRecordDecl *Record
362 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
363 if (Record->getDescribedClassTemplate())
364 WhichKind = 0;
365 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
366 WhichKind = 1;
367 else
368 WhichKind = 2;
369 }
370
371 Diag(NewParam->getLocation(),
372 diag::err_param_default_argument_member_template_redecl)
373 << WhichKind
374 << NewParam->getDefaultArgRange();
375 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376 }
377 }
378
Douglas Gregore13ad832010-02-12 07:32:17 +0000379 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000380 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000381
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383}
384
385/// CheckCXXDefaultArguments - Verify that the default arguments for a
386/// function declaration are well-formed according to C++
387/// [dcl.fct.default].
388void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
389 unsigned NumParams = FD->getNumParams();
390 unsigned p;
391
392 // Find first parameter with a default argument
393 for (p = 0; p < NumParams; ++p) {
394 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000395 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 break;
397 }
398
399 // C++ [dcl.fct.default]p4:
400 // In a given function declaration, all parameters
401 // subsequent to a parameter with a default argument shall
402 // have default arguments supplied in this or previous
403 // declarations. A default argument shall not be redefined
404 // by a later declaration (not even to the same value).
405 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000406 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000408 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000409 if (Param->isInvalidDecl())
410 /* We already complained about this parameter. */;
411 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000412 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000413 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000414 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 else
Mike Stump1eb44332009-09-09 15:08:12 +0000416 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000417 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner3d1cee32008-04-08 05:04:30 +0000419 LastMissingDefaultArg = p;
420 }
421 }
422
423 if (LastMissingDefaultArg > 0) {
424 // Some default arguments were missing. Clear out all of the
425 // default arguments up to (and including) the last missing
426 // default argument, so that we leave the function parameters
427 // in a semantically valid state.
428 for (p = 0; p <= LastMissingDefaultArg; ++p) {
429 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000430 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000431 Param->setDefaultArg(0);
432 }
433 }
434 }
435}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000436
Douglas Gregorb48fe382008-10-31 09:07:45 +0000437/// isCurrentClassName - Determine whether the identifier II is the
438/// name of the class type currently being defined. In the case of
439/// nested classes, this will only return true if II is the name of
440/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000441bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
442 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000443 assert(getLangOptions().CPlusPlus && "No class names in C!");
444
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000445 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000446 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000447 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000448 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
449 } else
450 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
451
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000452 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000453 return &II == CurDecl->getIdentifier();
454 else
455 return false;
456}
457
Mike Stump1eb44332009-09-09 15:08:12 +0000458/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000459///
460/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
461/// and returns NULL otherwise.
462CXXBaseSpecifier *
463Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
464 SourceRange SpecifierRange,
465 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000466 TypeSourceInfo *TInfo,
467 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000468 QualType BaseType = TInfo->getType();
469
Douglas Gregor2943aed2009-03-03 04:44:36 +0000470 // C++ [class.union]p1:
471 // A union shall not have base classes.
472 if (Class->isUnion()) {
473 Diag(Class->getLocation(), diag::err_base_clause_on_union)
474 << SpecifierRange;
475 return 0;
476 }
477
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000478 if (EllipsisLoc.isValid() &&
479 !TInfo->getType()->containsUnexpandedParameterPack()) {
480 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
481 << TInfo->getTypeLoc().getSourceRange();
482 EllipsisLoc = SourceLocation();
483 }
484
Douglas Gregor2943aed2009-03-03 04:44:36 +0000485 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000486 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000487 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000488 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000489
490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000491
492 // Base specifiers must be record types.
493 if (!BaseType->isRecordType()) {
494 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
495 return 0;
496 }
497
498 // C++ [class.union]p1:
499 // A union shall not be used as a base class.
500 if (BaseType->isUnionType()) {
501 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
502 return 0;
503 }
504
505 // C++ [class.derived]p2:
506 // The class-name in a base-specifier shall not be an incompletely
507 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000508 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000509 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000510 << SpecifierRange)) {
511 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000512 return 0;
John McCall572fc622010-08-17 07:23:57 +0000513 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000514
Eli Friedman1d954f62009-08-15 21:55:26 +0000515 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000516 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000517 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000518 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000519 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000520 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
521 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000522
Anders Carlssondfc2f102011-01-22 17:51:53 +0000523 // C++ [class.derived]p2:
524 // If a class is marked with the class-virt-specifier final and it appears
525 // as a base-type-specifier in a base-clause (10 class.derived), the program
526 // is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000527 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000528 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
529 << CXXBaseDecl->getDeclName();
530 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
531 << CXXBaseDecl->getDeclName();
532 return 0;
533 }
534
John McCall572fc622010-08-17 07:23:57 +0000535 if (BaseDecl->isInvalidDecl())
536 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000537
538 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000539 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000540 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000541 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000542}
543
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000544/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
545/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000546/// example:
547/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000548/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000549BaseResult
John McCalld226f652010-08-21 09:40:31 +0000550Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000551 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000552 ParsedType basetype, SourceLocation BaseLoc,
553 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000554 if (!classdecl)
555 return true;
556
Douglas Gregor40808ce2009-03-09 23:48:35 +0000557 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000558 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000559 if (!Class)
560 return true;
561
Nick Lewycky56062202010-07-26 16:56:01 +0000562 TypeSourceInfo *TInfo = 0;
563 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000564
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000565 if (EllipsisLoc.isInvalid() &&
566 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000567 UPPC_BaseType))
568 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000569
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000571 Virtual, Access, TInfo,
572 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000576}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000577
Douglas Gregor2943aed2009-03-03 04:44:36 +0000578/// \brief Performs the actual work of attaching the given base class
579/// specifiers to a C++ class.
580bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
581 unsigned NumBases) {
582 if (NumBases == 0)
583 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000584
585 // Used to keep track of which base types we have already seen, so
586 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000587 // that the key is always the unqualified canonical type of the base
588 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000589 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
590
591 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000592 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000594 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000595 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000597 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000598 if (!Class->hasObjectMember()) {
599 if (const RecordType *FDTTy =
600 NewBaseType.getTypePtr()->getAs<RecordType>())
601 if (FDTTy->getDecl()->hasObjectMember())
602 Class->setHasObjectMember(true);
603 }
604
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605 if (KnownBaseTypes[NewBaseType]) {
606 // C++ [class.mi]p3:
607 // A class shall not be specified as a direct base class of a
608 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000610 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000611 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000612 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613
614 // Delete the duplicate base class specifier; we're going to
615 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000616 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617
618 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000619 } else {
620 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 KnownBaseTypes[NewBaseType] = Bases[idx];
622 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000623 }
624 }
625
626 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000627 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the remaining (good) base class specifiers, since their
630 // data has been copied into the CXXRecordDecl.
631 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000632 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633
634 return Invalid;
635}
636
637/// ActOnBaseSpecifiers - Attach the given base specifiers to the
638/// class, after checking whether there are any duplicate base
639/// classes.
John McCalld226f652010-08-21 09:40:31 +0000640void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000641 unsigned NumBases) {
642 if (!ClassDecl || !Bases || !NumBases)
643 return;
644
645 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000646 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000647 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000648}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000649
John McCall3cb0ebd2010-03-10 03:28:59 +0000650static CXXRecordDecl *GetClassForType(QualType T) {
651 if (const RecordType *RT = T->getAs<RecordType>())
652 return cast<CXXRecordDecl>(RT->getDecl());
653 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
654 return ICT->getDecl();
655 else
656 return 0;
657}
658
Douglas Gregora8f32e02009-10-06 17:59:45 +0000659/// \brief Determine whether the type \p Derived is a C++ class that is
660/// derived from the type \p Base.
661bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
662 if (!getLangOptions().CPlusPlus)
663 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000664
665 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
666 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000667 return false;
668
John McCall3cb0ebd2010-03-10 03:28:59 +0000669 CXXRecordDecl *BaseRD = GetClassForType(Base);
670 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000671 return false;
672
John McCall86ff3082010-02-04 22:26:26 +0000673 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
674 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000675}
676
677/// \brief Determine whether the type \p Derived is a C++ class that is
678/// derived from the type \p Base.
679bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
680 if (!getLangOptions().CPlusPlus)
681 return false;
682
John McCall3cb0ebd2010-03-10 03:28:59 +0000683 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
684 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000685 return false;
686
John McCall3cb0ebd2010-03-10 03:28:59 +0000687 CXXRecordDecl *BaseRD = GetClassForType(Base);
688 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000689 return false;
690
Douglas Gregora8f32e02009-10-06 17:59:45 +0000691 return DerivedRD->isDerivedFrom(BaseRD, Paths);
692}
693
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000694void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000695 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000696 assert(BasePathArray.empty() && "Base path array must be empty!");
697 assert(Paths.isRecordingPaths() && "Must record paths!");
698
699 const CXXBasePath &Path = Paths.front();
700
701 // We first go backward and check if we have a virtual base.
702 // FIXME: It would be better if CXXBasePath had the base specifier for
703 // the nearest virtual base.
704 unsigned Start = 0;
705 for (unsigned I = Path.size(); I != 0; --I) {
706 if (Path[I - 1].Base->isVirtual()) {
707 Start = I - 1;
708 break;
709 }
710 }
711
712 // Now add all bases.
713 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000714 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000715}
716
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000717/// \brief Determine whether the given base path includes a virtual
718/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000719bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
720 for (CXXCastPath::const_iterator B = BasePath.begin(),
721 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000722 B != BEnd; ++B)
723 if ((*B)->isVirtual())
724 return true;
725
726 return false;
727}
728
Douglas Gregora8f32e02009-10-06 17:59:45 +0000729/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
730/// conversion (where Derived and Base are class types) is
731/// well-formed, meaning that the conversion is unambiguous (and
732/// that all of the base classes are accessible). Returns true
733/// and emits a diagnostic if the code is ill-formed, returns false
734/// otherwise. Loc is the location where this routine should point to
735/// if there is an error, and Range is the source range to highlight
736/// if there is an error.
737bool
738Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000739 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000740 unsigned AmbigiousBaseConvID,
741 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000742 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000743 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000744 // First, determine whether the path from Derived to Base is
745 // ambiguous. This is slightly more expensive than checking whether
746 // the Derived to Base conversion exists, because here we need to
747 // explore multiple paths to determine if there is an ambiguity.
748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
749 /*DetectVirtual=*/false);
750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
751 assert(DerivationOkay &&
752 "Can only be used with a derived-to-base conversion");
753 (void)DerivationOkay;
754
755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000756 if (InaccessibleBaseID) {
757 // Check that the base class can be accessed.
758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
759 InaccessibleBaseID)) {
760 case AR_inaccessible:
761 return true;
762 case AR_accessible:
763 case AR_dependent:
764 case AR_delayed:
765 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000766 }
John McCall6b2accb2010-02-10 09:31:12 +0000767 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000768
769 // Build a base path if necessary.
770 if (BasePath)
771 BuildBasePathArray(Paths, *BasePath);
772 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000773 }
774
775 // We know that the derived-to-base conversion is ambiguous, and
776 // we're going to produce a diagnostic. Perform the derived-to-base
777 // search just one more time to compute all of the possible paths so
778 // that we can print them out. This is more expensive than any of
779 // the previous derived-to-base checks we've done, but at this point
780 // performance isn't as much of an issue.
781 Paths.clear();
782 Paths.setRecordingPaths(true);
783 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
784 assert(StillOkay && "Can only be used with a derived-to-base conversion");
785 (void)StillOkay;
786
787 // Build up a textual representation of the ambiguous paths, e.g.,
788 // D -> B -> A, that will be used to illustrate the ambiguous
789 // conversions in the diagnostic. We only print one of the paths
790 // to each base class subobject.
791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
792
793 Diag(Loc, AmbigiousBaseConvID)
794 << Derived << Base << PathDisplayStr << Range << Name;
795 return true;
796}
797
798bool
799Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000800 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000801 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000802 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000803 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000804 IgnoreAccess ? 0
805 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000807 Loc, Range, DeclarationName(),
808 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000809}
810
811
812/// @brief Builds a string representing ambiguous paths from a
813/// specific derived class to different subobjects of the same base
814/// class.
815///
816/// This function builds a string that can be used in error messages
817/// to show the different paths that one can take through the
818/// inheritance hierarchy to go from the derived class to different
819/// subobjects of a base class. The result looks something like this:
820/// @code
821/// struct D -> struct B -> struct A
822/// struct D -> struct C -> struct A
823/// @endcode
824std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
825 std::string PathDisplayStr;
826 std::set<unsigned> DisplayedPaths;
827 for (CXXBasePaths::paths_iterator Path = Paths.begin();
828 Path != Paths.end(); ++Path) {
829 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
830 // We haven't displayed a path to this particular base
831 // class subobject yet.
832 PathDisplayStr += "\n ";
833 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
834 for (CXXBasePath::const_iterator Element = Path->begin();
835 Element != Path->end(); ++Element)
836 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
837 }
838 }
839
840 return PathDisplayStr;
841}
842
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000843//===----------------------------------------------------------------------===//
844// C++ class member Handling
845//===----------------------------------------------------------------------===//
846
Abramo Bagnara6206d532010-06-05 05:09:32 +0000847/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000848Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
849 SourceLocation ASLoc,
850 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000851 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000852 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000853 ASLoc, ColonLoc);
854 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000855 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000856}
857
Anders Carlsson9e682d92011-01-20 05:57:14 +0000858/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000859void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000860 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
861 if (!MD || !MD->isVirtual())
862 return;
863
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000864 if (MD->isDependentContext())
865 return;
866
Anders Carlsson9e682d92011-01-20 05:57:14 +0000867 // C++0x [class.virtual]p3:
868 // If a virtual function is marked with the virt-specifier override and does
869 // not override a member function of a base class,
870 // the program is ill-formed.
871 bool HasOverriddenMethods =
872 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000873 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000874 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000875 diag::err_function_marked_override_not_overriding)
876 << MD->getDeclName();
877 return;
878 }
Anders Carlssonaa23d282011-01-22 22:23:37 +0000879
880 // C++0x [class.derived]p8:
881 // In a class definition marked with the class-virt-specifier explicit,
882 // if a virtual member function that is neither implicitly-declared nor a
883 // destructor overrides a member function of a base class and it is not
884 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000885 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
886 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlssonaa23d282011-01-22 22:23:37 +0000887 llvm::SmallVector<const CXXMethodDecl*, 4>
888 OverriddenMethods(MD->begin_overridden_methods(),
889 MD->end_overridden_methods());
890
891 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
892 << MD->getDeclName()
893 << (unsigned)OverriddenMethods.size();
894
895 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
896 Diag(OverriddenMethods[I]->getLocation(),
897 diag::note_overridden_virtual_function);
898 }
Anders Carlsson9e682d92011-01-20 05:57:14 +0000899}
900
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000901/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
902/// function overrides a virtual member function marked 'final', according to
903/// C++0x [class.virtual]p3.
904bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
905 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000906 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000907 return false;
908
909 Diag(New->getLocation(), diag::err_final_function_overridden)
910 << New->getDeclName();
911 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
912 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000913}
914
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000915/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
916/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
917/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000918/// any.
John McCalld226f652010-08-21 09:40:31 +0000919Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000920Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000921 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000922 ExprTy *BW, const VirtSpecifiers &VS,
923 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000924 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000925 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000926 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
927 DeclarationName Name = NameInfo.getName();
928 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000929
930 // For anonymous bitfields, the location should point to the type.
931 if (Loc.isInvalid())
932 Loc = D.getSourceRange().getBegin();
933
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000934 Expr *BitWidth = static_cast<Expr*>(BW);
935 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000936
John McCall4bde1e12010-06-04 08:34:12 +0000937 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000938 assert(!DS.isFriendSpecified());
939
John McCall4bde1e12010-06-04 08:34:12 +0000940 bool isFunc = false;
941 if (D.isFunctionDeclarator())
942 isFunc = true;
943 else if (D.getNumTypeObjects() == 0 &&
944 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000945 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000946 isFunc = TDType->isFunctionType();
947 }
948
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949 // C++ 9.2p6: A member shall not be declared to have automatic storage
950 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000951 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
952 // data members and cannot be applied to names declared const or static,
953 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000954 switch (DS.getStorageClassSpec()) {
955 case DeclSpec::SCS_unspecified:
956 case DeclSpec::SCS_typedef:
957 case DeclSpec::SCS_static:
958 // FALL THROUGH.
959 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000960 case DeclSpec::SCS_mutable:
961 if (isFunc) {
962 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000963 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000964 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000965 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Sebastian Redla11f42f2008-11-17 23:24:37 +0000967 // FIXME: It would be nicer if the keyword was ignored only for this
968 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000969 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000970 }
971 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000972 default:
973 if (DS.getStorageClassSpecLoc().isValid())
974 Diag(DS.getStorageClassSpecLoc(),
975 diag::err_storageclass_invalid_for_member);
976 else
977 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
978 D.getMutableDeclSpec().ClearStorageClassSpecs();
979 }
980
Sebastian Redl669d5d72008-11-14 23:42:31 +0000981 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
982 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000983 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000984
985 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000986 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000987 CXXScopeSpec &SS = D.getCXXScopeSpec();
988
989
990 if (SS.isSet() && !SS.isInvalid()) {
991 // The user provided a superfluous scope specifier inside a class
992 // definition:
993 //
994 // class X {
995 // int X::member;
996 // };
997 DeclContext *DC = 0;
998 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
999 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1000 << Name << FixItHint::CreateRemoval(SS.getRange());
1001 else
1002 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1003 << Name << SS.getRange();
1004
1005 SS.clear();
1006 }
1007
Douglas Gregor37b372b2009-08-20 22:52:58 +00001008 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001009 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001010 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1011 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001012 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001013 } else {
John McCalld226f652010-08-21 09:40:31 +00001014 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001015 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001016 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001017 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001018
1019 // Non-instance-fields can't have a bitfield.
1020 if (BitWidth) {
1021 if (Member->isInvalidDecl()) {
1022 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001023 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001024 // C++ 9.6p3: A bit-field shall not be a static member.
1025 // "static member 'A' cannot be a bit-field"
1026 Diag(Loc, diag::err_static_not_bitfield)
1027 << Name << BitWidth->getSourceRange();
1028 } else if (isa<TypedefDecl>(Member)) {
1029 // "typedef member 'x' cannot be a bit-field"
1030 Diag(Loc, diag::err_typedef_not_bitfield)
1031 << Name << BitWidth->getSourceRange();
1032 } else {
1033 // A function typedef ("typedef int f(); f a;").
1034 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1035 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001036 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001037 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner8b963ef2009-03-05 23:01:03 +00001040 BitWidth = 0;
1041 Member->setInvalidDecl();
1042 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001043
1044 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregor37b372b2009-08-20 22:52:58 +00001046 // If we have declared a member function template, set the access of the
1047 // templated declaration as well.
1048 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1049 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001050 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001051
Anders Carlssonaae5af22011-01-20 04:34:22 +00001052 if (VS.isOverrideSpecified()) {
1053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1054 if (!MD || !MD->isVirtual()) {
1055 Diag(Member->getLocStart(),
1056 diag::override_keyword_only_allowed_on_virtual_member_functions)
1057 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001058 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001059 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001060 }
1061 if (VS.isFinalSpecified()) {
1062 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1063 if (!MD || !MD->isVirtual()) {
1064 Diag(Member->getLocStart(),
1065 diag::override_keyword_only_allowed_on_virtual_member_functions)
1066 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001067 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001068 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001069 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001070
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001071 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001072
Douglas Gregor10bd3682008-11-17 22:58:34 +00001073 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001074
Douglas Gregor021c3b32009-03-11 23:00:04 +00001075 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001076 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001077 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001078 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001079
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001080 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001081 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001082 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001083 }
John McCalld226f652010-08-21 09:40:31 +00001084 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001085}
1086
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001087/// \brief Find the direct and/or virtual base specifiers that
1088/// correspond to the given base type, for use in base initialization
1089/// within a constructor.
1090static bool FindBaseInitializer(Sema &SemaRef,
1091 CXXRecordDecl *ClassDecl,
1092 QualType BaseType,
1093 const CXXBaseSpecifier *&DirectBaseSpec,
1094 const CXXBaseSpecifier *&VirtualBaseSpec) {
1095 // First, check for a direct base class.
1096 DirectBaseSpec = 0;
1097 for (CXXRecordDecl::base_class_const_iterator Base
1098 = ClassDecl->bases_begin();
1099 Base != ClassDecl->bases_end(); ++Base) {
1100 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1101 // We found a direct base of this type. That's what we're
1102 // initializing.
1103 DirectBaseSpec = &*Base;
1104 break;
1105 }
1106 }
1107
1108 // Check for a virtual base class.
1109 // FIXME: We might be able to short-circuit this if we know in advance that
1110 // there are no virtual bases.
1111 VirtualBaseSpec = 0;
1112 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1113 // We haven't found a base yet; search the class hierarchy for a
1114 // virtual base class.
1115 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1116 /*DetectVirtual=*/false);
1117 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1118 BaseType, Paths)) {
1119 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1120 Path != Paths.end(); ++Path) {
1121 if (Path->back().Base->isVirtual()) {
1122 VirtualBaseSpec = Path->back().Base;
1123 break;
1124 }
1125 }
1126 }
1127 }
1128
1129 return DirectBaseSpec || VirtualBaseSpec;
1130}
1131
Douglas Gregor7ad83902008-11-05 04:29:56 +00001132/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001133MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001134Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001135 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001136 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001137 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001138 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001139 SourceLocation IdLoc,
1140 SourceLocation LParenLoc,
1141 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001142 SourceLocation RParenLoc,
1143 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001144 if (!ConstructorD)
1145 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001147 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
1149 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001150 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001151 if (!Constructor) {
1152 // The user wrote a constructor initializer on a function that is
1153 // not a C++ constructor. Ignore the error for now, because we may
1154 // have more member initializers coming; we'll diagnose it just
1155 // once in ActOnMemInitializers.
1156 return true;
1157 }
1158
1159 CXXRecordDecl *ClassDecl = Constructor->getParent();
1160
1161 // C++ [class.base.init]p2:
1162 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001163 // constructor's class and, if not found in that scope, are looked
1164 // up in the scope containing the constructor's definition.
1165 // [Note: if the constructor's class contains a member with the
1166 // same name as a direct or virtual base class of the class, a
1167 // mem-initializer-id naming the member or base class and composed
1168 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001169 // mem-initializer-id for the hidden base class may be specified
1170 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001171 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001172 // Look for a member, first.
1173 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001174 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001175 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001176 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001177 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001178
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001179 if (Member) {
1180 if (EllipsisLoc.isValid())
1181 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1182 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1183
Francois Pichet00eb3f92010-12-04 09:14:42 +00001184 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001185 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001186 }
1187
Francois Pichet00eb3f92010-12-04 09:14:42 +00001188 // Handle anonymous union case.
1189 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001190 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1191 if (EllipsisLoc.isValid())
1192 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1193 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1194
Francois Pichet00eb3f92010-12-04 09:14:42 +00001195 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1196 NumArgs, IdLoc,
1197 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001198 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001199 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001200 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001201 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001202 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001203 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001204
1205 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001206 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001207 } else {
1208 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1209 LookupParsedName(R, S, &SS);
1210
1211 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1212 if (!TyD) {
1213 if (R.isAmbiguous()) return true;
1214
John McCallfd225442010-04-09 19:01:14 +00001215 // We don't want access-control diagnostics here.
1216 R.suppressDiagnostics();
1217
Douglas Gregor7a886e12010-01-19 06:46:48 +00001218 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1219 bool NotUnknownSpecialization = false;
1220 DeclContext *DC = computeDeclContext(SS, false);
1221 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1222 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1223
1224 if (!NotUnknownSpecialization) {
1225 // When the scope specifier can refer to a member of an unknown
1226 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001227 BaseType = CheckTypenameType(ETK_None,
1228 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001229 *MemberOrBase, SourceLocation(),
1230 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001231 if (BaseType.isNull())
1232 return true;
1233
Douglas Gregor7a886e12010-01-19 06:46:48 +00001234 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001235 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001236 }
1237 }
1238
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001239 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001240 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001241 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1242 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001243 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001244 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001245 // We have found a non-static data member with a similar
1246 // name to what was typed; complain and initialize that
1247 // member.
1248 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1249 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001250 << FixItHint::CreateReplacement(R.getNameLoc(),
1251 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001252 Diag(Member->getLocation(), diag::note_previous_decl)
1253 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001254
1255 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1256 LParenLoc, RParenLoc);
1257 }
1258 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1259 const CXXBaseSpecifier *DirectBaseSpec;
1260 const CXXBaseSpecifier *VirtualBaseSpec;
1261 if (FindBaseInitializer(*this, ClassDecl,
1262 Context.getTypeDeclType(Type),
1263 DirectBaseSpec, VirtualBaseSpec)) {
1264 // We have found a direct or virtual base class with a
1265 // similar name to what was typed; complain and initialize
1266 // that base class.
1267 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1268 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001269 << FixItHint::CreateReplacement(R.getNameLoc(),
1270 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001271
1272 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1273 : VirtualBaseSpec;
1274 Diag(BaseSpec->getSourceRange().getBegin(),
1275 diag::note_base_class_specified_here)
1276 << BaseSpec->getType()
1277 << BaseSpec->getSourceRange();
1278
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001279 TyD = Type;
1280 }
1281 }
1282 }
1283
Douglas Gregor7a886e12010-01-19 06:46:48 +00001284 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001285 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1286 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1287 return true;
1288 }
John McCall2b194412009-12-21 10:41:20 +00001289 }
1290
Douglas Gregor7a886e12010-01-19 06:46:48 +00001291 if (BaseType.isNull()) {
1292 BaseType = Context.getTypeDeclType(TyD);
1293 if (SS.isSet()) {
1294 NestedNameSpecifier *Qualifier =
1295 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001296
Douglas Gregor7a886e12010-01-19 06:46:48 +00001297 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001298 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001299 }
John McCall2b194412009-12-21 10:41:20 +00001300 }
1301 }
Mike Stump1eb44332009-09-09 15:08:12 +00001302
John McCalla93c9342009-12-07 02:54:59 +00001303 if (!TInfo)
1304 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001305
John McCalla93c9342009-12-07 02:54:59 +00001306 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001307 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001308}
1309
John McCallb4190042009-11-04 23:02:40 +00001310/// Checks an initializer expression for use of uninitialized fields, such as
1311/// containing the field that is being initialized. Returns true if there is an
1312/// uninitialized field was used an updates the SourceLocation parameter; false
1313/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001314static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001315 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001316 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001317 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1318
Nick Lewycky43ad1822010-06-15 07:32:55 +00001319 if (isa<CallExpr>(S)) {
1320 // Do not descend into function calls or constructors, as the use
1321 // of an uninitialized field may be valid. One would have to inspect
1322 // the contents of the function/ctor to determine if it is safe or not.
1323 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1324 // may be safe, depending on what the function/ctor does.
1325 return false;
1326 }
1327 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1328 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001329
1330 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1331 // The member expression points to a static data member.
1332 assert(VD->isStaticDataMember() &&
1333 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001334 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001335 return false;
1336 }
1337
1338 if (isa<EnumConstantDecl>(RhsField)) {
1339 // The member expression points to an enum.
1340 return false;
1341 }
1342
John McCallb4190042009-11-04 23:02:40 +00001343 if (RhsField == LhsField) {
1344 // Initializing a field with itself. Throw a warning.
1345 // But wait; there are exceptions!
1346 // Exception #1: The field may not belong to this record.
1347 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001348 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001349 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1350 // Even though the field matches, it does not belong to this record.
1351 return false;
1352 }
1353 // None of the exceptions triggered; return true to indicate an
1354 // uninitialized field was used.
1355 *L = ME->getMemberLoc();
1356 return true;
1357 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001358 } else if (isa<SizeOfAlignOfExpr>(S)) {
1359 // sizeof/alignof doesn't reference contents, do not warn.
1360 return false;
1361 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1362 // address-of doesn't reference contents (the pointer may be dereferenced
1363 // in the same expression but it would be rare; and weird).
1364 if (UOE->getOpcode() == UO_AddrOf)
1365 return false;
John McCallb4190042009-11-04 23:02:40 +00001366 }
John McCall7502c1d2011-02-13 04:07:26 +00001367 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001368 if (!*it) {
1369 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001370 continue;
1371 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001372 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1373 return true;
John McCallb4190042009-11-04 23:02:40 +00001374 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001375 return false;
John McCallb4190042009-11-04 23:02:40 +00001376}
1377
John McCallf312b1e2010-08-26 23:41:50 +00001378MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001379Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001380 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001381 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001382 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001383 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1384 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1385 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001386 "Member must be a FieldDecl or IndirectFieldDecl");
1387
Douglas Gregor464b2f02010-11-05 22:21:31 +00001388 if (Member->isInvalidDecl())
1389 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001390
John McCallb4190042009-11-04 23:02:40 +00001391 // Diagnose value-uses of fields to initialize themselves, e.g.
1392 // foo(foo)
1393 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001394 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001395 for (unsigned i = 0; i < NumArgs; ++i) {
1396 SourceLocation L;
1397 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1398 // FIXME: Return true in the case when other fields are used before being
1399 // uninitialized. For example, let this field be the i'th field. When
1400 // initializing the i'th field, throw a warning if any of the >= i'th
1401 // fields are used, as they are not yet initialized.
1402 // Right now we are only handling the case where the i'th field uses
1403 // itself in its initializer.
1404 Diag(L, diag::warn_field_is_uninit);
1405 }
1406 }
1407
Eli Friedman59c04372009-07-29 19:44:27 +00001408 bool HasDependentArg = false;
1409 for (unsigned i = 0; i < NumArgs; i++)
1410 HasDependentArg |= Args[i]->isTypeDependent();
1411
Chandler Carruth894aed92010-12-06 09:23:57 +00001412 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001413 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001414 // Can't check initialization for a member of dependent type or when
1415 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001416 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1417 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001418
1419 // Erase any temporaries within this evaluation context; we're not
1420 // going to track them in the AST, since we'll be rebuilding the
1421 // ASTs during template instantiation.
1422 ExprTemporaries.erase(
1423 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1424 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001425 } else {
1426 // Initialize the member.
1427 InitializedEntity MemberEntity =
1428 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1429 : InitializedEntity::InitializeMember(IndirectMember, 0);
1430 InitializationKind Kind =
1431 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001432
Chandler Carruth894aed92010-12-06 09:23:57 +00001433 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1434
1435 ExprResult MemberInit =
1436 InitSeq.Perform(*this, MemberEntity, Kind,
1437 MultiExprArg(*this, Args, NumArgs), 0);
1438 if (MemberInit.isInvalid())
1439 return true;
1440
1441 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1442
1443 // C++0x [class.base.init]p7:
1444 // The initialization of each base and member constitutes a
1445 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001446 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001447 if (MemberInit.isInvalid())
1448 return true;
1449
1450 // If we are in a dependent context, template instantiation will
1451 // perform this type-checking again. Just save the arguments that we
1452 // received in a ParenListExpr.
1453 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1454 // of the information that we have about the member
1455 // initializer. However, deconstructing the ASTs is a dicey process,
1456 // and this approach is far more likely to get the corner cases right.
1457 if (CurContext->isDependentContext())
1458 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1459 RParenLoc);
1460 else
1461 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001462 }
1463
Chandler Carruth894aed92010-12-06 09:23:57 +00001464 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001465 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001466 IdLoc, LParenLoc, Init,
1467 RParenLoc);
1468 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001469 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001470 IdLoc, LParenLoc, Init,
1471 RParenLoc);
1472 }
Eli Friedman59c04372009-07-29 19:44:27 +00001473}
1474
John McCallf312b1e2010-08-26 23:41:50 +00001475MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001476Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1477 Expr **Args, unsigned NumArgs,
1478 SourceLocation LParenLoc,
1479 SourceLocation RParenLoc,
1480 CXXRecordDecl *ClassDecl,
1481 SourceLocation EllipsisLoc) {
1482 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1483 if (!LangOpts.CPlusPlus0x)
1484 return Diag(Loc, diag::err_delegation_0x_only)
1485 << TInfo->getTypeLoc().getLocalSourceRange();
1486
1487 return Diag(Loc, diag::err_delegation_unimplemented)
1488 << TInfo->getTypeLoc().getLocalSourceRange();
1489}
1490
1491MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001492Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001493 Expr **Args, unsigned NumArgs,
1494 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001495 CXXRecordDecl *ClassDecl,
1496 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001497 bool HasDependentArg = false;
1498 for (unsigned i = 0; i < NumArgs; i++)
1499 HasDependentArg |= Args[i]->isTypeDependent();
1500
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001501 SourceLocation BaseLoc
1502 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1503
1504 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1505 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1506 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1507
1508 // C++ [class.base.init]p2:
1509 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001510 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001511 // of that class, the mem-initializer is ill-formed. A
1512 // mem-initializer-list can initialize a base class using any
1513 // name that denotes that base class type.
1514 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1515
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001516 if (EllipsisLoc.isValid()) {
1517 // This is a pack expansion.
1518 if (!BaseType->containsUnexpandedParameterPack()) {
1519 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1520 << SourceRange(BaseLoc, RParenLoc);
1521
1522 EllipsisLoc = SourceLocation();
1523 }
1524 } else {
1525 // Check for any unexpanded parameter packs.
1526 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1527 return true;
1528
1529 for (unsigned I = 0; I != NumArgs; ++I)
1530 if (DiagnoseUnexpandedParameterPack(Args[I]))
1531 return true;
1532 }
1533
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001534 // Check for direct and virtual base classes.
1535 const CXXBaseSpecifier *DirectBaseSpec = 0;
1536 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1537 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001538 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1539 BaseType))
1540 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1541 LParenLoc, RParenLoc, ClassDecl,
1542 EllipsisLoc);
1543
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001544 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1545 VirtualBaseSpec);
1546
1547 // C++ [base.class.init]p2:
1548 // Unless the mem-initializer-id names a nonstatic data member of the
1549 // constructor's class or a direct or virtual base of that class, the
1550 // mem-initializer is ill-formed.
1551 if (!DirectBaseSpec && !VirtualBaseSpec) {
1552 // If the class has any dependent bases, then it's possible that
1553 // one of those types will resolve to the same type as
1554 // BaseType. Therefore, just treat this as a dependent base
1555 // class initialization. FIXME: Should we try to check the
1556 // initialization anyway? It seems odd.
1557 if (ClassDecl->hasAnyDependentBases())
1558 Dependent = true;
1559 else
1560 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1561 << BaseType << Context.getTypeDeclType(ClassDecl)
1562 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1563 }
1564 }
1565
1566 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001567 // Can't check initialization for a base of dependent type or when
1568 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001569 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001570 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1571 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001572
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001573 // Erase any temporaries within this evaluation context; we're not
1574 // going to track them in the AST, since we'll be rebuilding the
1575 // ASTs during template instantiation.
1576 ExprTemporaries.erase(
1577 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1578 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Sean Huntcbb67482011-01-08 20:30:50 +00001580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001581 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001582 LParenLoc,
1583 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001584 RParenLoc,
1585 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001586 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001587
1588 // C++ [base.class.init]p2:
1589 // If a mem-initializer-id is ambiguous because it designates both
1590 // a direct non-virtual base class and an inherited virtual base
1591 // class, the mem-initializer is ill-formed.
1592 if (DirectBaseSpec && VirtualBaseSpec)
1593 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001594 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001595
1596 CXXBaseSpecifier *BaseSpec
1597 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1598 if (!BaseSpec)
1599 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1600
1601 // Initialize the base.
1602 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001603 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001604 InitializationKind Kind =
1605 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1606
1607 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1608
John McCall60d7b3a2010-08-24 06:29:42 +00001609 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001611 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001612 if (BaseInit.isInvalid())
1613 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001614
1615 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001616
1617 // C++0x [class.base.init]p7:
1618 // The initialization of each base and member constitutes a
1619 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001620 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001621 if (BaseInit.isInvalid())
1622 return true;
1623
1624 // If we are in a dependent context, template instantiation will
1625 // perform this type-checking again. Just save the arguments that we
1626 // received in a ParenListExpr.
1627 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1628 // of the information that we have about the base
1629 // initializer. However, deconstructing the ASTs is a dicey process,
1630 // and this approach is far more likely to get the corner cases right.
1631 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001632 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001633 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1634 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001635 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001636 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001637 LParenLoc,
1638 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001639 RParenLoc,
1640 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001641 }
1642
Sean Huntcbb67482011-01-08 20:30:50 +00001643 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001644 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001645 LParenLoc,
1646 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001647 RParenLoc,
1648 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001649}
1650
Anders Carlssone5ef7402010-04-23 03:10:23 +00001651/// ImplicitInitializerKind - How an implicit base or member initializer should
1652/// initialize its base or member.
1653enum ImplicitInitializerKind {
1654 IIK_Default,
1655 IIK_Copy,
1656 IIK_Move
1657};
1658
Anders Carlssondefefd22010-04-23 02:00:02 +00001659static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001660BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001661 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001662 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001663 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001664 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001665 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001666 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1667 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001668
John McCall60d7b3a2010-08-24 06:29:42 +00001669 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001670
1671 switch (ImplicitInitKind) {
1672 case IIK_Default: {
1673 InitializationKind InitKind
1674 = InitializationKind::CreateDefault(Constructor->getLocation());
1675 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1676 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001677 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001678 break;
1679 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001680
Anders Carlssone5ef7402010-04-23 03:10:23 +00001681 case IIK_Copy: {
1682 ParmVarDecl *Param = Constructor->getParamDecl(0);
1683 QualType ParamType = Param->getType().getNonReferenceType();
1684
1685 Expr *CopyCtorArg =
1686 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001687 Constructor->getLocation(), ParamType,
1688 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001689
Anders Carlssonc7957502010-04-24 22:02:54 +00001690 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001691 QualType ArgTy =
1692 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1693 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001694
1695 CXXCastPath BasePath;
1696 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001697 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001698 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001699 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001700
Anders Carlssone5ef7402010-04-23 03:10:23 +00001701 InitializationKind InitKind
1702 = InitializationKind::CreateDirect(Constructor->getLocation(),
1703 SourceLocation(), SourceLocation());
1704 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1705 &CopyCtorArg, 1);
1706 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001707 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001708 break;
1709 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001710
Anders Carlssone5ef7402010-04-23 03:10:23 +00001711 case IIK_Move:
1712 assert(false && "Unhandled initializer kind!");
1713 }
John McCall9ae2f072010-08-23 23:25:46 +00001714
Douglas Gregor53c374f2010-12-07 00:41:46 +00001715 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001716 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001717 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001718
Anders Carlssondefefd22010-04-23 02:00:02 +00001719 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001720 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001721 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1722 SourceLocation()),
1723 BaseSpec->isVirtual(),
1724 SourceLocation(),
1725 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001726 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001727 SourceLocation());
1728
Anders Carlssondefefd22010-04-23 02:00:02 +00001729 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001730}
1731
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001732static bool
1733BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001734 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001735 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001736 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001737 if (Field->isInvalidDecl())
1738 return true;
1739
Chandler Carruthf186b542010-06-29 23:50:44 +00001740 SourceLocation Loc = Constructor->getLocation();
1741
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001742 if (ImplicitInitKind == IIK_Copy) {
1743 ParmVarDecl *Param = Constructor->getParamDecl(0);
1744 QualType ParamType = Param->getType().getNonReferenceType();
1745
1746 Expr *MemberExprBase =
1747 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001748 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001749
1750 // Build a reference to this field within the parameter.
1751 CXXScopeSpec SS;
1752 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1753 Sema::LookupMemberName);
1754 MemberLookup.addDecl(Field, AS_public);
1755 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001756 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001757 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001758 ParamType, Loc,
1759 /*IsArrow=*/false,
1760 SS,
1761 /*FirstQualifierInScope=*/0,
1762 MemberLookup,
1763 /*TemplateArgs=*/0);
1764 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001765 return true;
1766
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001767 // When the field we are copying is an array, create index variables for
1768 // each dimension of the array. We use these index variables to subscript
1769 // the source array, and other clients (e.g., CodeGen) will perform the
1770 // necessary iteration with these index variables.
1771 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1772 QualType BaseType = Field->getType();
1773 QualType SizeType = SemaRef.Context.getSizeType();
1774 while (const ConstantArrayType *Array
1775 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1776 // Create the iteration variable for this array index.
1777 IdentifierInfo *IterationVarName = 0;
1778 {
1779 llvm::SmallString<8> Str;
1780 llvm::raw_svector_ostream OS(Str);
1781 OS << "__i" << IndexVariables.size();
1782 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1783 }
1784 VarDecl *IterationVar
1785 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1786 IterationVarName, SizeType,
1787 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001788 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001789 IndexVariables.push_back(IterationVar);
1790
1791 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001792 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001793 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001794 assert(!IterationVarRef.isInvalid() &&
1795 "Reference to invented variable cannot fail!");
1796
1797 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001798 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001799 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001800 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001801 Loc);
1802 if (CopyCtorArg.isInvalid())
1803 return true;
1804
1805 BaseType = Array->getElementType();
1806 }
1807
1808 // Construct the entity that we will be initializing. For an array, this
1809 // will be first element in the array, which may require several levels
1810 // of array-subscript entities.
1811 llvm::SmallVector<InitializedEntity, 4> Entities;
1812 Entities.reserve(1 + IndexVariables.size());
1813 Entities.push_back(InitializedEntity::InitializeMember(Field));
1814 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1815 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1816 0,
1817 Entities.back()));
1818
1819 // Direct-initialize to use the copy constructor.
1820 InitializationKind InitKind =
1821 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1822
1823 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1824 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1825 &CopyCtorArgE, 1);
1826
John McCall60d7b3a2010-08-24 06:29:42 +00001827 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001828 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001829 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001830 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001831 if (MemberInit.isInvalid())
1832 return true;
1833
1834 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001835 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001836 MemberInit.takeAs<Expr>(), Loc,
1837 IndexVariables.data(),
1838 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001839 return false;
1840 }
1841
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001842 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1843
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001844 QualType FieldBaseElementType =
1845 SemaRef.Context.getBaseElementType(Field->getType());
1846
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001847 if (FieldBaseElementType->isRecordType()) {
1848 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001849 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001850 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001851
1852 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001853 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001854 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001855
Douglas Gregor53c374f2010-12-07 00:41:46 +00001856 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001857 if (MemberInit.isInvalid())
1858 return true;
1859
1860 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001861 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001862 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001863 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001864 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001865 return false;
1866 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001867
1868 if (FieldBaseElementType->isReferenceType()) {
1869 SemaRef.Diag(Constructor->getLocation(),
1870 diag::err_uninitialized_member_in_ctor)
1871 << (int)Constructor->isImplicit()
1872 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1873 << 0 << Field->getDeclName();
1874 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1875 return true;
1876 }
1877
1878 if (FieldBaseElementType.isConstQualified()) {
1879 SemaRef.Diag(Constructor->getLocation(),
1880 diag::err_uninitialized_member_in_ctor)
1881 << (int)Constructor->isImplicit()
1882 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1883 << 1 << Field->getDeclName();
1884 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1885 return true;
1886 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001887
1888 // Nothing to initialize.
1889 CXXMemberInit = 0;
1890 return false;
1891}
John McCallf1860e52010-05-20 23:23:51 +00001892
1893namespace {
1894struct BaseAndFieldInfo {
1895 Sema &S;
1896 CXXConstructorDecl *Ctor;
1897 bool AnyErrorsInInits;
1898 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001899 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1900 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001901
1902 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1903 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1904 // FIXME: Handle implicit move constructors.
1905 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1906 IIK = IIK_Copy;
1907 else
1908 IIK = IIK_Default;
1909 }
1910};
1911}
1912
1913static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1914 FieldDecl *Top, FieldDecl *Field) {
1915
Chandler Carruthe861c602010-06-30 02:59:29 +00001916 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00001917 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001918 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001919 return false;
1920 }
1921
1922 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1923 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1924 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001925 CXXRecordDecl *FieldClassDecl
1926 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001927
1928 // Even though union members never have non-trivial default
1929 // constructions in C++03, we still build member initializers for aggregate
1930 // record types which can be union members, and C++0x allows non-trivial
1931 // default constructors for union members, so we ensure that only one
1932 // member is initialized for these.
1933 if (FieldClassDecl->isUnion()) {
1934 // First check for an explicit initializer for one field.
1935 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1936 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00001937 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001938 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001939
1940 // Once we've initialized a field of an anonymous union, the union
1941 // field in the class is also initialized, so exit immediately.
1942 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001943 } else if ((*FA)->isAnonymousStructOrUnion()) {
1944 if (CollectFieldInitializer(Info, Top, *FA))
1945 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001946 }
1947 }
1948
1949 // Fallthrough and construct a default initializer for the union as
1950 // a whole, which can call its default constructor if such a thing exists
1951 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1952 // behavior going forward with C++0x, when anonymous unions there are
1953 // finalized, we should revisit this.
1954 } else {
1955 // For structs, we simply descend through to initialize all members where
1956 // necessary.
1957 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1958 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1959 if (CollectFieldInitializer(Info, Top, *FA))
1960 return true;
1961 }
1962 }
John McCallf1860e52010-05-20 23:23:51 +00001963 }
1964
1965 // Don't try to build an implicit initializer if there were semantic
1966 // errors in any of the initializers (and therefore we might be
1967 // missing some that the user actually wrote).
1968 if (Info.AnyErrorsInInits)
1969 return false;
1970
Sean Huntcbb67482011-01-08 20:30:50 +00001971 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00001972 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1973 return true;
John McCallf1860e52010-05-20 23:23:51 +00001974
Francois Pichet00eb3f92010-12-04 09:14:42 +00001975 if (Init)
1976 Info.AllToInit.push_back(Init);
1977
John McCallf1860e52010-05-20 23:23:51 +00001978 return false;
1979}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001980
Eli Friedman80c30da2009-11-09 19:20:36 +00001981bool
Sean Huntcbb67482011-01-08 20:30:50 +00001982Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1983 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001984 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001985 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001986 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001987 // Just store the initializers as written, they will be checked during
1988 // instantiation.
1989 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00001990 Constructor->setNumCtorInitializers(NumInitializers);
1991 CXXCtorInitializer **baseOrMemberInitializers =
1992 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001993 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00001994 NumInitializers * sizeof(CXXCtorInitializer*));
1995 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001996 }
1997
1998 return false;
1999 }
2000
John McCallf1860e52010-05-20 23:23:51 +00002001 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002002
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002003 // We need to build the initializer AST according to order of construction
2004 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002005 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002006 if (!ClassDecl)
2007 return true;
2008
Eli Friedman80c30da2009-11-09 19:20:36 +00002009 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002011 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002012 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002013
2014 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002015 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002016 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002017 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002018 }
2019
Anders Carlsson711f34a2010-04-21 19:52:01 +00002020 // Keep track of the direct virtual bases.
2021 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2022 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2023 E = ClassDecl->bases_end(); I != E; ++I) {
2024 if (I->isVirtual())
2025 DirectVBases.insert(I);
2026 }
2027
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002028 // Push virtual bases before others.
2029 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2030 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2031
Sean Huntcbb67482011-01-08 20:30:50 +00002032 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002033 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2034 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002035 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002036 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002037 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002038 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002039 VBase, IsInheritedVirtualBase,
2040 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002041 HadError = true;
2042 continue;
2043 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002044
John McCallf1860e52010-05-20 23:23:51 +00002045 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002046 }
2047 }
Mike Stump1eb44332009-09-09 15:08:12 +00002048
John McCallf1860e52010-05-20 23:23:51 +00002049 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002050 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2051 E = ClassDecl->bases_end(); Base != E; ++Base) {
2052 // Virtuals are in the virtual base list and already constructed.
2053 if (Base->isVirtual())
2054 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Sean Huntcbb67482011-01-08 20:30:50 +00002056 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002057 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2058 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002059 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002060 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002061 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002062 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002063 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002064 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002065 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002066 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002067
John McCallf1860e52010-05-20 23:23:51 +00002068 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002069 }
2070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
John McCallf1860e52010-05-20 23:23:51 +00002072 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002073 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002074 E = ClassDecl->field_end(); Field != E; ++Field) {
2075 if ((*Field)->getType()->isIncompleteArrayType()) {
2076 assert(ClassDecl->hasFlexibleArrayMember() &&
2077 "Incomplete array type is not valid");
2078 continue;
2079 }
John McCallf1860e52010-05-20 23:23:51 +00002080 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002081 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
John McCallf1860e52010-05-20 23:23:51 +00002084 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002085 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002086 Constructor->setNumCtorInitializers(NumInitializers);
2087 CXXCtorInitializer **baseOrMemberInitializers =
2088 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002089 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002090 NumInitializers * sizeof(CXXCtorInitializer*));
2091 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002092
John McCallef027fe2010-03-16 21:39:52 +00002093 // Constructors implicitly reference the base and member
2094 // destructors.
2095 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2096 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002097 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002098
2099 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002100}
2101
Eli Friedman6347f422009-07-21 19:28:10 +00002102static void *GetKeyForTopLevelField(FieldDecl *Field) {
2103 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002104 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002105 if (RT->getDecl()->isAnonymousStructOrUnion())
2106 return static_cast<void *>(RT->getDecl());
2107 }
2108 return static_cast<void *>(Field);
2109}
2110
Anders Carlssonea356fb2010-04-02 05:42:15 +00002111static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002112 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002113}
2114
Anders Carlssonea356fb2010-04-02 05:42:15 +00002115static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002116 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002117 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002118 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002119
Eli Friedman6347f422009-07-21 19:28:10 +00002120 // For fields injected into the class via declaration of an anonymous union,
2121 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002122 FieldDecl *Field = Member->getAnyMember();
2123
John McCall3c3ccdb2010-04-10 09:28:51 +00002124 // If the field is a member of an anonymous struct or union, our key
2125 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002126 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002127 if (RD->isAnonymousStructOrUnion()) {
2128 while (true) {
2129 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2130 if (Parent->isAnonymousStructOrUnion())
2131 RD = Parent;
2132 else
2133 break;
2134 }
2135
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002136 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002137 }
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002139 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002140}
2141
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002142static void
2143DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002144 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002145 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002146 unsigned NumInits) {
2147 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002148 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002150 // Don't check initializers order unless the warning is enabled at the
2151 // location of at least one initializer.
2152 bool ShouldCheckOrder = false;
2153 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002154 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002155 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2156 Init->getSourceLocation())
2157 != Diagnostic::Ignored) {
2158 ShouldCheckOrder = true;
2159 break;
2160 }
2161 }
2162 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002163 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002164
John McCalld6ca8da2010-04-10 07:37:23 +00002165 // Build the list of bases and members in the order that they'll
2166 // actually be initialized. The explicit initializers should be in
2167 // this same order but may be missing things.
2168 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anders Carlsson071d6102010-04-02 03:38:04 +00002170 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2171
John McCalld6ca8da2010-04-10 07:37:23 +00002172 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002173 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002174 ClassDecl->vbases_begin(),
2175 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002176 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002177
John McCalld6ca8da2010-04-10 07:37:23 +00002178 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002179 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002180 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002181 if (Base->isVirtual())
2182 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002183 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002184 }
Mike Stump1eb44332009-09-09 15:08:12 +00002185
John McCalld6ca8da2010-04-10 07:37:23 +00002186 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002187 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2188 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002189 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002190
John McCalld6ca8da2010-04-10 07:37:23 +00002191 unsigned NumIdealInits = IdealInitKeys.size();
2192 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002193
Sean Huntcbb67482011-01-08 20:30:50 +00002194 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002195 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002196 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002197 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002198
2199 // Scan forward to try to find this initializer in the idealized
2200 // initializers list.
2201 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2202 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002203 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002204
2205 // If we didn't find this initializer, it must be because we
2206 // scanned past it on a previous iteration. That can only
2207 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002208 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002209 Sema::SemaDiagnosticBuilder D =
2210 SemaRef.Diag(PrevInit->getSourceLocation(),
2211 diag::warn_initializer_out_of_order);
2212
Francois Pichet00eb3f92010-12-04 09:14:42 +00002213 if (PrevInit->isAnyMemberInitializer())
2214 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002215 else
2216 D << 1 << PrevInit->getBaseClassInfo()->getType();
2217
Francois Pichet00eb3f92010-12-04 09:14:42 +00002218 if (Init->isAnyMemberInitializer())
2219 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002220 else
2221 D << 1 << Init->getBaseClassInfo()->getType();
2222
2223 // Move back to the initializer's location in the ideal list.
2224 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2225 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002226 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002227
2228 assert(IdealIndex != NumIdealInits &&
2229 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002230 }
John McCalld6ca8da2010-04-10 07:37:23 +00002231
2232 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002233 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002234}
2235
John McCall3c3ccdb2010-04-10 09:28:51 +00002236namespace {
2237bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002238 CXXCtorInitializer *Init,
2239 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002240 if (!PrevInit) {
2241 PrevInit = Init;
2242 return false;
2243 }
2244
2245 if (FieldDecl *Field = Init->getMember())
2246 S.Diag(Init->getSourceLocation(),
2247 diag::err_multiple_mem_initialization)
2248 << Field->getDeclName()
2249 << Init->getSourceRange();
2250 else {
John McCallf4c73712011-01-19 06:33:43 +00002251 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002252 assert(BaseClass && "neither field nor base");
2253 S.Diag(Init->getSourceLocation(),
2254 diag::err_multiple_base_initialization)
2255 << QualType(BaseClass, 0)
2256 << Init->getSourceRange();
2257 }
2258 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2259 << 0 << PrevInit->getSourceRange();
2260
2261 return true;
2262}
2263
Sean Huntcbb67482011-01-08 20:30:50 +00002264typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002265typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2266
2267bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002268 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002269 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002270 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002271 RecordDecl *Parent = Field->getParent();
2272 if (!Parent->isAnonymousStructOrUnion())
2273 return false;
2274
2275 NamedDecl *Child = Field;
2276 do {
2277 if (Parent->isUnion()) {
2278 UnionEntry &En = Unions[Parent];
2279 if (En.first && En.first != Child) {
2280 S.Diag(Init->getSourceLocation(),
2281 diag::err_multiple_mem_union_initialization)
2282 << Field->getDeclName()
2283 << Init->getSourceRange();
2284 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2285 << 0 << En.second->getSourceRange();
2286 return true;
2287 } else if (!En.first) {
2288 En.first = Child;
2289 En.second = Init;
2290 }
2291 }
2292
2293 Child = Parent;
2294 Parent = cast<RecordDecl>(Parent->getDeclContext());
2295 } while (Parent->isAnonymousStructOrUnion());
2296
2297 return false;
2298}
2299}
2300
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002301/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002302void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002303 SourceLocation ColonLoc,
2304 MemInitTy **meminits, unsigned NumMemInits,
2305 bool AnyErrors) {
2306 if (!ConstructorDecl)
2307 return;
2308
2309 AdjustDeclIfTemplate(ConstructorDecl);
2310
2311 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002312 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002313
2314 if (!Constructor) {
2315 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2316 return;
2317 }
2318
Sean Huntcbb67482011-01-08 20:30:50 +00002319 CXXCtorInitializer **MemInits =
2320 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002321
2322 // Mapping for the duplicate initializers check.
2323 // For member initializers, this is keyed with a FieldDecl*.
2324 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002325 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002326
2327 // Mapping for the inconsistent anonymous-union initializers check.
2328 RedundantUnionMap MemberUnions;
2329
Anders Carlssonea356fb2010-04-02 05:42:15 +00002330 bool HadError = false;
2331 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002332 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002333
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002334 // Set the source order index.
2335 Init->setSourceOrder(i);
2336
Francois Pichet00eb3f92010-12-04 09:14:42 +00002337 if (Init->isAnyMemberInitializer()) {
2338 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002339 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2340 CheckRedundantUnionInit(*this, Init, MemberUnions))
2341 HadError = true;
2342 } else {
2343 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2344 if (CheckRedundantInit(*this, Init, Members[Key]))
2345 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002346 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002347 }
2348
Anders Carlssonea356fb2010-04-02 05:42:15 +00002349 if (HadError)
2350 return;
2351
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002352 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002353
Sean Huntcbb67482011-01-08 20:30:50 +00002354 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002355}
2356
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002357void
John McCallef027fe2010-03-16 21:39:52 +00002358Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2359 CXXRecordDecl *ClassDecl) {
2360 // Ignore dependent contexts.
2361 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002362 return;
John McCall58e6f342010-03-16 05:22:47 +00002363
2364 // FIXME: all the access-control diagnostics are positioned on the
2365 // field/base declaration. That's probably good; that said, the
2366 // user might reasonably want to know why the destructor is being
2367 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002368
Anders Carlsson9f853df2009-11-17 04:44:12 +00002369 // Non-static data members.
2370 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2371 E = ClassDecl->field_end(); I != E; ++I) {
2372 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002373 if (Field->isInvalidDecl())
2374 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002375 QualType FieldType = Context.getBaseElementType(Field->getType());
2376
2377 const RecordType* RT = FieldType->getAs<RecordType>();
2378 if (!RT)
2379 continue;
2380
2381 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2382 if (FieldClassDecl->hasTrivialDestructor())
2383 continue;
2384
Douglas Gregordb89f282010-07-01 22:47:18 +00002385 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002386 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002387 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002388 << Field->getDeclName()
2389 << FieldType);
2390
John McCallef027fe2010-03-16 21:39:52 +00002391 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002392 }
2393
John McCall58e6f342010-03-16 05:22:47 +00002394 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2395
Anders Carlsson9f853df2009-11-17 04:44:12 +00002396 // Bases.
2397 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2398 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002399 // Bases are always records in a well-formed non-dependent class.
2400 const RecordType *RT = Base->getType()->getAs<RecordType>();
2401
2402 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002403 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002404 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002405
2406 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002407 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002408 if (BaseClassDecl->hasTrivialDestructor())
2409 continue;
John McCall58e6f342010-03-16 05:22:47 +00002410
Douglas Gregordb89f282010-07-01 22:47:18 +00002411 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002412
2413 // FIXME: caret should be on the start of the class name
2414 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002415 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002416 << Base->getType()
2417 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002418
John McCallef027fe2010-03-16 21:39:52 +00002419 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002420 }
2421
2422 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002423 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2424 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002425
2426 // Bases are always records in a well-formed non-dependent class.
2427 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2428
2429 // Ignore direct virtual bases.
2430 if (DirectVirtualBases.count(RT))
2431 continue;
2432
Anders Carlsson9f853df2009-11-17 04:44:12 +00002433 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002434 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002435 if (BaseClassDecl->hasTrivialDestructor())
2436 continue;
John McCall58e6f342010-03-16 05:22:47 +00002437
Douglas Gregordb89f282010-07-01 22:47:18 +00002438 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002439 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002440 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002441 << VBase->getType());
2442
John McCallef027fe2010-03-16 21:39:52 +00002443 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002444 }
2445}
2446
John McCalld226f652010-08-21 09:40:31 +00002447void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002448 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002449 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Mike Stump1eb44332009-09-09 15:08:12 +00002451 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002452 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002453 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002454}
2455
Mike Stump1eb44332009-09-09 15:08:12 +00002456bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002457 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002458 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002459 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002460 else
John McCall94c3b562010-08-18 09:41:07 +00002461 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002462}
2463
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002464bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002465 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002466 if (!getLangOptions().CPlusPlus)
2467 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Anders Carlsson11f21a02009-03-23 19:10:31 +00002469 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002470 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Ted Kremenek6217b802009-07-29 21:53:49 +00002472 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002473 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002474 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002475 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002477 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002478 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002479 }
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Ted Kremenek6217b802009-07-29 21:53:49 +00002481 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002482 if (!RT)
2483 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002484
John McCall86ff3082010-02-04 22:26:26 +00002485 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002486
John McCall94c3b562010-08-18 09:41:07 +00002487 // We can't answer whether something is abstract until it has a
2488 // definition. If it's currently being defined, we'll walk back
2489 // over all the declarations when we have a full definition.
2490 const CXXRecordDecl *Def = RD->getDefinition();
2491 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002492 return false;
2493
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002494 if (!RD->isAbstract())
2495 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002497 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002498 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002499
John McCall94c3b562010-08-18 09:41:07 +00002500 return true;
2501}
2502
2503void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2504 // Check if we've already emitted the list of pure virtual functions
2505 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002506 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002507 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002509 CXXFinalOverriderMap FinalOverriders;
2510 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002512 // Keep a set of seen pure methods so we won't diagnose the same method
2513 // more than once.
2514 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2515
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002516 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2517 MEnd = FinalOverriders.end();
2518 M != MEnd;
2519 ++M) {
2520 for (OverridingMethods::iterator SO = M->second.begin(),
2521 SOEnd = M->second.end();
2522 SO != SOEnd; ++SO) {
2523 // C++ [class.abstract]p4:
2524 // A class is abstract if it contains or inherits at least one
2525 // pure virtual function for which the final overrider is pure
2526 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002528 //
2529 if (SO->second.size() != 1)
2530 continue;
2531
2532 if (!SO->second.front().Method->isPure())
2533 continue;
2534
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002535 if (!SeenPureMethods.insert(SO->second.front().Method))
2536 continue;
2537
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002538 Diag(SO->second.front().Method->getLocation(),
2539 diag::note_pure_virtual_function)
2540 << SO->second.front().Method->getDeclName();
2541 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002542 }
2543
2544 if (!PureVirtualClassDiagSet)
2545 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2546 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002547}
2548
Anders Carlsson8211eff2009-03-24 01:19:16 +00002549namespace {
John McCall94c3b562010-08-18 09:41:07 +00002550struct AbstractUsageInfo {
2551 Sema &S;
2552 CXXRecordDecl *Record;
2553 CanQualType AbstractType;
2554 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002555
John McCall94c3b562010-08-18 09:41:07 +00002556 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2557 : S(S), Record(Record),
2558 AbstractType(S.Context.getCanonicalType(
2559 S.Context.getTypeDeclType(Record))),
2560 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002561
John McCall94c3b562010-08-18 09:41:07 +00002562 void DiagnoseAbstractType() {
2563 if (Invalid) return;
2564 S.DiagnoseAbstractType(Record);
2565 Invalid = true;
2566 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002567
John McCall94c3b562010-08-18 09:41:07 +00002568 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2569};
2570
2571struct CheckAbstractUsage {
2572 AbstractUsageInfo &Info;
2573 const NamedDecl *Ctx;
2574
2575 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2576 : Info(Info), Ctx(Ctx) {}
2577
2578 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2579 switch (TL.getTypeLocClass()) {
2580#define ABSTRACT_TYPELOC(CLASS, PARENT)
2581#define TYPELOC(CLASS, PARENT) \
2582 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2583#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002584 }
John McCall94c3b562010-08-18 09:41:07 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
John McCall94c3b562010-08-18 09:41:07 +00002587 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2588 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2589 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2590 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2591 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002592 }
John McCall94c3b562010-08-18 09:41:07 +00002593 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002594
John McCall94c3b562010-08-18 09:41:07 +00002595 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2596 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2597 }
Mike Stump1eb44332009-09-09 15:08:12 +00002598
John McCall94c3b562010-08-18 09:41:07 +00002599 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2600 // Visit the type parameters from a permissive context.
2601 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2602 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2603 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2604 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2605 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2606 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002607 }
John McCall94c3b562010-08-18 09:41:07 +00002608 }
Mike Stump1eb44332009-09-09 15:08:12 +00002609
John McCall94c3b562010-08-18 09:41:07 +00002610 // Visit pointee types from a permissive context.
2611#define CheckPolymorphic(Type) \
2612 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2613 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2614 }
2615 CheckPolymorphic(PointerTypeLoc)
2616 CheckPolymorphic(ReferenceTypeLoc)
2617 CheckPolymorphic(MemberPointerTypeLoc)
2618 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002619
John McCall94c3b562010-08-18 09:41:07 +00002620 /// Handle all the types we haven't given a more specific
2621 /// implementation for above.
2622 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2623 // Every other kind of type that we haven't called out already
2624 // that has an inner type is either (1) sugar or (2) contains that
2625 // inner type in some way as a subobject.
2626 if (TypeLoc Next = TL.getNextTypeLoc())
2627 return Visit(Next, Sel);
2628
2629 // If there's no inner type and we're in a permissive context,
2630 // don't diagnose.
2631 if (Sel == Sema::AbstractNone) return;
2632
2633 // Check whether the type matches the abstract type.
2634 QualType T = TL.getType();
2635 if (T->isArrayType()) {
2636 Sel = Sema::AbstractArrayType;
2637 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002638 }
John McCall94c3b562010-08-18 09:41:07 +00002639 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2640 if (CT != Info.AbstractType) return;
2641
2642 // It matched; do some magic.
2643 if (Sel == Sema::AbstractArrayType) {
2644 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2645 << T << TL.getSourceRange();
2646 } else {
2647 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2648 << Sel << T << TL.getSourceRange();
2649 }
2650 Info.DiagnoseAbstractType();
2651 }
2652};
2653
2654void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2655 Sema::AbstractDiagSelID Sel) {
2656 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2657}
2658
2659}
2660
2661/// Check for invalid uses of an abstract type in a method declaration.
2662static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2663 CXXMethodDecl *MD) {
2664 // No need to do the check on definitions, which require that
2665 // the return/param types be complete.
2666 if (MD->isThisDeclarationADefinition())
2667 return;
2668
2669 // For safety's sake, just ignore it if we don't have type source
2670 // information. This should never happen for non-implicit methods,
2671 // but...
2672 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2673 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2674}
2675
2676/// Check for invalid uses of an abstract type within a class definition.
2677static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2678 CXXRecordDecl *RD) {
2679 for (CXXRecordDecl::decl_iterator
2680 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2681 Decl *D = *I;
2682 if (D->isImplicit()) continue;
2683
2684 // Methods and method templates.
2685 if (isa<CXXMethodDecl>(D)) {
2686 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2687 } else if (isa<FunctionTemplateDecl>(D)) {
2688 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2689 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2690
2691 // Fields and static variables.
2692 } else if (isa<FieldDecl>(D)) {
2693 FieldDecl *FD = cast<FieldDecl>(D);
2694 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2695 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2696 } else if (isa<VarDecl>(D)) {
2697 VarDecl *VD = cast<VarDecl>(D);
2698 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2699 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2700
2701 // Nested classes and class templates.
2702 } else if (isa<CXXRecordDecl>(D)) {
2703 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2704 } else if (isa<ClassTemplateDecl>(D)) {
2705 CheckAbstractClassUsage(Info,
2706 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2707 }
2708 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002709}
2710
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002711/// \brief Perform semantic checks on a class definition that has been
2712/// completing, introducing implicitly-declared members, checking for
2713/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002714void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002715 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002716 return;
2717
John McCall94c3b562010-08-18 09:41:07 +00002718 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2719 AbstractUsageInfo Info(*this, Record);
2720 CheckAbstractClassUsage(Info, Record);
2721 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002722
2723 // If this is not an aggregate type and has no user-declared constructor,
2724 // complain about any non-static data members of reference or const scalar
2725 // type, since they will never get initializers.
2726 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2727 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2728 bool Complained = false;
2729 for (RecordDecl::field_iterator F = Record->field_begin(),
2730 FEnd = Record->field_end();
2731 F != FEnd; ++F) {
2732 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002733 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002734 if (!Complained) {
2735 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2736 << Record->getTagKind() << Record;
2737 Complained = true;
2738 }
2739
2740 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2741 << F->getType()->isReferenceType()
2742 << F->getDeclName();
2743 }
2744 }
2745 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002746
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002747 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002748 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002749
2750 if (Record->getIdentifier()) {
2751 // C++ [class.mem]p13:
2752 // If T is the name of a class, then each of the following shall have a
2753 // name different from T:
2754 // - every member of every anonymous union that is a member of class T.
2755 //
2756 // C++ [class.mem]p14:
2757 // In addition, if class T has a user-declared constructor (12.1), every
2758 // non-static data member of class T shall have a name different from T.
2759 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002760 R.first != R.second; ++R.first) {
2761 NamedDecl *D = *R.first;
2762 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2763 isa<IndirectFieldDecl>(D)) {
2764 Diag(D->getLocation(), diag::err_member_name_of_class)
2765 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002766 break;
2767 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002768 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002769 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002770
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002771 // Warn if the class has virtual methods but non-virtual public destructor.
Argyrios Kyrtzidis668fdd82011-02-02 18:47:41 +00002772 if (Record->isDynamicClass() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002773 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002774 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002775 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2776 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2777 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002778
2779 // See if a method overloads virtual methods in a base
2780 /// class without overriding any.
2781 if (!Record->isDependentType()) {
2782 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2783 MEnd = Record->method_end();
2784 M != MEnd; ++M) {
2785 DiagnoseHiddenVirtualMethods(Record, *M);
2786 }
2787 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002788
2789 // Declare inherited constructors. We do this eagerly here because:
2790 // - The standard requires an eager diagnostic for conflicting inherited
2791 // constructors from different classes.
2792 // - The lazy declaration of the other implicit constructors is so as to not
2793 // waste space and performance on classes that are not meant to be
2794 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2795 // have inherited constructors.
2796 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002797}
2798
2799/// \brief Data used with FindHiddenVirtualMethod
2800struct FindHiddenVirtualMethodData {
2801 Sema *S;
2802 CXXMethodDecl *Method;
2803 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2804 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2805};
2806
2807/// \brief Member lookup function that determines whether a given C++
2808/// method overloads virtual methods in a base class without overriding any,
2809/// to be used with CXXRecordDecl::lookupInBases().
2810static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2811 CXXBasePath &Path,
2812 void *UserData) {
2813 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2814
2815 FindHiddenVirtualMethodData &Data
2816 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2817
2818 DeclarationName Name = Data.Method->getDeclName();
2819 assert(Name.getNameKind() == DeclarationName::Identifier);
2820
2821 bool foundSameNameMethod = false;
2822 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2823 for (Path.Decls = BaseRecord->lookup(Name);
2824 Path.Decls.first != Path.Decls.second;
2825 ++Path.Decls.first) {
2826 NamedDecl *D = *Path.Decls.first;
2827 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002828 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002829 foundSameNameMethod = true;
2830 // Interested only in hidden virtual methods.
2831 if (!MD->isVirtual())
2832 continue;
2833 // If the method we are checking overrides a method from its base
2834 // don't warn about the other overloaded methods.
2835 if (!Data.S->IsOverload(Data.Method, MD, false))
2836 return true;
2837 // Collect the overload only if its hidden.
2838 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2839 overloadedMethods.push_back(MD);
2840 }
2841 }
2842
2843 if (foundSameNameMethod)
2844 Data.OverloadedMethods.append(overloadedMethods.begin(),
2845 overloadedMethods.end());
2846 return foundSameNameMethod;
2847}
2848
2849/// \brief See if a method overloads virtual methods in a base class without
2850/// overriding any.
2851void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2852 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2853 MD->getLocation()) == Diagnostic::Ignored)
2854 return;
2855 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2856 return;
2857
2858 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2859 /*bool RecordPaths=*/false,
2860 /*bool DetectVirtual=*/false);
2861 FindHiddenVirtualMethodData Data;
2862 Data.Method = MD;
2863 Data.S = this;
2864
2865 // Keep the base methods that were overriden or introduced in the subclass
2866 // by 'using' in a set. A base method not in this set is hidden.
2867 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2868 res.first != res.second; ++res.first) {
2869 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2870 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2871 E = MD->end_overridden_methods();
2872 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002873 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002874 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2875 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002876 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002877 }
2878
2879 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2880 !Data.OverloadedMethods.empty()) {
2881 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2882 << MD << (Data.OverloadedMethods.size() > 1);
2883
2884 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2885 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2886 Diag(overloadedMD->getLocation(),
2887 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2888 }
2889 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002890}
2891
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002892void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002893 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002894 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002895 SourceLocation RBrac,
2896 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002897 if (!TagDecl)
2898 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Douglas Gregor42af25f2009-05-11 19:58:34 +00002900 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002901
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002902 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002903 // strict aliasing violation!
2904 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002905 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002906
Douglas Gregor23c94db2010-07-02 17:43:08 +00002907 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002908 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002909}
2910
Douglas Gregord92ec472010-07-01 05:10:53 +00002911namespace {
2912 /// \brief Helper class that collects exception specifications for
2913 /// implicitly-declared special member functions.
2914 class ImplicitExceptionSpecification {
2915 ASTContext &Context;
2916 bool AllowsAllExceptions;
2917 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2918 llvm::SmallVector<QualType, 4> Exceptions;
2919
2920 public:
2921 explicit ImplicitExceptionSpecification(ASTContext &Context)
2922 : Context(Context), AllowsAllExceptions(false) { }
2923
2924 /// \brief Whether the special member function should have any
2925 /// exception specification at all.
2926 bool hasExceptionSpecification() const {
2927 return !AllowsAllExceptions;
2928 }
2929
2930 /// \brief Whether the special member function should have a
2931 /// throw(...) exception specification (a Microsoft extension).
2932 bool hasAnyExceptionSpecification() const {
2933 return false;
2934 }
2935
2936 /// \brief The number of exceptions in the exception specification.
2937 unsigned size() const { return Exceptions.size(); }
2938
2939 /// \brief The set of exceptions in the exception specification.
2940 const QualType *data() const { return Exceptions.data(); }
2941
2942 /// \brief Note that
2943 void CalledDecl(CXXMethodDecl *Method) {
2944 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002945 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002946 return;
2947
2948 const FunctionProtoType *Proto
2949 = Method->getType()->getAs<FunctionProtoType>();
2950
2951 // If this function can throw any exceptions, make a note of that.
2952 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2953 AllowsAllExceptions = true;
2954 ExceptionsSeen.clear();
2955 Exceptions.clear();
2956 return;
2957 }
2958
2959 // Record the exceptions in this function's exception specification.
2960 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2961 EEnd = Proto->exception_end();
2962 E != EEnd; ++E)
2963 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2964 Exceptions.push_back(*E);
2965 }
2966 };
2967}
2968
2969
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002970/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2971/// special functions, such as the default constructor, copy
2972/// constructor, or destructor, to the given C++ class (C++
2973/// [special]p1). This routine can only be executed just before the
2974/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002975void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002976 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002977 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002978
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002979 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002980 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002981
Douglas Gregora376d102010-07-02 21:50:04 +00002982 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2983 ++ASTContext::NumImplicitCopyAssignmentOperators;
2984
2985 // If we have a dynamic class, then the copy assignment operator may be
2986 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2987 // it shows up in the right place in the vtable and that we diagnose
2988 // problems with the implicit exception specification.
2989 if (ClassDecl->isDynamicClass())
2990 DeclareImplicitCopyAssignment(ClassDecl);
2991 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002992
Douglas Gregor4923aa22010-07-02 20:37:36 +00002993 if (!ClassDecl->hasUserDeclaredDestructor()) {
2994 ++ASTContext::NumImplicitDestructors;
2995
2996 // If we have a dynamic class, then the destructor may be virtual, so we
2997 // have to declare the destructor immediately. This ensures that, e.g., it
2998 // shows up in the right place in the vtable and that we diagnose problems
2999 // with the implicit exception specification.
3000 if (ClassDecl->isDynamicClass())
3001 DeclareImplicitDestructor(ClassDecl);
3002 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003003}
3004
John McCalld226f652010-08-21 09:40:31 +00003005void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003006 if (!D)
3007 return;
3008
3009 TemplateParameterList *Params = 0;
3010 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3011 Params = Template->getTemplateParameters();
3012 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3013 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3014 Params = PartialSpec->getTemplateParameters();
3015 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003016 return;
3017
Douglas Gregor6569d682009-05-27 23:11:45 +00003018 for (TemplateParameterList::iterator Param = Params->begin(),
3019 ParamEnd = Params->end();
3020 Param != ParamEnd; ++Param) {
3021 NamedDecl *Named = cast<NamedDecl>(*Param);
3022 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003023 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003024 IdResolver.AddDecl(Named);
3025 }
3026 }
3027}
3028
John McCalld226f652010-08-21 09:40:31 +00003029void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003030 if (!RecordD) return;
3031 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003032 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003033 PushDeclContext(S, Record);
3034}
3035
John McCalld226f652010-08-21 09:40:31 +00003036void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003037 if (!RecordD) return;
3038 PopDeclContext();
3039}
3040
Douglas Gregor72b505b2008-12-16 21:30:33 +00003041/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3042/// parsing a top-level (non-nested) C++ class, and we are now
3043/// parsing those parts of the given Method declaration that could
3044/// not be parsed earlier (C++ [class.mem]p2), such as default
3045/// arguments. This action should enter the scope of the given
3046/// Method declaration as if we had just parsed the qualified method
3047/// name. However, it should not bring the parameters into scope;
3048/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003049void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003050}
3051
3052/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3053/// C++ method declaration. We're (re-)introducing the given
3054/// function parameter into scope for use in parsing later parts of
3055/// the method declaration. For example, we could see an
3056/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003057void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003058 if (!ParamD)
3059 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003060
John McCalld226f652010-08-21 09:40:31 +00003061 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003062
3063 // If this parameter has an unparsed default argument, clear it out
3064 // to make way for the parsed default argument.
3065 if (Param->hasUnparsedDefaultArg())
3066 Param->setDefaultArg(0);
3067
John McCalld226f652010-08-21 09:40:31 +00003068 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003069 if (Param->getDeclName())
3070 IdResolver.AddDecl(Param);
3071}
3072
3073/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3074/// processing the delayed method declaration for Method. The method
3075/// declaration is now considered finished. There may be a separate
3076/// ActOnStartOfFunctionDef action later (not necessarily
3077/// immediately!) for this method, if it was also defined inside the
3078/// class body.
John McCalld226f652010-08-21 09:40:31 +00003079void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003080 if (!MethodD)
3081 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003083 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003084
John McCalld226f652010-08-21 09:40:31 +00003085 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003086
3087 // Now that we have our default arguments, check the constructor
3088 // again. It could produce additional diagnostics or affect whether
3089 // the class has implicitly-declared destructors, among other
3090 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003091 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3092 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003093
3094 // Check the default arguments, which we may have added.
3095 if (!Method->isInvalidDecl())
3096 CheckCXXDefaultArguments(Method);
3097}
3098
Douglas Gregor42a552f2008-11-05 20:51:48 +00003099/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003100/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003101/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003102/// emit diagnostics and set the invalid bit to true. In any case, the type
3103/// will be updated to reflect a well-formed type for the constructor and
3104/// returned.
3105QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003106 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003107 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003108
3109 // C++ [class.ctor]p3:
3110 // A constructor shall not be virtual (10.3) or static (9.4). A
3111 // constructor can be invoked for a const, volatile or const
3112 // volatile object. A constructor shall not be declared const,
3113 // volatile, or const volatile (9.3.2).
3114 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003115 if (!D.isInvalidType())
3116 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3117 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3118 << SourceRange(D.getIdentifierLoc());
3119 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003120 }
John McCalld931b082010-08-26 03:08:43 +00003121 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003122 if (!D.isInvalidType())
3123 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3124 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3125 << SourceRange(D.getIdentifierLoc());
3126 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003127 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003128 }
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003130 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003131 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003132 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003133 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3134 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003135 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003136 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3137 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003138 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003139 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3140 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003141 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Douglas Gregorc938c162011-01-26 05:01:58 +00003144 // C++0x [class.ctor]p4:
3145 // A constructor shall not be declared with a ref-qualifier.
3146 if (FTI.hasRefQualifier()) {
3147 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3148 << FTI.RefQualifierIsLValueRef
3149 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3150 D.setInvalidType();
3151 }
3152
Douglas Gregor42a552f2008-11-05 20:51:48 +00003153 // Rebuild the function type "R" without any type qualifiers (in
3154 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003155 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003156 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003157 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3158 return R;
3159
3160 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3161 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003162 EPI.RefQualifier = RQ_None;
3163
Chris Lattner65401802009-04-25 08:28:21 +00003164 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003165 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003166}
3167
Douglas Gregor72b505b2008-12-16 21:30:33 +00003168/// CheckConstructor - Checks a fully-formed constructor for
3169/// well-formedness, issuing any diagnostics required. Returns true if
3170/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003171void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003172 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003173 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3174 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003175 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003176
3177 // C++ [class.copy]p3:
3178 // A declaration of a constructor for a class X is ill-formed if
3179 // its first parameter is of type (optionally cv-qualified) X and
3180 // either there are no other parameters or else all other
3181 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003182 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003183 ((Constructor->getNumParams() == 1) ||
3184 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003185 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3186 Constructor->getTemplateSpecializationKind()
3187 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003188 QualType ParamType = Constructor->getParamDecl(0)->getType();
3189 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3190 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003191 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003192 const char *ConstRef
3193 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3194 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003195 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003196 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003197
3198 // FIXME: Rather that making the constructor invalid, we should endeavor
3199 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003200 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003201 }
3202 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003203}
3204
John McCall15442822010-08-04 01:04:25 +00003205/// CheckDestructor - Checks a fully-formed destructor definition for
3206/// well-formedness, issuing any diagnostics required. Returns true
3207/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003208bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003209 CXXRecordDecl *RD = Destructor->getParent();
3210
3211 if (Destructor->isVirtual()) {
3212 SourceLocation Loc;
3213
3214 if (!Destructor->isImplicit())
3215 Loc = Destructor->getLocation();
3216 else
3217 Loc = RD->getLocation();
3218
3219 // If we have a virtual destructor, look up the deallocation function
3220 FunctionDecl *OperatorDelete = 0;
3221 DeclarationName Name =
3222 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003223 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003224 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003225
3226 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003227
3228 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003229 }
Anders Carlsson37909802009-11-30 21:24:50 +00003230
3231 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003232}
3233
Mike Stump1eb44332009-09-09 15:08:12 +00003234static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003235FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3236 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3237 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003238 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003239}
3240
Douglas Gregor42a552f2008-11-05 20:51:48 +00003241/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3242/// the well-formednes of the destructor declarator @p D with type @p
3243/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003244/// emit diagnostics and set the declarator to invalid. Even if this happens,
3245/// will be updated to reflect a well-formed type for the destructor and
3246/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003247QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003248 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003249 // C++ [class.dtor]p1:
3250 // [...] A typedef-name that names a class is a class-name
3251 // (7.1.3); however, a typedef-name that names a class shall not
3252 // be used as the identifier in the declarator for a destructor
3253 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003254 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003255 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003256 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003257 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003258
3259 // C++ [class.dtor]p2:
3260 // A destructor is used to destroy objects of its class type. A
3261 // destructor takes no parameters, and no return type can be
3262 // specified for it (not even void). The address of a destructor
3263 // shall not be taken. A destructor shall not be static. A
3264 // destructor can be invoked for a const, volatile or const
3265 // volatile object. A destructor shall not be declared const,
3266 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003267 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003268 if (!D.isInvalidType())
3269 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3270 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003271 << SourceRange(D.getIdentifierLoc())
3272 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3273
John McCalld931b082010-08-26 03:08:43 +00003274 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003275 }
Chris Lattner65401802009-04-25 08:28:21 +00003276 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003277 // Destructors don't have return types, but the parser will
3278 // happily parse something like:
3279 //
3280 // class X {
3281 // float ~X();
3282 // };
3283 //
3284 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003285 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3286 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3287 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003288 }
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003290 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003291 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003292 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003293 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3294 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003295 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003296 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3297 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003298 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003299 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3300 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003301 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003302 }
3303
Douglas Gregorc938c162011-01-26 05:01:58 +00003304 // C++0x [class.dtor]p2:
3305 // A destructor shall not be declared with a ref-qualifier.
3306 if (FTI.hasRefQualifier()) {
3307 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3308 << FTI.RefQualifierIsLValueRef
3309 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3310 D.setInvalidType();
3311 }
3312
Douglas Gregor42a552f2008-11-05 20:51:48 +00003313 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003314 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003315 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3316
3317 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003318 FTI.freeArgs();
3319 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003320 }
3321
Mike Stump1eb44332009-09-09 15:08:12 +00003322 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003323 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003324 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003325 D.setInvalidType();
3326 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003327
3328 // Rebuild the function type "R" without any type qualifiers or
3329 // parameters (in case any of the errors above fired) and with
3330 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003331 // types.
John McCalle23cf432010-12-14 08:05:40 +00003332 if (!D.isInvalidType())
3333 return R;
3334
Douglas Gregord92ec472010-07-01 05:10:53 +00003335 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003336 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3337 EPI.Variadic = false;
3338 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003339 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003340 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003341}
3342
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003343/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3344/// well-formednes of the conversion function declarator @p D with
3345/// type @p R. If there are any errors in the declarator, this routine
3346/// will emit diagnostics and return true. Otherwise, it will return
3347/// false. Either way, the type @p R will be updated to reflect a
3348/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003349void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003350 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003351 // C++ [class.conv.fct]p1:
3352 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003353 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003354 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003355 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003356 if (!D.isInvalidType())
3357 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3358 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3359 << SourceRange(D.getIdentifierLoc());
3360 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003361 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003362 }
John McCalla3f81372010-04-13 00:04:31 +00003363
3364 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3365
Chris Lattner6e475012009-04-25 08:35:12 +00003366 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003367 // Conversion functions don't have return types, but the parser will
3368 // happily parse something like:
3369 //
3370 // class X {
3371 // float operator bool();
3372 // };
3373 //
3374 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003375 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3376 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3377 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003378 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003379 }
3380
John McCalla3f81372010-04-13 00:04:31 +00003381 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3382
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003383 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003384 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003385 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3386
3387 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003388 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003389 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003390 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003391 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003392 D.setInvalidType();
3393 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003394
John McCalla3f81372010-04-13 00:04:31 +00003395 // Diagnose "&operator bool()" and other such nonsense. This
3396 // is actually a gcc extension which we don't support.
3397 if (Proto->getResultType() != ConvType) {
3398 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3399 << Proto->getResultType();
3400 D.setInvalidType();
3401 ConvType = Proto->getResultType();
3402 }
3403
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003404 // C++ [class.conv.fct]p4:
3405 // The conversion-type-id shall not represent a function type nor
3406 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003407 if (ConvType->isArrayType()) {
3408 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3409 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003410 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003411 } else if (ConvType->isFunctionType()) {
3412 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3413 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003414 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003415 }
3416
3417 // Rebuild the function type "R" without any parameters (in case any
3418 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003419 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003420 if (D.isInvalidType())
3421 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003422
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003423 // C++0x explicit conversion operators.
3424 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003425 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003426 diag::warn_explicit_conversion_functions)
3427 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003428}
3429
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003430/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3431/// the declaration of the given C++ conversion function. This routine
3432/// is responsible for recording the conversion function in the C++
3433/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003434Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003435 assert(Conversion && "Expected to receive a conversion function declaration");
3436
Douglas Gregor9d350972008-12-12 08:25:50 +00003437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003438
3439 // Make sure we aren't redeclaring the conversion function.
3440 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003441
3442 // C++ [class.conv.fct]p1:
3443 // [...] A conversion function is never used to convert a
3444 // (possibly cv-qualified) object to the (possibly cv-qualified)
3445 // same object type (or a reference to it), to a (possibly
3446 // cv-qualified) base class of that type (or a reference to it),
3447 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003448 // FIXME: Suppress this warning if the conversion function ends up being a
3449 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003450 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003451 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003452 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003453 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003454 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3455 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003456 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003457 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003458 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3459 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003460 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003461 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003462 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003463 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003464 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003465 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003466 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003467 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003468 }
3469
Douglas Gregore80622f2010-09-29 04:25:11 +00003470 if (FunctionTemplateDecl *ConversionTemplate
3471 = Conversion->getDescribedFunctionTemplate())
3472 return ConversionTemplate;
3473
John McCalld226f652010-08-21 09:40:31 +00003474 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003475}
3476
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003477//===----------------------------------------------------------------------===//
3478// Namespace Handling
3479//===----------------------------------------------------------------------===//
3480
John McCallea318642010-08-26 09:15:37 +00003481
3482
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003483/// ActOnStartNamespaceDef - This is called at the start of a namespace
3484/// definition.
John McCalld226f652010-08-21 09:40:31 +00003485Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003486 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003487 SourceLocation IdentLoc,
3488 IdentifierInfo *II,
3489 SourceLocation LBrace,
3490 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003491 // anonymous namespace starts at its left brace
3492 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3493 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003494 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003495 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003496
3497 Scope *DeclRegionScope = NamespcScope->getParent();
3498
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003499 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3500
John McCall90f14502010-12-10 02:59:44 +00003501 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3502 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003503
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003504 if (II) {
3505 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003506 // The identifier in an original-namespace-definition shall not
3507 // have been previously defined in the declarative region in
3508 // which the original-namespace-definition appears. The
3509 // identifier in an original-namespace-definition is the name of
3510 // the namespace. Subsequently in that declarative region, it is
3511 // treated as an original-namespace-name.
3512 //
3513 // Since namespace names are unique in their scope, and we don't
3514 // look through using directives, just
3515 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3516 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003517
Douglas Gregor44b43212008-12-11 16:49:14 +00003518 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3519 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003520 if (Namespc->isInline() != OrigNS->isInline()) {
3521 // inline-ness must match
3522 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3523 << Namespc->isInline();
3524 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3525 Namespc->setInvalidDecl();
3526 // Recover by ignoring the new namespace's inline status.
3527 Namespc->setInline(OrigNS->isInline());
3528 }
3529
Douglas Gregor44b43212008-12-11 16:49:14 +00003530 // Attach this namespace decl to the chain of extended namespace
3531 // definitions.
3532 OrigNS->setNextNamespace(Namespc);
3533 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003534
Mike Stump1eb44332009-09-09 15:08:12 +00003535 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003536 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003537 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003538 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003539 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003540 } else if (PrevDecl) {
3541 // This is an invalid name redefinition.
3542 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3543 << Namespc->getDeclName();
3544 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3545 Namespc->setInvalidDecl();
3546 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003547 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003548 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003549 // This is the first "real" definition of the namespace "std", so update
3550 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003551 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003552 // We had already defined a dummy namespace "std". Link this new
3553 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003554 StdNS->setNextNamespace(Namespc);
3555 StdNS->setLocation(IdentLoc);
3556 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003557 }
3558
3559 // Make our StdNamespace cache point at the first real definition of the
3560 // "std" namespace.
3561 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003562 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003563
3564 PushOnScopeChains(Namespc, DeclRegionScope);
3565 } else {
John McCall9aeed322009-10-01 00:25:31 +00003566 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003567 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003568
3569 // Link the anonymous namespace into its parent.
3570 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003571 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003572 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3573 PrevDecl = TU->getAnonymousNamespace();
3574 TU->setAnonymousNamespace(Namespc);
3575 } else {
3576 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3577 PrevDecl = ND->getAnonymousNamespace();
3578 ND->setAnonymousNamespace(Namespc);
3579 }
3580
3581 // Link the anonymous namespace with its previous declaration.
3582 if (PrevDecl) {
3583 assert(PrevDecl->isAnonymousNamespace());
3584 assert(!PrevDecl->getNextNamespace());
3585 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3586 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003587
3588 if (Namespc->isInline() != PrevDecl->isInline()) {
3589 // inline-ness must match
3590 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3591 << Namespc->isInline();
3592 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3593 Namespc->setInvalidDecl();
3594 // Recover by ignoring the new namespace's inline status.
3595 Namespc->setInline(PrevDecl->isInline());
3596 }
John McCall5fdd7642009-12-16 02:06:49 +00003597 }
John McCall9aeed322009-10-01 00:25:31 +00003598
Douglas Gregora4181472010-03-24 00:46:35 +00003599 CurContext->addDecl(Namespc);
3600
John McCall9aeed322009-10-01 00:25:31 +00003601 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3602 // behaves as if it were replaced by
3603 // namespace unique { /* empty body */ }
3604 // using namespace unique;
3605 // namespace unique { namespace-body }
3606 // where all occurrences of 'unique' in a translation unit are
3607 // replaced by the same identifier and this identifier differs
3608 // from all other identifiers in the entire program.
3609
3610 // We just create the namespace with an empty name and then add an
3611 // implicit using declaration, just like the standard suggests.
3612 //
3613 // CodeGen enforces the "universally unique" aspect by giving all
3614 // declarations semantically contained within an anonymous
3615 // namespace internal linkage.
3616
John McCall5fdd7642009-12-16 02:06:49 +00003617 if (!PrevDecl) {
3618 UsingDirectiveDecl* UD
3619 = UsingDirectiveDecl::Create(Context, CurContext,
3620 /* 'using' */ LBrace,
3621 /* 'namespace' */ SourceLocation(),
3622 /* qualifier */ SourceRange(),
3623 /* NNS */ NULL,
3624 /* identifier */ SourceLocation(),
3625 Namespc,
3626 /* Ancestor */ CurContext);
3627 UD->setImplicit();
3628 CurContext->addDecl(UD);
3629 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003630 }
3631
3632 // Although we could have an invalid decl (i.e. the namespace name is a
3633 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003634 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3635 // for the namespace has the declarations that showed up in that particular
3636 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003637 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003638 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003639}
3640
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003641/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3642/// is a namespace alias, returns the namespace it points to.
3643static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3644 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3645 return AD->getNamespace();
3646 return dyn_cast_or_null<NamespaceDecl>(D);
3647}
3648
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003649/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3650/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003651void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003652 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3653 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3654 Namespc->setRBracLoc(RBrace);
3655 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003656 if (Namespc->hasAttr<VisibilityAttr>())
3657 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003658}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003659
John McCall384aff82010-08-25 07:42:41 +00003660CXXRecordDecl *Sema::getStdBadAlloc() const {
3661 return cast_or_null<CXXRecordDecl>(
3662 StdBadAlloc.get(Context.getExternalSource()));
3663}
3664
3665NamespaceDecl *Sema::getStdNamespace() const {
3666 return cast_or_null<NamespaceDecl>(
3667 StdNamespace.get(Context.getExternalSource()));
3668}
3669
Douglas Gregor66992202010-06-29 17:53:46 +00003670/// \brief Retrieve the special "std" namespace, which may require us to
3671/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003672NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003673 if (!StdNamespace) {
3674 // The "std" namespace has not yet been defined, so build one implicitly.
3675 StdNamespace = NamespaceDecl::Create(Context,
3676 Context.getTranslationUnitDecl(),
3677 SourceLocation(),
3678 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003679 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003680 }
3681
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003682 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003683}
3684
John McCalld226f652010-08-21 09:40:31 +00003685Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003686 SourceLocation UsingLoc,
3687 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003688 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003689 SourceLocation IdentLoc,
3690 IdentifierInfo *NamespcName,
3691 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003692 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3693 assert(NamespcName && "Invalid NamespcName.");
3694 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003695
3696 // This can only happen along a recovery path.
3697 while (S->getFlags() & Scope::TemplateParamScope)
3698 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003699 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003700
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003701 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003702 NestedNameSpecifier *Qualifier = 0;
3703 if (SS.isSet())
3704 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3705
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003706 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003707 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3708 LookupParsedName(R, S, &SS);
3709 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003710 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003711
Douglas Gregor66992202010-06-29 17:53:46 +00003712 if (R.empty()) {
3713 // Allow "using namespace std;" or "using namespace ::std;" even if
3714 // "std" hasn't been defined yet, for GCC compatibility.
3715 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3716 NamespcName->isStr("std")) {
3717 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003718 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003719 R.resolveKind();
3720 }
3721 // Otherwise, attempt typo correction.
3722 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3723 CTC_NoKeywords, 0)) {
3724 if (R.getAsSingle<NamespaceDecl>() ||
3725 R.getAsSingle<NamespaceAliasDecl>()) {
3726 if (DeclContext *DC = computeDeclContext(SS, false))
3727 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3728 << NamespcName << DC << Corrected << SS.getRange()
3729 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3730 else
3731 Diag(IdentLoc, diag::err_using_directive_suggest)
3732 << NamespcName << Corrected
3733 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3734 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3735 << Corrected;
3736
3737 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003738 } else {
3739 R.clear();
3740 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003741 }
3742 }
3743 }
3744
John McCallf36e02d2009-10-09 21:13:30 +00003745 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003746 NamedDecl *Named = R.getFoundDecl();
3747 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3748 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003749 // C++ [namespace.udir]p1:
3750 // A using-directive specifies that the names in the nominated
3751 // namespace can be used in the scope in which the
3752 // using-directive appears after the using-directive. During
3753 // unqualified name lookup (3.4.1), the names appear as if they
3754 // were declared in the nearest enclosing namespace which
3755 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003756 // namespace. [Note: in this context, "contains" means "contains
3757 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003758
3759 // Find enclosing context containing both using-directive and
3760 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003761 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003762 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3763 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3764 CommonAncestor = CommonAncestor->getParent();
3765
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003766 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003767 SS.getRange(),
3768 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003769 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003770 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003771 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003772 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003773 }
3774
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003775 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003776 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003777}
3778
3779void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3780 // If scope has associated entity, then using directive is at namespace
3781 // or translation unit scope. We add UsingDirectiveDecls, into
3782 // it's lookup structure.
3783 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003784 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003785 else
3786 // Otherwise it is block-sope. using-directives will affect lookup
3787 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003788 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003789}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003790
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003791
John McCalld226f652010-08-21 09:40:31 +00003792Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003793 AccessSpecifier AS,
3794 bool HasUsingKeyword,
3795 SourceLocation UsingLoc,
3796 CXXScopeSpec &SS,
3797 UnqualifiedId &Name,
3798 AttributeList *AttrList,
3799 bool IsTypeName,
3800 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003801 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Douglas Gregor12c118a2009-11-04 16:30:06 +00003803 switch (Name.getKind()) {
3804 case UnqualifiedId::IK_Identifier:
3805 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003806 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003807 case UnqualifiedId::IK_ConversionFunctionId:
3808 break;
3809
3810 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003811 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003812 // C++0x inherited constructors.
3813 if (getLangOptions().CPlusPlus0x) break;
3814
Douglas Gregor12c118a2009-11-04 16:30:06 +00003815 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3816 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003817 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003818
3819 case UnqualifiedId::IK_DestructorName:
3820 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3821 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003822 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003823
3824 case UnqualifiedId::IK_TemplateId:
3825 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3826 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003827 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003828 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003829
3830 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3831 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003832 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003833 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003834
John McCall60fa3cf2009-12-11 02:10:03 +00003835 // Warn about using declarations.
3836 // TODO: store that the declaration was written without 'using' and
3837 // talk about access decls instead of using decls in the
3838 // diagnostics.
3839 if (!HasUsingKeyword) {
3840 UsingLoc = Name.getSourceRange().getBegin();
3841
3842 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003843 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003844 }
3845
Douglas Gregor56c04582010-12-16 00:46:58 +00003846 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3847 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3848 return 0;
3849
John McCall9488ea12009-11-17 05:59:44 +00003850 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003851 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003852 /* IsInstantiation */ false,
3853 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003854 if (UD)
3855 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003856
John McCalld226f652010-08-21 09:40:31 +00003857 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003858}
3859
Douglas Gregor09acc982010-07-07 23:08:52 +00003860/// \brief Determine whether a using declaration considers the given
3861/// declarations as "equivalent", e.g., if they are redeclarations of
3862/// the same entity or are both typedefs of the same type.
3863static bool
3864IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3865 bool &SuppressRedeclaration) {
3866 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3867 SuppressRedeclaration = false;
3868 return true;
3869 }
3870
3871 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3872 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3873 SuppressRedeclaration = true;
3874 return Context.hasSameType(TD1->getUnderlyingType(),
3875 TD2->getUnderlyingType());
3876 }
3877
3878 return false;
3879}
3880
3881
John McCall9f54ad42009-12-10 09:41:52 +00003882/// Determines whether to create a using shadow decl for a particular
3883/// decl, given the set of decls existing prior to this using lookup.
3884bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3885 const LookupResult &Previous) {
3886 // Diagnose finding a decl which is not from a base class of the
3887 // current class. We do this now because there are cases where this
3888 // function will silently decide not to build a shadow decl, which
3889 // will pre-empt further diagnostics.
3890 //
3891 // We don't need to do this in C++0x because we do the check once on
3892 // the qualifier.
3893 //
3894 // FIXME: diagnose the following if we care enough:
3895 // struct A { int foo; };
3896 // struct B : A { using A::foo; };
3897 // template <class T> struct C : A {};
3898 // template <class T> struct D : C<T> { using B::foo; } // <---
3899 // This is invalid (during instantiation) in C++03 because B::foo
3900 // resolves to the using decl in B, which is not a base class of D<T>.
3901 // We can't diagnose it immediately because C<T> is an unknown
3902 // specialization. The UsingShadowDecl in D<T> then points directly
3903 // to A::foo, which will look well-formed when we instantiate.
3904 // The right solution is to not collapse the shadow-decl chain.
3905 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3906 DeclContext *OrigDC = Orig->getDeclContext();
3907
3908 // Handle enums and anonymous structs.
3909 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3910 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3911 while (OrigRec->isAnonymousStructOrUnion())
3912 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3913
3914 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3915 if (OrigDC == CurContext) {
3916 Diag(Using->getLocation(),
3917 diag::err_using_decl_nested_name_specifier_is_current_class)
3918 << Using->getNestedNameRange();
3919 Diag(Orig->getLocation(), diag::note_using_decl_target);
3920 return true;
3921 }
3922
3923 Diag(Using->getNestedNameRange().getBegin(),
3924 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3925 << Using->getTargetNestedNameDecl()
3926 << cast<CXXRecordDecl>(CurContext)
3927 << Using->getNestedNameRange();
3928 Diag(Orig->getLocation(), diag::note_using_decl_target);
3929 return true;
3930 }
3931 }
3932
3933 if (Previous.empty()) return false;
3934
3935 NamedDecl *Target = Orig;
3936 if (isa<UsingShadowDecl>(Target))
3937 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3938
John McCalld7533ec2009-12-11 02:33:26 +00003939 // If the target happens to be one of the previous declarations, we
3940 // don't have a conflict.
3941 //
3942 // FIXME: but we might be increasing its access, in which case we
3943 // should redeclare it.
3944 NamedDecl *NonTag = 0, *Tag = 0;
3945 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3946 I != E; ++I) {
3947 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003948 bool Result;
3949 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3950 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003951
3952 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3953 }
3954
John McCall9f54ad42009-12-10 09:41:52 +00003955 if (Target->isFunctionOrFunctionTemplate()) {
3956 FunctionDecl *FD;
3957 if (isa<FunctionTemplateDecl>(Target))
3958 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3959 else
3960 FD = cast<FunctionDecl>(Target);
3961
3962 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003963 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003964 case Ovl_Overload:
3965 return false;
3966
3967 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003968 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003969 break;
3970
3971 // We found a decl with the exact signature.
3972 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003973 // If we're in a record, we want to hide the target, so we
3974 // return true (without a diagnostic) to tell the caller not to
3975 // build a shadow decl.
3976 if (CurContext->isRecord())
3977 return true;
3978
3979 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003980 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003981 break;
3982 }
3983
3984 Diag(Target->getLocation(), diag::note_using_decl_target);
3985 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3986 return true;
3987 }
3988
3989 // Target is not a function.
3990
John McCall9f54ad42009-12-10 09:41:52 +00003991 if (isa<TagDecl>(Target)) {
3992 // No conflict between a tag and a non-tag.
3993 if (!Tag) return false;
3994
John McCall41ce66f2009-12-10 19:51:03 +00003995 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003996 Diag(Target->getLocation(), diag::note_using_decl_target);
3997 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3998 return true;
3999 }
4000
4001 // No conflict between a tag and a non-tag.
4002 if (!NonTag) return false;
4003
John McCall41ce66f2009-12-10 19:51:03 +00004004 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004005 Diag(Target->getLocation(), diag::note_using_decl_target);
4006 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4007 return true;
4008}
4009
John McCall9488ea12009-11-17 05:59:44 +00004010/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004011UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004012 UsingDecl *UD,
4013 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004014
4015 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004016 NamedDecl *Target = Orig;
4017 if (isa<UsingShadowDecl>(Target)) {
4018 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4019 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004020 }
4021
4022 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004023 = UsingShadowDecl::Create(Context, CurContext,
4024 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004025 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004026
4027 Shadow->setAccess(UD->getAccess());
4028 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4029 Shadow->setInvalidDecl();
4030
John McCall9488ea12009-11-17 05:59:44 +00004031 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004032 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004033 else
John McCall604e7f12009-12-08 07:46:18 +00004034 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004035
John McCall604e7f12009-12-08 07:46:18 +00004036
John McCall9f54ad42009-12-10 09:41:52 +00004037 return Shadow;
4038}
John McCall604e7f12009-12-08 07:46:18 +00004039
John McCall9f54ad42009-12-10 09:41:52 +00004040/// Hides a using shadow declaration. This is required by the current
4041/// using-decl implementation when a resolvable using declaration in a
4042/// class is followed by a declaration which would hide or override
4043/// one or more of the using decl's targets; for example:
4044///
4045/// struct Base { void foo(int); };
4046/// struct Derived : Base {
4047/// using Base::foo;
4048/// void foo(int);
4049/// };
4050///
4051/// The governing language is C++03 [namespace.udecl]p12:
4052///
4053/// When a using-declaration brings names from a base class into a
4054/// derived class scope, member functions in the derived class
4055/// override and/or hide member functions with the same name and
4056/// parameter types in a base class (rather than conflicting).
4057///
4058/// There are two ways to implement this:
4059/// (1) optimistically create shadow decls when they're not hidden
4060/// by existing declarations, or
4061/// (2) don't create any shadow decls (or at least don't make them
4062/// visible) until we've fully parsed/instantiated the class.
4063/// The problem with (1) is that we might have to retroactively remove
4064/// a shadow decl, which requires several O(n) operations because the
4065/// decl structures are (very reasonably) not designed for removal.
4066/// (2) avoids this but is very fiddly and phase-dependent.
4067void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004068 if (Shadow->getDeclName().getNameKind() ==
4069 DeclarationName::CXXConversionFunctionName)
4070 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4071
John McCall9f54ad42009-12-10 09:41:52 +00004072 // Remove it from the DeclContext...
4073 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004074
John McCall9f54ad42009-12-10 09:41:52 +00004075 // ...and the scope, if applicable...
4076 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004077 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004078 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004079 }
4080
John McCall9f54ad42009-12-10 09:41:52 +00004081 // ...and the using decl.
4082 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4083
4084 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004085 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004086}
4087
John McCall7ba107a2009-11-18 02:36:19 +00004088/// Builds a using declaration.
4089///
4090/// \param IsInstantiation - Whether this call arises from an
4091/// instantiation of an unresolved using declaration. We treat
4092/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004093NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4094 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004095 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004096 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004097 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004098 bool IsInstantiation,
4099 bool IsTypeName,
4100 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004101 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004102 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004103 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004104
Anders Carlsson550b14b2009-08-28 05:49:21 +00004105 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004107 if (SS.isEmpty()) {
4108 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004109 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004110 }
Mike Stump1eb44332009-09-09 15:08:12 +00004111
John McCall9f54ad42009-12-10 09:41:52 +00004112 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004113 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004114 ForRedeclaration);
4115 Previous.setHideTags(false);
4116 if (S) {
4117 LookupName(Previous, S);
4118
4119 // It is really dumb that we have to do this.
4120 LookupResult::Filter F = Previous.makeFilter();
4121 while (F.hasNext()) {
4122 NamedDecl *D = F.next();
4123 if (!isDeclInScope(D, CurContext, S))
4124 F.erase();
4125 }
4126 F.done();
4127 } else {
4128 assert(IsInstantiation && "no scope in non-instantiation");
4129 assert(CurContext->isRecord() && "scope not record in instantiation");
4130 LookupQualifiedName(Previous, CurContext);
4131 }
4132
Sebastian Redlf677ea32011-02-05 19:23:19 +00004133 NestedNameSpecifier *NNS = SS.getScopeRep();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004134
John McCall9f54ad42009-12-10 09:41:52 +00004135 // Check for invalid redeclarations.
4136 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4137 return 0;
4138
4139 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004140 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4141 return 0;
4142
John McCallaf8e6ed2009-11-12 03:15:40 +00004143 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004144 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00004145 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004146 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004147 // FIXME: not all declaration name kinds are legal here
4148 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4149 UsingLoc, TypenameLoc,
4150 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004151 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004152 } else {
4153 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004154 UsingLoc, SS.getRange(),
4155 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004156 }
John McCalled976492009-12-04 22:46:56 +00004157 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004158 D = UsingDecl::Create(Context, CurContext,
4159 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00004160 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004161 }
John McCalled976492009-12-04 22:46:56 +00004162 D->setAccess(AS);
4163 CurContext->addDecl(D);
4164
4165 if (!LookupContext) return D;
4166 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004167
John McCall77bb1aa2010-05-01 00:40:08 +00004168 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004169 UD->setInvalidDecl();
4170 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004171 }
4172
Sebastian Redlf677ea32011-02-05 19:23:19 +00004173 // Constructor inheriting using decls get special treatment.
4174 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4175 if (CheckInheritedConstructorUsingDecl(UD))
4176 UD->setInvalidDecl();
4177 return UD;
4178 }
4179
4180 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004181
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004182 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004183
John McCall604e7f12009-12-08 07:46:18 +00004184 // Unlike most lookups, we don't always want to hide tag
4185 // declarations: tag names are visible through the using declaration
4186 // even if hidden by ordinary names, *except* in a dependent context
4187 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004188 if (!IsInstantiation)
4189 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004190
John McCalla24dc2e2009-11-17 02:14:36 +00004191 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004192
John McCallf36e02d2009-10-09 21:13:30 +00004193 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004194 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004195 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004196 UD->setInvalidDecl();
4197 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004198 }
4199
John McCalled976492009-12-04 22:46:56 +00004200 if (R.isAmbiguous()) {
4201 UD->setInvalidDecl();
4202 return UD;
4203 }
Mike Stump1eb44332009-09-09 15:08:12 +00004204
John McCall7ba107a2009-11-18 02:36:19 +00004205 if (IsTypeName) {
4206 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004207 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004208 Diag(IdentLoc, diag::err_using_typename_non_type);
4209 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4210 Diag((*I)->getUnderlyingDecl()->getLocation(),
4211 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004212 UD->setInvalidDecl();
4213 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004214 }
4215 } else {
4216 // If we asked for a non-typename and we got a type, error out,
4217 // but only if this is an instantiation of an unresolved using
4218 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004219 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004220 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4221 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004222 UD->setInvalidDecl();
4223 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004224 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004225 }
4226
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004227 // C++0x N2914 [namespace.udecl]p6:
4228 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004229 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004230 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4231 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004232 UD->setInvalidDecl();
4233 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004234 }
Mike Stump1eb44332009-09-09 15:08:12 +00004235
John McCall9f54ad42009-12-10 09:41:52 +00004236 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4237 if (!CheckUsingShadowDecl(UD, *I, Previous))
4238 BuildUsingShadowDecl(S, UD, *I);
4239 }
John McCall9488ea12009-11-17 05:59:44 +00004240
4241 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004242}
4243
Sebastian Redlf677ea32011-02-05 19:23:19 +00004244/// Additional checks for a using declaration referring to a constructor name.
4245bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4246 if (UD->isTypeName()) {
4247 // FIXME: Cannot specify typename when specifying constructor
4248 return true;
4249 }
4250
4251 const Type *SourceType = UD->getTargetNestedNameDecl()->getAsType();
4252 assert(SourceType &&
4253 "Using decl naming constructor doesn't have type in scope spec.");
4254 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4255
4256 // Check whether the named type is a direct base class.
4257 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4258 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4259 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4260 BaseIt != BaseE; ++BaseIt) {
4261 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4262 if (CanonicalSourceType == BaseType)
4263 break;
4264 }
4265
4266 if (BaseIt == BaseE) {
4267 // Did not find SourceType in the bases.
4268 Diag(UD->getUsingLocation(),
4269 diag::err_using_decl_constructor_not_in_direct_base)
4270 << UD->getNameInfo().getSourceRange()
4271 << QualType(SourceType, 0) << TargetClass;
4272 return true;
4273 }
4274
4275 BaseIt->setInheritConstructors();
4276
4277 return false;
4278}
4279
John McCall9f54ad42009-12-10 09:41:52 +00004280/// Checks that the given using declaration is not an invalid
4281/// redeclaration. Note that this is checking only for the using decl
4282/// itself, not for any ill-formedness among the UsingShadowDecls.
4283bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4284 bool isTypeName,
4285 const CXXScopeSpec &SS,
4286 SourceLocation NameLoc,
4287 const LookupResult &Prev) {
4288 // C++03 [namespace.udecl]p8:
4289 // C++0x [namespace.udecl]p10:
4290 // A using-declaration is a declaration and can therefore be used
4291 // repeatedly where (and only where) multiple declarations are
4292 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004293 //
John McCall8a726212010-11-29 18:01:58 +00004294 // That's in non-member contexts.
4295 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004296 return false;
4297
4298 NestedNameSpecifier *Qual
4299 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4300
4301 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4302 NamedDecl *D = *I;
4303
4304 bool DTypename;
4305 NestedNameSpecifier *DQual;
4306 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4307 DTypename = UD->isTypeName();
4308 DQual = UD->getTargetNestedNameDecl();
4309 } else if (UnresolvedUsingValueDecl *UD
4310 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4311 DTypename = false;
4312 DQual = UD->getTargetNestedNameSpecifier();
4313 } else if (UnresolvedUsingTypenameDecl *UD
4314 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4315 DTypename = true;
4316 DQual = UD->getTargetNestedNameSpecifier();
4317 } else continue;
4318
4319 // using decls differ if one says 'typename' and the other doesn't.
4320 // FIXME: non-dependent using decls?
4321 if (isTypeName != DTypename) continue;
4322
4323 // using decls differ if they name different scopes (but note that
4324 // template instantiation can cause this check to trigger when it
4325 // didn't before instantiation).
4326 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4327 Context.getCanonicalNestedNameSpecifier(DQual))
4328 continue;
4329
4330 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004331 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004332 return true;
4333 }
4334
4335 return false;
4336}
4337
John McCall604e7f12009-12-08 07:46:18 +00004338
John McCalled976492009-12-04 22:46:56 +00004339/// Checks that the given nested-name qualifier used in a using decl
4340/// in the current context is appropriately related to the current
4341/// scope. If an error is found, diagnoses it and returns true.
4342bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4343 const CXXScopeSpec &SS,
4344 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004345 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004346
John McCall604e7f12009-12-08 07:46:18 +00004347 if (!CurContext->isRecord()) {
4348 // C++03 [namespace.udecl]p3:
4349 // C++0x [namespace.udecl]p8:
4350 // A using-declaration for a class member shall be a member-declaration.
4351
4352 // If we weren't able to compute a valid scope, it must be a
4353 // dependent class scope.
4354 if (!NamedContext || NamedContext->isRecord()) {
4355 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4356 << SS.getRange();
4357 return true;
4358 }
4359
4360 // Otherwise, everything is known to be fine.
4361 return false;
4362 }
4363
4364 // The current scope is a record.
4365
4366 // If the named context is dependent, we can't decide much.
4367 if (!NamedContext) {
4368 // FIXME: in C++0x, we can diagnose if we can prove that the
4369 // nested-name-specifier does not refer to a base class, which is
4370 // still possible in some cases.
4371
4372 // Otherwise we have to conservatively report that things might be
4373 // okay.
4374 return false;
4375 }
4376
4377 if (!NamedContext->isRecord()) {
4378 // Ideally this would point at the last name in the specifier,
4379 // but we don't have that level of source info.
4380 Diag(SS.getRange().getBegin(),
4381 diag::err_using_decl_nested_name_specifier_is_not_class)
4382 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4383 return true;
4384 }
4385
Douglas Gregor6fb07292010-12-21 07:41:49 +00004386 if (!NamedContext->isDependentContext() &&
4387 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4388 return true;
4389
John McCall604e7f12009-12-08 07:46:18 +00004390 if (getLangOptions().CPlusPlus0x) {
4391 // C++0x [namespace.udecl]p3:
4392 // In a using-declaration used as a member-declaration, the
4393 // nested-name-specifier shall name a base class of the class
4394 // being defined.
4395
4396 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4397 cast<CXXRecordDecl>(NamedContext))) {
4398 if (CurContext == NamedContext) {
4399 Diag(NameLoc,
4400 diag::err_using_decl_nested_name_specifier_is_current_class)
4401 << SS.getRange();
4402 return true;
4403 }
4404
4405 Diag(SS.getRange().getBegin(),
4406 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4407 << (NestedNameSpecifier*) SS.getScopeRep()
4408 << cast<CXXRecordDecl>(CurContext)
4409 << SS.getRange();
4410 return true;
4411 }
4412
4413 return false;
4414 }
4415
4416 // C++03 [namespace.udecl]p4:
4417 // A using-declaration used as a member-declaration shall refer
4418 // to a member of a base class of the class being defined [etc.].
4419
4420 // Salient point: SS doesn't have to name a base class as long as
4421 // lookup only finds members from base classes. Therefore we can
4422 // diagnose here only if we can prove that that can't happen,
4423 // i.e. if the class hierarchies provably don't intersect.
4424
4425 // TODO: it would be nice if "definitely valid" results were cached
4426 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4427 // need to be repeated.
4428
4429 struct UserData {
4430 llvm::DenseSet<const CXXRecordDecl*> Bases;
4431
4432 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4433 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4434 Data->Bases.insert(Base);
4435 return true;
4436 }
4437
4438 bool hasDependentBases(const CXXRecordDecl *Class) {
4439 return !Class->forallBases(collect, this);
4440 }
4441
4442 /// Returns true if the base is dependent or is one of the
4443 /// accumulated base classes.
4444 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4445 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4446 return !Data->Bases.count(Base);
4447 }
4448
4449 bool mightShareBases(const CXXRecordDecl *Class) {
4450 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4451 }
4452 };
4453
4454 UserData Data;
4455
4456 // Returns false if we find a dependent base.
4457 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4458 return false;
4459
4460 // Returns false if the class has a dependent base or if it or one
4461 // of its bases is present in the base set of the current context.
4462 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4463 return false;
4464
4465 Diag(SS.getRange().getBegin(),
4466 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4467 << (NestedNameSpecifier*) SS.getScopeRep()
4468 << cast<CXXRecordDecl>(CurContext)
4469 << SS.getRange();
4470
4471 return true;
John McCalled976492009-12-04 22:46:56 +00004472}
4473
John McCalld226f652010-08-21 09:40:31 +00004474Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004475 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004476 SourceLocation AliasLoc,
4477 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004478 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004479 SourceLocation IdentLoc,
4480 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004481
Anders Carlsson81c85c42009-03-28 23:53:49 +00004482 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004483 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4484 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004485
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004486 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004487 NamedDecl *PrevDecl
4488 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4489 ForRedeclaration);
4490 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4491 PrevDecl = 0;
4492
4493 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004494 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004495 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004496 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004497 // FIXME: At some point, we'll want to create the (redundant)
4498 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004499 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004500 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004501 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004502 }
Mike Stump1eb44332009-09-09 15:08:12 +00004503
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004504 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4505 diag::err_redefinition_different_kind;
4506 Diag(AliasLoc, DiagID) << Alias;
4507 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004508 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004509 }
4510
John McCalla24dc2e2009-11-17 02:14:36 +00004511 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004512 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004513
John McCallf36e02d2009-10-09 21:13:30 +00004514 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004515 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4516 CTC_NoKeywords, 0)) {
4517 if (R.getAsSingle<NamespaceDecl>() ||
4518 R.getAsSingle<NamespaceAliasDecl>()) {
4519 if (DeclContext *DC = computeDeclContext(SS, false))
4520 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4521 << Ident << DC << Corrected << SS.getRange()
4522 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4523 else
4524 Diag(IdentLoc, diag::err_using_directive_suggest)
4525 << Ident << Corrected
4526 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4527
4528 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4529 << Corrected;
4530
4531 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004532 } else {
4533 R.clear();
4534 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004535 }
4536 }
4537
4538 if (R.empty()) {
4539 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004540 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004541 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004542 }
Mike Stump1eb44332009-09-09 15:08:12 +00004543
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004544 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004545 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4546 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004547 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004548 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004549
John McCall3dbd3d52010-02-16 06:53:13 +00004550 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004551 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004552}
4553
Douglas Gregor39957dc2010-05-01 15:04:51 +00004554namespace {
4555 /// \brief Scoped object used to handle the state changes required in Sema
4556 /// to implicitly define the body of a C++ member function;
4557 class ImplicitlyDefinedFunctionScope {
4558 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004559 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004560
4561 public:
4562 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004563 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004564 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004565 S.PushFunctionScope();
4566 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4567 }
4568
4569 ~ImplicitlyDefinedFunctionScope() {
4570 S.PopExpressionEvaluationContext();
4571 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004572 }
4573 };
4574}
4575
Sebastian Redl751025d2010-09-13 22:02:47 +00004576static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4577 CXXRecordDecl *D) {
4578 ASTContext &Context = Self.Context;
4579 QualType ClassType = Context.getTypeDeclType(D);
4580 DeclarationName ConstructorName
4581 = Context.DeclarationNames.getCXXConstructorName(
4582 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4583
4584 DeclContext::lookup_const_iterator Con, ConEnd;
4585 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4586 Con != ConEnd; ++Con) {
4587 // FIXME: In C++0x, a constructor template can be a default constructor.
4588 if (isa<FunctionTemplateDecl>(*Con))
4589 continue;
4590
4591 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4592 if (Constructor->isDefaultConstructor())
4593 return Constructor;
4594 }
4595 return 0;
4596}
4597
Douglas Gregor23c94db2010-07-02 17:43:08 +00004598CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4599 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004600 // C++ [class.ctor]p5:
4601 // A default constructor for a class X is a constructor of class X
4602 // that can be called without an argument. If there is no
4603 // user-declared constructor for class X, a default constructor is
4604 // implicitly declared. An implicitly-declared default constructor
4605 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004606 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4607 "Should not build implicit default constructor!");
4608
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004609 // C++ [except.spec]p14:
4610 // An implicitly declared special member function (Clause 12) shall have an
4611 // exception-specification. [...]
4612 ImplicitExceptionSpecification ExceptSpec(Context);
4613
4614 // Direct base-class destructors.
4615 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4616 BEnd = ClassDecl->bases_end();
4617 B != BEnd; ++B) {
4618 if (B->isVirtual()) // Handled below.
4619 continue;
4620
Douglas Gregor18274032010-07-03 00:47:00 +00004621 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4622 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4623 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4624 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004625 else if (CXXConstructorDecl *Constructor
4626 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004627 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004628 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004629 }
4630
4631 // Virtual base-class destructors.
4632 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4633 BEnd = ClassDecl->vbases_end();
4634 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004635 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4636 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4637 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4638 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4639 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004640 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004641 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004642 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004643 }
4644
4645 // Field destructors.
4646 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4647 FEnd = ClassDecl->field_end();
4648 F != FEnd; ++F) {
4649 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004650 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4651 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4652 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4653 ExceptSpec.CalledDecl(
4654 DeclareImplicitDefaultConstructor(FieldClassDecl));
4655 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004656 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004657 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004658 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004659 }
John McCalle23cf432010-12-14 08:05:40 +00004660
4661 FunctionProtoType::ExtProtoInfo EPI;
4662 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4663 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4664 EPI.NumExceptions = ExceptSpec.size();
4665 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004666
4667 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004668 CanQualType ClassType
4669 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4670 DeclarationName Name
4671 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004672 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004673 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004674 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004675 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004676 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004677 /*TInfo=*/0,
4678 /*isExplicit=*/false,
4679 /*isInline=*/true,
4680 /*isImplicitlyDeclared=*/true);
4681 DefaultCon->setAccess(AS_public);
4682 DefaultCon->setImplicit();
4683 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004684
4685 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004686 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4687
Douglas Gregor23c94db2010-07-02 17:43:08 +00004688 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004689 PushOnScopeChains(DefaultCon, S, false);
4690 ClassDecl->addDecl(DefaultCon);
4691
Douglas Gregor32df23e2010-07-01 22:02:46 +00004692 return DefaultCon;
4693}
4694
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004695void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4696 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004697 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004698 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004699 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004700
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004701 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004702 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004703
Douglas Gregor39957dc2010-05-01 15:04:51 +00004704 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004705 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004706 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004707 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004708 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004709 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004710 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004711 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004712 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004713
4714 SourceLocation Loc = Constructor->getLocation();
4715 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4716
4717 Constructor->setUsed();
4718 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004719}
4720
Sebastian Redlf677ea32011-02-05 19:23:19 +00004721void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4722 // We start with an initial pass over the base classes to collect those that
4723 // inherit constructors from. If there are none, we can forgo all further
4724 // processing.
4725 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4726 BasesVector BasesToInheritFrom;
4727 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4728 BaseE = ClassDecl->bases_end();
4729 BaseIt != BaseE; ++BaseIt) {
4730 if (BaseIt->getInheritConstructors()) {
4731 QualType Base = BaseIt->getType();
4732 if (Base->isDependentType()) {
4733 // If we inherit constructors from anything that is dependent, just
4734 // abort processing altogether. We'll get another chance for the
4735 // instantiations.
4736 return;
4737 }
4738 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4739 }
4740 }
4741 if (BasesToInheritFrom.empty())
4742 return;
4743
4744 // Now collect the constructors that we already have in the current class.
4745 // Those take precedence over inherited constructors.
4746 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4747 // unless there is a user-declared constructor with the same signature in
4748 // the class where the using-declaration appears.
4749 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4750 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4751 CtorE = ClassDecl->ctor_end();
4752 CtorIt != CtorE; ++CtorIt) {
4753 ExistingConstructors.insert(
4754 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4755 }
4756
4757 Scope *S = getScopeForContext(ClassDecl);
4758 DeclarationName CreatedCtorName =
4759 Context.DeclarationNames.getCXXConstructorName(
4760 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4761
4762 // Now comes the true work.
4763 // First, we keep a map from constructor types to the base that introduced
4764 // them. Needed for finding conflicting constructors. We also keep the
4765 // actually inserted declarations in there, for pretty diagnostics.
4766 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4767 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4768 ConstructorToSourceMap InheritedConstructors;
4769 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4770 BaseE = BasesToInheritFrom.end();
4771 BaseIt != BaseE; ++BaseIt) {
4772 const RecordType *Base = *BaseIt;
4773 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4774 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4775 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4776 CtorE = BaseDecl->ctor_end();
4777 CtorIt != CtorE; ++CtorIt) {
4778 // Find the using declaration for inheriting this base's constructors.
4779 DeclarationName Name =
4780 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4781 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4782 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4783 SourceLocation UsingLoc = UD ? UD->getLocation() :
4784 ClassDecl->getLocation();
4785
4786 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4787 // from the class X named in the using-declaration consists of actual
4788 // constructors and notional constructors that result from the
4789 // transformation of defaulted parameters as follows:
4790 // - all non-template default constructors of X, and
4791 // - for each non-template constructor of X that has at least one
4792 // parameter with a default argument, the set of constructors that
4793 // results from omitting any ellipsis parameter specification and
4794 // successively omitting parameters with a default argument from the
4795 // end of the parameter-type-list.
4796 CXXConstructorDecl *BaseCtor = *CtorIt;
4797 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4798 const FunctionProtoType *BaseCtorType =
4799 BaseCtor->getType()->getAs<FunctionProtoType>();
4800
4801 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4802 maxParams = BaseCtor->getNumParams();
4803 params <= maxParams; ++params) {
4804 // Skip default constructors. They're never inherited.
4805 if (params == 0)
4806 continue;
4807 // Skip copy and move constructors for the same reason.
4808 if (CanBeCopyOrMove && params == 1)
4809 continue;
4810
4811 // Build up a function type for this particular constructor.
4812 // FIXME: The working paper does not consider that the exception spec
4813 // for the inheriting constructor might be larger than that of the
4814 // source. This code doesn't yet, either.
4815 const Type *NewCtorType;
4816 if (params == maxParams)
4817 NewCtorType = BaseCtorType;
4818 else {
4819 llvm::SmallVector<QualType, 16> Args;
4820 for (unsigned i = 0; i < params; ++i) {
4821 Args.push_back(BaseCtorType->getArgType(i));
4822 }
4823 FunctionProtoType::ExtProtoInfo ExtInfo =
4824 BaseCtorType->getExtProtoInfo();
4825 ExtInfo.Variadic = false;
4826 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4827 Args.data(), params, ExtInfo)
4828 .getTypePtr();
4829 }
4830 const Type *CanonicalNewCtorType =
4831 Context.getCanonicalType(NewCtorType);
4832
4833 // Now that we have the type, first check if the class already has a
4834 // constructor with this signature.
4835 if (ExistingConstructors.count(CanonicalNewCtorType))
4836 continue;
4837
4838 // Then we check if we have already declared an inherited constructor
4839 // with this signature.
4840 std::pair<ConstructorToSourceMap::iterator, bool> result =
4841 InheritedConstructors.insert(std::make_pair(
4842 CanonicalNewCtorType,
4843 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
4844 if (!result.second) {
4845 // Already in the map. If it came from a different class, that's an
4846 // error. Not if it's from the same.
4847 CanQualType PreviousBase = result.first->second.first;
4848 if (CanonicalBase != PreviousBase) {
4849 const CXXConstructorDecl *PrevCtor = result.first->second.second;
4850 const CXXConstructorDecl *PrevBaseCtor =
4851 PrevCtor->getInheritedConstructor();
4852 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
4853
4854 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
4855 Diag(BaseCtor->getLocation(),
4856 diag::note_using_decl_constructor_conflict_current_ctor);
4857 Diag(PrevBaseCtor->getLocation(),
4858 diag::note_using_decl_constructor_conflict_previous_ctor);
4859 Diag(PrevCtor->getLocation(),
4860 diag::note_using_decl_constructor_conflict_previous_using);
4861 }
4862 continue;
4863 }
4864
4865 // OK, we're there, now add the constructor.
4866 // C++0x [class.inhctor]p8: [...] that would be performed by a
4867 // user-writtern inline constructor [...]
4868 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
4869 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
4870 Context, ClassDecl, DNI, QualType(NewCtorType, 0), /*TInfo=*/0,
4871 BaseCtor->isExplicit(), /*Inline=*/true,
4872 /*ImplicitlyDeclared=*/true);
4873 NewCtor->setAccess(BaseCtor->getAccess());
4874
4875 // Build up the parameter decls and add them.
4876 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
4877 for (unsigned i = 0; i < params; ++i) {
4878 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, UsingLoc,
4879 /*IdentifierInfo=*/0,
4880 BaseCtorType->getArgType(i),
4881 /*TInfo=*/0, SC_None,
4882 SC_None, /*DefaultArg=*/0));
4883 }
4884 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
4885 NewCtor->setInheritedConstructor(BaseCtor);
4886
4887 PushOnScopeChains(NewCtor, S, false);
4888 ClassDecl->addDecl(NewCtor);
4889 result.first->second.second = NewCtor;
4890 }
4891 }
4892 }
4893}
4894
Douglas Gregor23c94db2010-07-02 17:43:08 +00004895CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004896 // C++ [class.dtor]p2:
4897 // If a class has no user-declared destructor, a destructor is
4898 // declared implicitly. An implicitly-declared destructor is an
4899 // inline public member of its class.
4900
4901 // C++ [except.spec]p14:
4902 // An implicitly declared special member function (Clause 12) shall have
4903 // an exception-specification.
4904 ImplicitExceptionSpecification ExceptSpec(Context);
4905
4906 // Direct base-class destructors.
4907 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4908 BEnd = ClassDecl->bases_end();
4909 B != BEnd; ++B) {
4910 if (B->isVirtual()) // Handled below.
4911 continue;
4912
4913 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4914 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004915 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004916 }
4917
4918 // Virtual base-class destructors.
4919 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4920 BEnd = ClassDecl->vbases_end();
4921 B != BEnd; ++B) {
4922 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4923 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004924 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004925 }
4926
4927 // Field destructors.
4928 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4929 FEnd = ClassDecl->field_end();
4930 F != FEnd; ++F) {
4931 if (const RecordType *RecordTy
4932 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4933 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004934 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004935 }
4936
Douglas Gregor4923aa22010-07-02 20:37:36 +00004937 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004938 FunctionProtoType::ExtProtoInfo EPI;
4939 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4940 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4941 EPI.NumExceptions = ExceptSpec.size();
4942 EPI.Exceptions = ExceptSpec.data();
4943 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004944
4945 CanQualType ClassType
4946 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4947 DeclarationName Name
4948 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004949 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004950 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004951 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004952 /*isInline=*/true,
4953 /*isImplicitlyDeclared=*/true);
4954 Destructor->setAccess(AS_public);
4955 Destructor->setImplicit();
4956 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004957
4958 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004959 ++ASTContext::NumImplicitDestructorsDeclared;
4960
4961 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004962 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004963 PushOnScopeChains(Destructor, S, false);
4964 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004965
4966 // This could be uniqued if it ever proves significant.
4967 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4968
4969 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004970
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004971 return Destructor;
4972}
4973
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004974void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004975 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004976 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004977 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004978 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004979 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004980
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004981 if (Destructor->isInvalidDecl())
4982 return;
4983
Douglas Gregor39957dc2010-05-01 15:04:51 +00004984 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004985
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004986 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004987 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4988 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004989
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004990 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004991 Diag(CurrentLocation, diag::note_member_synthesized_at)
4992 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4993
4994 Destructor->setInvalidDecl();
4995 return;
4996 }
4997
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004998 SourceLocation Loc = Destructor->getLocation();
4999 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5000
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005001 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005002 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005003}
5004
Douglas Gregor06a9f362010-05-01 20:49:11 +00005005/// \brief Builds a statement that copies the given entity from \p From to
5006/// \c To.
5007///
5008/// This routine is used to copy the members of a class with an
5009/// implicitly-declared copy assignment operator. When the entities being
5010/// copied are arrays, this routine builds for loops to copy them.
5011///
5012/// \param S The Sema object used for type-checking.
5013///
5014/// \param Loc The location where the implicit copy is being generated.
5015///
5016/// \param T The type of the expressions being copied. Both expressions must
5017/// have this type.
5018///
5019/// \param To The expression we are copying to.
5020///
5021/// \param From The expression we are copying from.
5022///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005023/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5024/// Otherwise, it's a non-static member subobject.
5025///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005026/// \param Depth Internal parameter recording the depth of the recursion.
5027///
5028/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005029static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005030BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005031 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005032 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005033 // C++0x [class.copy]p30:
5034 // Each subobject is assigned in the manner appropriate to its type:
5035 //
5036 // - if the subobject is of class type, the copy assignment operator
5037 // for the class is used (as if by explicit qualification; that is,
5038 // ignoring any possible virtual overriding functions in more derived
5039 // classes);
5040 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5041 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5042
5043 // Look for operator=.
5044 DeclarationName Name
5045 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5046 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5047 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5048
5049 // Filter out any result that isn't a copy-assignment operator.
5050 LookupResult::Filter F = OpLookup.makeFilter();
5051 while (F.hasNext()) {
5052 NamedDecl *D = F.next();
5053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5054 if (Method->isCopyAssignmentOperator())
5055 continue;
5056
5057 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005058 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005059 F.done();
5060
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005061 // Suppress the protected check (C++ [class.protected]) for each of the
5062 // assignment operators we found. This strange dance is required when
5063 // we're assigning via a base classes's copy-assignment operator. To
5064 // ensure that we're getting the right base class subobject (without
5065 // ambiguities), we need to cast "this" to that subobject type; to
5066 // ensure that we don't go through the virtual call mechanism, we need
5067 // to qualify the operator= name with the base class (see below). However,
5068 // this means that if the base class has a protected copy assignment
5069 // operator, the protected member access check will fail. So, we
5070 // rewrite "protected" access to "public" access in this case, since we
5071 // know by construction that we're calling from a derived class.
5072 if (CopyingBaseSubobject) {
5073 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5074 L != LEnd; ++L) {
5075 if (L.getAccess() == AS_protected)
5076 L.setAccess(AS_public);
5077 }
5078 }
5079
Douglas Gregor06a9f362010-05-01 20:49:11 +00005080 // Create the nested-name-specifier that will be used to qualify the
5081 // reference to operator=; this is required to suppress the virtual
5082 // call mechanism.
5083 CXXScopeSpec SS;
5084 SS.setRange(Loc);
5085 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
5086 T.getTypePtr()));
5087
5088 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005089 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005090 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005091 /*FirstQualifierInScope=*/0, OpLookup,
5092 /*TemplateArgs=*/0,
5093 /*SuppressQualifierCheck=*/true);
5094 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005095 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005096
5097 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005098
John McCall60d7b3a2010-08-24 06:29:42 +00005099 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005100 OpEqualRef.takeAs<Expr>(),
5101 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005102 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005103 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005104
5105 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005106 }
John McCallb0207482010-03-16 06:11:48 +00005107
Douglas Gregor06a9f362010-05-01 20:49:11 +00005108 // - if the subobject is of scalar type, the built-in assignment
5109 // operator is used.
5110 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5111 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005112 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005113 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005114 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005115
5116 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005117 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005118
5119 // - if the subobject is an array, each element is assigned, in the
5120 // manner appropriate to the element type;
5121
5122 // Construct a loop over the array bounds, e.g.,
5123 //
5124 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5125 //
5126 // that will copy each of the array elements.
5127 QualType SizeType = S.Context.getSizeType();
5128
5129 // Create the iteration variable.
5130 IdentifierInfo *IterationVarName = 0;
5131 {
5132 llvm::SmallString<8> Str;
5133 llvm::raw_svector_ostream OS(Str);
5134 OS << "__i" << Depth;
5135 IterationVarName = &S.Context.Idents.get(OS.str());
5136 }
5137 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
5138 IterationVarName, SizeType,
5139 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005140 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005141
5142 // Initialize the iteration variable to zero.
5143 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005144 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005145
5146 // Create a reference to the iteration variable; we'll use this several
5147 // times throughout.
5148 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005149 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005150 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5151
5152 // Create the DeclStmt that holds the iteration variable.
5153 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5154
5155 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005156 llvm::APInt Upper
5157 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005158 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005159 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005160 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5161 BO_NE, S.Context.BoolTy,
5162 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005163
5164 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005165 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005166 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5167 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005168
5169 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005170 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5171 IterationVarRef, Loc));
5172 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5173 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005174
5175 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005176 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5177 To, From, CopyingBaseSubobject,
5178 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005179 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005180 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005181
5182 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005183 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005184 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005185 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005186 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005187}
5188
Douglas Gregora376d102010-07-02 21:50:04 +00005189/// \brief Determine whether the given class has a copy assignment operator
5190/// that accepts a const-qualified argument.
5191static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5192 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5193
5194 if (!Class->hasDeclaredCopyAssignment())
5195 S.DeclareImplicitCopyAssignment(Class);
5196
5197 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5198 DeclarationName OpName
5199 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5200
5201 DeclContext::lookup_const_iterator Op, OpEnd;
5202 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5203 // C++ [class.copy]p9:
5204 // A user-declared copy assignment operator is a non-static non-template
5205 // member function of class X with exactly one parameter of type X, X&,
5206 // const X&, volatile X& or const volatile X&.
5207 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5208 if (!Method)
5209 continue;
5210
5211 if (Method->isStatic())
5212 continue;
5213 if (Method->getPrimaryTemplate())
5214 continue;
5215 const FunctionProtoType *FnType =
5216 Method->getType()->getAs<FunctionProtoType>();
5217 assert(FnType && "Overloaded operator has no prototype.");
5218 // Don't assert on this; an invalid decl might have been left in the AST.
5219 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5220 continue;
5221 bool AcceptsConst = true;
5222 QualType ArgType = FnType->getArgType(0);
5223 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5224 ArgType = Ref->getPointeeType();
5225 // Is it a non-const lvalue reference?
5226 if (!ArgType.isConstQualified())
5227 AcceptsConst = false;
5228 }
5229 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5230 continue;
5231
5232 // We have a single argument of type cv X or cv X&, i.e. we've found the
5233 // copy assignment operator. Return whether it accepts const arguments.
5234 return AcceptsConst;
5235 }
5236 assert(Class->isInvalidDecl() &&
5237 "No copy assignment operator declared in valid code.");
5238 return false;
5239}
5240
Douglas Gregor23c94db2010-07-02 17:43:08 +00005241CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005242 // Note: The following rules are largely analoguous to the copy
5243 // constructor rules. Note that virtual bases are not taken into account
5244 // for determining the argument type of the operator. Note also that
5245 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005246
5247
Douglas Gregord3c35902010-07-01 16:36:15 +00005248 // C++ [class.copy]p10:
5249 // If the class definition does not explicitly declare a copy
5250 // assignment operator, one is declared implicitly.
5251 // The implicitly-defined copy assignment operator for a class X
5252 // will have the form
5253 //
5254 // X& X::operator=(const X&)
5255 //
5256 // if
5257 bool HasConstCopyAssignment = true;
5258
5259 // -- each direct base class B of X has a copy assignment operator
5260 // whose parameter is of type const B&, const volatile B& or B,
5261 // and
5262 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5263 BaseEnd = ClassDecl->bases_end();
5264 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5265 assert(!Base->getType()->isDependentType() &&
5266 "Cannot generate implicit members for class with dependent bases.");
5267 const CXXRecordDecl *BaseClassDecl
5268 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005269 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005270 }
5271
5272 // -- for all the nonstatic data members of X that are of a class
5273 // type M (or array thereof), each such class type has a copy
5274 // assignment operator whose parameter is of type const M&,
5275 // const volatile M& or M.
5276 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5277 FieldEnd = ClassDecl->field_end();
5278 HasConstCopyAssignment && Field != FieldEnd;
5279 ++Field) {
5280 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5281 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5282 const CXXRecordDecl *FieldClassDecl
5283 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005284 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005285 }
5286 }
5287
5288 // Otherwise, the implicitly declared copy assignment operator will
5289 // have the form
5290 //
5291 // X& X::operator=(X&)
5292 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5293 QualType RetType = Context.getLValueReferenceType(ArgType);
5294 if (HasConstCopyAssignment)
5295 ArgType = ArgType.withConst();
5296 ArgType = Context.getLValueReferenceType(ArgType);
5297
Douglas Gregorb87786f2010-07-01 17:48:08 +00005298 // C++ [except.spec]p14:
5299 // An implicitly declared special member function (Clause 12) shall have an
5300 // exception-specification. [...]
5301 ImplicitExceptionSpecification ExceptSpec(Context);
5302 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5303 BaseEnd = ClassDecl->bases_end();
5304 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005305 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005306 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005307
5308 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5309 DeclareImplicitCopyAssignment(BaseClassDecl);
5310
Douglas Gregorb87786f2010-07-01 17:48:08 +00005311 if (CXXMethodDecl *CopyAssign
5312 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5313 ExceptSpec.CalledDecl(CopyAssign);
5314 }
5315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5316 FieldEnd = ClassDecl->field_end();
5317 Field != FieldEnd;
5318 ++Field) {
5319 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5320 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005321 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005322 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005323
5324 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5325 DeclareImplicitCopyAssignment(FieldClassDecl);
5326
Douglas Gregorb87786f2010-07-01 17:48:08 +00005327 if (CXXMethodDecl *CopyAssign
5328 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5329 ExceptSpec.CalledDecl(CopyAssign);
5330 }
5331 }
5332
Douglas Gregord3c35902010-07-01 16:36:15 +00005333 // An implicitly-declared copy assignment operator is an inline public
5334 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005335 FunctionProtoType::ExtProtoInfo EPI;
5336 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5337 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5338 EPI.NumExceptions = ExceptSpec.size();
5339 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005340 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00005341 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005342 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00005343 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005344 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005345 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005346 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00005347 /*isInline=*/true);
5348 CopyAssignment->setAccess(AS_public);
5349 CopyAssignment->setImplicit();
5350 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005351
5352 // Add the parameter to the operator.
5353 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5354 ClassDecl->getLocation(),
5355 /*Id=*/0,
5356 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005357 SC_None,
5358 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005359 CopyAssignment->setParams(&FromParam, 1);
5360
Douglas Gregora376d102010-07-02 21:50:04 +00005361 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005362 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5363
Douglas Gregor23c94db2010-07-02 17:43:08 +00005364 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005365 PushOnScopeChains(CopyAssignment, S, false);
5366 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005367
5368 AddOverriddenMethods(ClassDecl, CopyAssignment);
5369 return CopyAssignment;
5370}
5371
Douglas Gregor06a9f362010-05-01 20:49:11 +00005372void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5373 CXXMethodDecl *CopyAssignOperator) {
5374 assert((CopyAssignOperator->isImplicit() &&
5375 CopyAssignOperator->isOverloadedOperator() &&
5376 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005377 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005378 "DefineImplicitCopyAssignment called for wrong function");
5379
5380 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5381
5382 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5383 CopyAssignOperator->setInvalidDecl();
5384 return;
5385 }
5386
5387 CopyAssignOperator->setUsed();
5388
5389 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005390 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005391
5392 // C++0x [class.copy]p30:
5393 // The implicitly-defined or explicitly-defaulted copy assignment operator
5394 // for a non-union class X performs memberwise copy assignment of its
5395 // subobjects. The direct base classes of X are assigned first, in the
5396 // order of their declaration in the base-specifier-list, and then the
5397 // immediate non-static data members of X are assigned, in the order in
5398 // which they were declared in the class definition.
5399
5400 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005401 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005402
5403 // The parameter for the "other" object, which we are copying from.
5404 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5405 Qualifiers OtherQuals = Other->getType().getQualifiers();
5406 QualType OtherRefType = Other->getType();
5407 if (const LValueReferenceType *OtherRef
5408 = OtherRefType->getAs<LValueReferenceType>()) {
5409 OtherRefType = OtherRef->getPointeeType();
5410 OtherQuals = OtherRefType.getQualifiers();
5411 }
5412
5413 // Our location for everything implicitly-generated.
5414 SourceLocation Loc = CopyAssignOperator->getLocation();
5415
5416 // Construct a reference to the "other" object. We'll be using this
5417 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005418 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005419 assert(OtherRef && "Reference to parameter cannot fail!");
5420
5421 // Construct the "this" pointer. We'll be using this throughout the generated
5422 // ASTs.
5423 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5424 assert(This && "Reference to this cannot fail!");
5425
5426 // Assign base classes.
5427 bool Invalid = false;
5428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5429 E = ClassDecl->bases_end(); Base != E; ++Base) {
5430 // Form the assignment:
5431 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5432 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005433 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005434 Invalid = true;
5435 continue;
5436 }
5437
John McCallf871d0c2010-08-07 06:22:56 +00005438 CXXCastPath BasePath;
5439 BasePath.push_back(Base);
5440
Douglas Gregor06a9f362010-05-01 20:49:11 +00005441 // Construct the "from" expression, which is an implicit cast to the
5442 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005443 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005444 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005445 CK_UncheckedDerivedToBase,
5446 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005447
5448 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005449 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005450
5451 // Implicitly cast "this" to the appropriately-qualified base type.
5452 Expr *ToE = To.takeAs<Expr>();
5453 ImpCastExprToType(ToE,
5454 Context.getCVRQualifiedType(BaseType,
5455 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005456 CK_UncheckedDerivedToBase,
5457 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005458 To = Owned(ToE);
5459
5460 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005461 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005462 To.get(), From,
5463 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005464 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005465 Diag(CurrentLocation, diag::note_member_synthesized_at)
5466 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5467 CopyAssignOperator->setInvalidDecl();
5468 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005469 }
5470
5471 // Success! Record the copy.
5472 Statements.push_back(Copy.takeAs<Expr>());
5473 }
5474
5475 // \brief Reference to the __builtin_memcpy function.
5476 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005477 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005478 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005479
5480 // Assign non-static members.
5481 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5482 FieldEnd = ClassDecl->field_end();
5483 Field != FieldEnd; ++Field) {
5484 // Check for members of reference type; we can't copy those.
5485 if (Field->getType()->isReferenceType()) {
5486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5487 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5488 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005489 Diag(CurrentLocation, diag::note_member_synthesized_at)
5490 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005491 Invalid = true;
5492 continue;
5493 }
5494
5495 // Check for members of const-qualified, non-class type.
5496 QualType BaseType = Context.getBaseElementType(Field->getType());
5497 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5498 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5499 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5500 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005501 Diag(CurrentLocation, diag::note_member_synthesized_at)
5502 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005503 Invalid = true;
5504 continue;
5505 }
5506
5507 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005508 if (FieldType->isIncompleteArrayType()) {
5509 assert(ClassDecl->hasFlexibleArrayMember() &&
5510 "Incomplete array type is not valid");
5511 continue;
5512 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005513
5514 // Build references to the field in the object we're copying from and to.
5515 CXXScopeSpec SS; // Intentionally empty
5516 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5517 LookupMemberName);
5518 MemberLookup.addDecl(*Field);
5519 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005520 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005521 Loc, /*IsArrow=*/false,
5522 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005523 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005524 Loc, /*IsArrow=*/true,
5525 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005526 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5527 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5528
5529 // If the field should be copied with __builtin_memcpy rather than via
5530 // explicit assignments, do so. This optimization only applies for arrays
5531 // of scalars and arrays of class type with trivial copy-assignment
5532 // operators.
5533 if (FieldType->isArrayType() &&
5534 (!BaseType->isRecordType() ||
5535 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5536 ->hasTrivialCopyAssignment())) {
5537 // Compute the size of the memory buffer to be copied.
5538 QualType SizeType = Context.getSizeType();
5539 llvm::APInt Size(Context.getTypeSize(SizeType),
5540 Context.getTypeSizeInChars(BaseType).getQuantity());
5541 for (const ConstantArrayType *Array
5542 = Context.getAsConstantArrayType(FieldType);
5543 Array;
5544 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005545 llvm::APInt ArraySize
5546 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005547 Size *= ArraySize;
5548 }
5549
5550 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005551 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5552 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005553
5554 bool NeedsCollectableMemCpy =
5555 (BaseType->isRecordType() &&
5556 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5557
5558 if (NeedsCollectableMemCpy) {
5559 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005560 // Create a reference to the __builtin_objc_memmove_collectable function.
5561 LookupResult R(*this,
5562 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005563 Loc, LookupOrdinaryName);
5564 LookupName(R, TUScope, true);
5565
5566 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5567 if (!CollectableMemCpy) {
5568 // Something went horribly wrong earlier, and we will have
5569 // complained about it.
5570 Invalid = true;
5571 continue;
5572 }
5573
5574 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5575 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005576 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005577 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5578 }
5579 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005580 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005581 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005582 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5583 LookupOrdinaryName);
5584 LookupName(R, TUScope, true);
5585
5586 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5587 if (!BuiltinMemCpy) {
5588 // Something went horribly wrong earlier, and we will have complained
5589 // about it.
5590 Invalid = true;
5591 continue;
5592 }
5593
5594 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5595 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005596 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005597 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5598 }
5599
John McCallca0408f2010-08-23 06:44:23 +00005600 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005601 CallArgs.push_back(To.takeAs<Expr>());
5602 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005603 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005604 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005605 if (NeedsCollectableMemCpy)
5606 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005607 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005608 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005609 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005610 else
5611 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005612 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005613 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005614 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005615
Douglas Gregor06a9f362010-05-01 20:49:11 +00005616 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5617 Statements.push_back(Call.takeAs<Expr>());
5618 continue;
5619 }
5620
5621 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005622 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005623 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005624 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005625 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005626 Diag(CurrentLocation, diag::note_member_synthesized_at)
5627 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5628 CopyAssignOperator->setInvalidDecl();
5629 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005630 }
5631
5632 // Success! Record the copy.
5633 Statements.push_back(Copy.takeAs<Stmt>());
5634 }
5635
5636 if (!Invalid) {
5637 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005638 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005639
John McCall60d7b3a2010-08-24 06:29:42 +00005640 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005641 if (Return.isInvalid())
5642 Invalid = true;
5643 else {
5644 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005645
5646 if (Trap.hasErrorOccurred()) {
5647 Diag(CurrentLocation, diag::note_member_synthesized_at)
5648 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5649 Invalid = true;
5650 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005651 }
5652 }
5653
5654 if (Invalid) {
5655 CopyAssignOperator->setInvalidDecl();
5656 return;
5657 }
5658
John McCall60d7b3a2010-08-24 06:29:42 +00005659 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005660 /*isStmtExpr=*/false);
5661 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5662 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005663}
5664
Douglas Gregor23c94db2010-07-02 17:43:08 +00005665CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5666 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005667 // C++ [class.copy]p4:
5668 // If the class definition does not explicitly declare a copy
5669 // constructor, one is declared implicitly.
5670
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005671 // C++ [class.copy]p5:
5672 // The implicitly-declared copy constructor for a class X will
5673 // have the form
5674 //
5675 // X::X(const X&)
5676 //
5677 // if
5678 bool HasConstCopyConstructor = true;
5679
5680 // -- each direct or virtual base class B of X has a copy
5681 // constructor whose first parameter is of type const B& or
5682 // const volatile B&, and
5683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5684 BaseEnd = ClassDecl->bases_end();
5685 HasConstCopyConstructor && Base != BaseEnd;
5686 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005687 // Virtual bases are handled below.
5688 if (Base->isVirtual())
5689 continue;
5690
Douglas Gregor22584312010-07-02 23:41:54 +00005691 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005692 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005693 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5694 DeclareImplicitCopyConstructor(BaseClassDecl);
5695
Douglas Gregor598a8542010-07-01 18:27:03 +00005696 HasConstCopyConstructor
5697 = BaseClassDecl->hasConstCopyConstructor(Context);
5698 }
5699
5700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5701 BaseEnd = ClassDecl->vbases_end();
5702 HasConstCopyConstructor && Base != BaseEnd;
5703 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005704 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005705 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005706 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5707 DeclareImplicitCopyConstructor(BaseClassDecl);
5708
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005709 HasConstCopyConstructor
5710 = BaseClassDecl->hasConstCopyConstructor(Context);
5711 }
5712
5713 // -- for all the nonstatic data members of X that are of a
5714 // class type M (or array thereof), each such class type
5715 // has a copy constructor whose first parameter is of type
5716 // const M& or const volatile M&.
5717 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5718 FieldEnd = ClassDecl->field_end();
5719 HasConstCopyConstructor && Field != FieldEnd;
5720 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005721 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005722 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005723 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005724 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005725 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5726 DeclareImplicitCopyConstructor(FieldClassDecl);
5727
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005728 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005729 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005730 }
5731 }
5732
5733 // Otherwise, the implicitly declared copy constructor will have
5734 // the form
5735 //
5736 // X::X(X&)
5737 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5738 QualType ArgType = ClassType;
5739 if (HasConstCopyConstructor)
5740 ArgType = ArgType.withConst();
5741 ArgType = Context.getLValueReferenceType(ArgType);
5742
Douglas Gregor0d405db2010-07-01 20:59:04 +00005743 // C++ [except.spec]p14:
5744 // An implicitly declared special member function (Clause 12) shall have an
5745 // exception-specification. [...]
5746 ImplicitExceptionSpecification ExceptSpec(Context);
5747 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5748 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5749 BaseEnd = ClassDecl->bases_end();
5750 Base != BaseEnd;
5751 ++Base) {
5752 // Virtual bases are handled below.
5753 if (Base->isVirtual())
5754 continue;
5755
Douglas Gregor22584312010-07-02 23:41:54 +00005756 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005757 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005758 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5759 DeclareImplicitCopyConstructor(BaseClassDecl);
5760
Douglas Gregor0d405db2010-07-01 20:59:04 +00005761 if (CXXConstructorDecl *CopyConstructor
5762 = BaseClassDecl->getCopyConstructor(Context, Quals))
5763 ExceptSpec.CalledDecl(CopyConstructor);
5764 }
5765 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5766 BaseEnd = ClassDecl->vbases_end();
5767 Base != BaseEnd;
5768 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005769 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005770 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005771 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5772 DeclareImplicitCopyConstructor(BaseClassDecl);
5773
Douglas Gregor0d405db2010-07-01 20:59:04 +00005774 if (CXXConstructorDecl *CopyConstructor
5775 = BaseClassDecl->getCopyConstructor(Context, Quals))
5776 ExceptSpec.CalledDecl(CopyConstructor);
5777 }
5778 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5779 FieldEnd = ClassDecl->field_end();
5780 Field != FieldEnd;
5781 ++Field) {
5782 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5783 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005784 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005785 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005786 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5787 DeclareImplicitCopyConstructor(FieldClassDecl);
5788
Douglas Gregor0d405db2010-07-01 20:59:04 +00005789 if (CXXConstructorDecl *CopyConstructor
5790 = FieldClassDecl->getCopyConstructor(Context, Quals))
5791 ExceptSpec.CalledDecl(CopyConstructor);
5792 }
5793 }
5794
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005795 // An implicitly-declared copy constructor is an inline public
5796 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005797 FunctionProtoType::ExtProtoInfo EPI;
5798 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5799 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5800 EPI.NumExceptions = ExceptSpec.size();
5801 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005802 DeclarationName Name
5803 = Context.DeclarationNames.getCXXConstructorName(
5804 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005805 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005806 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005807 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005808 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005809 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005810 /*TInfo=*/0,
5811 /*isExplicit=*/false,
5812 /*isInline=*/true,
5813 /*isImplicitlyDeclared=*/true);
5814 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005815 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5816
Douglas Gregor22584312010-07-02 23:41:54 +00005817 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005818 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5819
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005820 // Add the parameter to the constructor.
5821 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5822 ClassDecl->getLocation(),
5823 /*IdentifierInfo=*/0,
5824 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005825 SC_None,
5826 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005827 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005828 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005829 PushOnScopeChains(CopyConstructor, S, false);
5830 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005831
5832 return CopyConstructor;
5833}
5834
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005835void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5836 CXXConstructorDecl *CopyConstructor,
5837 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005838 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005839 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005840 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005841 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005842
Anders Carlsson63010a72010-04-23 16:24:12 +00005843 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005844 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005845
Douglas Gregor39957dc2010-05-01 15:04:51 +00005846 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005847 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005848
Sean Huntcbb67482011-01-08 20:30:50 +00005849 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005850 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005851 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005852 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005853 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005854 } else {
5855 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5856 CopyConstructor->getLocation(),
5857 MultiStmtArg(*this, 0, 0),
5858 /*isStmtExpr=*/false)
5859 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005860 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005861
5862 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005863}
5864
John McCall60d7b3a2010-08-24 06:29:42 +00005865ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005866Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005867 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005868 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005869 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005870 unsigned ConstructKind,
5871 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005872 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005873
Douglas Gregor2f599792010-04-02 18:24:57 +00005874 // C++0x [class.copy]p34:
5875 // When certain criteria are met, an implementation is allowed to
5876 // omit the copy/move construction of a class object, even if the
5877 // copy/move constructor and/or destructor for the object have
5878 // side effects. [...]
5879 // - when a temporary class object that has not been bound to a
5880 // reference (12.2) would be copied/moved to a class object
5881 // with the same cv-unqualified type, the copy/move operation
5882 // can be omitted by constructing the temporary object
5883 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005884 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00005885 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005886 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005887 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005888 }
Mike Stump1eb44332009-09-09 15:08:12 +00005889
5890 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005891 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005892 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005893}
5894
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005895/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5896/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005897ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005898Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5899 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005900 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005901 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005902 unsigned ConstructKind,
5903 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005904 unsigned NumExprs = ExprArgs.size();
5905 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005906
Douglas Gregor7edfb692009-11-23 12:27:39 +00005907 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005908 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005909 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005910 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005911 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5912 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005913}
5914
Mike Stump1eb44332009-09-09 15:08:12 +00005915bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005916 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005917 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005918 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005919 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005920 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005921 move(Exprs), false, CXXConstructExpr::CK_Complete,
5922 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005923 if (TempResult.isInvalid())
5924 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005925
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005926 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005927 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005928 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005929 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005930 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005931
Anders Carlssonfe2de492009-08-25 05:18:00 +00005932 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005933}
5934
John McCall68c6c9a2010-02-02 09:10:11 +00005935void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5936 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005937 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005938 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005939 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005940 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005941 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005942 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005943 << VD->getDeclName()
5944 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005945
John McCallae792222010-09-18 05:25:11 +00005946 // TODO: this should be re-enabled for static locals by !CXAAtExit
5947 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005948 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005949 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005950}
5951
Mike Stump1eb44332009-09-09 15:08:12 +00005952/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005953/// ActOnDeclarator, when a C++ direct initializer is present.
5954/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005955void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005956 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005957 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005958 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005959 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005960
5961 // If there is no declaration, there was an error parsing it. Just ignore
5962 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005963 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005964 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005965
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005966 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5967 if (!VDecl) {
5968 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5969 RealDecl->setInvalidDecl();
5970 return;
5971 }
5972
Douglas Gregor83ddad32009-08-26 21:14:46 +00005973 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005974 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005975 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5976 //
5977 // Clients that want to distinguish between the two forms, can check for
5978 // direct initializer using VarDecl::hasCXXDirectInitializer().
5979 // A major benefit is that clients that don't particularly care about which
5980 // exactly form was it (like the CodeGen) can handle both cases without
5981 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005982
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005983 // C++ 8.5p11:
5984 // The form of initialization (using parentheses or '=') is generally
5985 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005986 // class type.
5987
Douglas Gregor4dffad62010-02-11 22:55:30 +00005988 if (!VDecl->getType()->isDependentType() &&
5989 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005990 diag::err_typecheck_decl_incomplete_type)) {
5991 VDecl->setInvalidDecl();
5992 return;
5993 }
5994
Douglas Gregor90f93822009-12-22 22:17:25 +00005995 // The variable can not have an abstract class type.
5996 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5997 diag::err_abstract_type_in_decl,
5998 AbstractVariableType))
5999 VDecl->setInvalidDecl();
6000
Sebastian Redl31310a22010-02-01 20:16:42 +00006001 const VarDecl *Def;
6002 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006003 Diag(VDecl->getLocation(), diag::err_redefinition)
6004 << VDecl->getDeclName();
6005 Diag(Def->getLocation(), diag::note_previous_definition);
6006 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006007 return;
6008 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006009
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006010 // C++ [class.static.data]p4
6011 // If a static data member is of const integral or const
6012 // enumeration type, its declaration in the class definition can
6013 // specify a constant-initializer which shall be an integral
6014 // constant expression (5.19). In that case, the member can appear
6015 // in integral constant expressions. The member shall still be
6016 // defined in a namespace scope if it is used in the program and the
6017 // namespace scope definition shall not contain an initializer.
6018 //
6019 // We already performed a redefinition check above, but for static
6020 // data members we also need to check whether there was an in-class
6021 // declaration with an initializer.
6022 const VarDecl* PrevInit = 0;
6023 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6024 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6025 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6026 return;
6027 }
6028
Douglas Gregora31040f2010-12-16 01:31:22 +00006029 bool IsDependent = false;
6030 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6031 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6032 VDecl->setInvalidDecl();
6033 return;
6034 }
6035
6036 if (Exprs.get()[I]->isTypeDependent())
6037 IsDependent = true;
6038 }
6039
Douglas Gregor4dffad62010-02-11 22:55:30 +00006040 // If either the declaration has a dependent type or if any of the
6041 // expressions is type-dependent, we represent the initialization
6042 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006043 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006044 // Let clients know that initialization was done with a direct initializer.
6045 VDecl->setCXXDirectInitializer(true);
6046
6047 // Store the initialization expressions as a ParenListExpr.
6048 unsigned NumExprs = Exprs.size();
6049 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6050 (Expr **)Exprs.release(),
6051 NumExprs, RParenLoc));
6052 return;
6053 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006054
6055 // Capture the variable that is being initialized and the style of
6056 // initialization.
6057 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6058
6059 // FIXME: Poor source location information.
6060 InitializationKind Kind
6061 = InitializationKind::CreateDirect(VDecl->getLocation(),
6062 LParenLoc, RParenLoc);
6063
6064 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006065 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006066 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006067 if (Result.isInvalid()) {
6068 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006069 return;
6070 }
John McCallb4eb64d2010-10-08 02:01:28 +00006071
6072 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006073
Douglas Gregor53c374f2010-12-07 00:41:46 +00006074 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006075 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006076 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006077
John McCall2998d6b2011-01-19 11:48:09 +00006078 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006079}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006080
Douglas Gregor39da0b82009-09-09 23:08:42 +00006081/// \brief Given a constructor and the set of arguments provided for the
6082/// constructor, convert the arguments and add any required default arguments
6083/// to form a proper call to this constructor.
6084///
6085/// \returns true if an error occurred, false otherwise.
6086bool
6087Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6088 MultiExprArg ArgsPtr,
6089 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006090 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006091 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6092 unsigned NumArgs = ArgsPtr.size();
6093 Expr **Args = (Expr **)ArgsPtr.get();
6094
6095 const FunctionProtoType *Proto
6096 = Constructor->getType()->getAs<FunctionProtoType>();
6097 assert(Proto && "Constructor without a prototype?");
6098 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006099
6100 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006101 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006102 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006103 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006104 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006105
6106 VariadicCallType CallType =
6107 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6108 llvm::SmallVector<Expr *, 8> AllArgs;
6109 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6110 Proto, 0, Args, NumArgs, AllArgs,
6111 CallType);
6112 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6113 ConvertedArgs.push_back(AllArgs[i]);
6114 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006115}
6116
Anders Carlsson20d45d22009-12-12 00:32:00 +00006117static inline bool
6118CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6119 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006120 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006121 if (isa<NamespaceDecl>(DC)) {
6122 return SemaRef.Diag(FnDecl->getLocation(),
6123 diag::err_operator_new_delete_declared_in_namespace)
6124 << FnDecl->getDeclName();
6125 }
6126
6127 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006128 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006129 return SemaRef.Diag(FnDecl->getLocation(),
6130 diag::err_operator_new_delete_declared_static)
6131 << FnDecl->getDeclName();
6132 }
6133
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006134 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006135}
6136
Anders Carlsson156c78e2009-12-13 17:53:43 +00006137static inline bool
6138CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6139 CanQualType ExpectedResultType,
6140 CanQualType ExpectedFirstParamType,
6141 unsigned DependentParamTypeDiag,
6142 unsigned InvalidParamTypeDiag) {
6143 QualType ResultType =
6144 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6145
6146 // Check that the result type is not dependent.
6147 if (ResultType->isDependentType())
6148 return SemaRef.Diag(FnDecl->getLocation(),
6149 diag::err_operator_new_delete_dependent_result_type)
6150 << FnDecl->getDeclName() << ExpectedResultType;
6151
6152 // Check that the result type is what we expect.
6153 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6154 return SemaRef.Diag(FnDecl->getLocation(),
6155 diag::err_operator_new_delete_invalid_result_type)
6156 << FnDecl->getDeclName() << ExpectedResultType;
6157
6158 // A function template must have at least 2 parameters.
6159 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6160 return SemaRef.Diag(FnDecl->getLocation(),
6161 diag::err_operator_new_delete_template_too_few_parameters)
6162 << FnDecl->getDeclName();
6163
6164 // The function decl must have at least 1 parameter.
6165 if (FnDecl->getNumParams() == 0)
6166 return SemaRef.Diag(FnDecl->getLocation(),
6167 diag::err_operator_new_delete_too_few_parameters)
6168 << FnDecl->getDeclName();
6169
6170 // Check the the first parameter type is not dependent.
6171 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6172 if (FirstParamType->isDependentType())
6173 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6174 << FnDecl->getDeclName() << ExpectedFirstParamType;
6175
6176 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006177 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006178 ExpectedFirstParamType)
6179 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6180 << FnDecl->getDeclName() << ExpectedFirstParamType;
6181
6182 return false;
6183}
6184
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006185static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006186CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006187 // C++ [basic.stc.dynamic.allocation]p1:
6188 // A program is ill-formed if an allocation function is declared in a
6189 // namespace scope other than global scope or declared static in global
6190 // scope.
6191 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6192 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006193
6194 CanQualType SizeTy =
6195 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6196
6197 // C++ [basic.stc.dynamic.allocation]p1:
6198 // The return type shall be void*. The first parameter shall have type
6199 // std::size_t.
6200 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6201 SizeTy,
6202 diag::err_operator_new_dependent_param_type,
6203 diag::err_operator_new_param_type))
6204 return true;
6205
6206 // C++ [basic.stc.dynamic.allocation]p1:
6207 // The first parameter shall not have an associated default argument.
6208 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006209 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006210 diag::err_operator_new_default_arg)
6211 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6212
6213 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006214}
6215
6216static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006217CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6218 // C++ [basic.stc.dynamic.deallocation]p1:
6219 // A program is ill-formed if deallocation functions are declared in a
6220 // namespace scope other than global scope or declared static in global
6221 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006222 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6223 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006224
6225 // C++ [basic.stc.dynamic.deallocation]p2:
6226 // Each deallocation function shall return void and its first parameter
6227 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006228 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6229 SemaRef.Context.VoidPtrTy,
6230 diag::err_operator_delete_dependent_param_type,
6231 diag::err_operator_delete_param_type))
6232 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006233
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006234 return false;
6235}
6236
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006237/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6238/// of this overloaded operator is well-formed. If so, returns false;
6239/// otherwise, emits appropriate diagnostics and returns true.
6240bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006241 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006242 "Expected an overloaded operator declaration");
6243
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006244 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6245
Mike Stump1eb44332009-09-09 15:08:12 +00006246 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006247 // The allocation and deallocation functions, operator new,
6248 // operator new[], operator delete and operator delete[], are
6249 // described completely in 3.7.3. The attributes and restrictions
6250 // found in the rest of this subclause do not apply to them unless
6251 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006252 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006253 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006254
Anders Carlssona3ccda52009-12-12 00:26:23 +00006255 if (Op == OO_New || Op == OO_Array_New)
6256 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006257
6258 // C++ [over.oper]p6:
6259 // An operator function shall either be a non-static member
6260 // function or be a non-member function and have at least one
6261 // parameter whose type is a class, a reference to a class, an
6262 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006263 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6264 if (MethodDecl->isStatic())
6265 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006266 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006267 } else {
6268 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006269 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6270 ParamEnd = FnDecl->param_end();
6271 Param != ParamEnd; ++Param) {
6272 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006273 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6274 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006275 ClassOrEnumParam = true;
6276 break;
6277 }
6278 }
6279
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006280 if (!ClassOrEnumParam)
6281 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006282 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006283 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006284 }
6285
6286 // C++ [over.oper]p8:
6287 // An operator function cannot have default arguments (8.3.6),
6288 // except where explicitly stated below.
6289 //
Mike Stump1eb44332009-09-09 15:08:12 +00006290 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006291 // (C++ [over.call]p1).
6292 if (Op != OO_Call) {
6293 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6294 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006295 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006296 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006297 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006298 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006299 }
6300 }
6301
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006302 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6303 { false, false, false }
6304#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6305 , { Unary, Binary, MemberOnly }
6306#include "clang/Basic/OperatorKinds.def"
6307 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006308
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006309 bool CanBeUnaryOperator = OperatorUses[Op][0];
6310 bool CanBeBinaryOperator = OperatorUses[Op][1];
6311 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006312
6313 // C++ [over.oper]p8:
6314 // [...] Operator functions cannot have more or fewer parameters
6315 // than the number required for the corresponding operator, as
6316 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006317 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006318 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006319 if (Op != OO_Call &&
6320 ((NumParams == 1 && !CanBeUnaryOperator) ||
6321 (NumParams == 2 && !CanBeBinaryOperator) ||
6322 (NumParams < 1) || (NumParams > 2))) {
6323 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006324 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006325 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006326 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006327 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006328 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006329 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006330 assert(CanBeBinaryOperator &&
6331 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006332 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006333 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006334
Chris Lattner416e46f2008-11-21 07:57:12 +00006335 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006336 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006337 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006338
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006339 // Overloaded operators other than operator() cannot be variadic.
6340 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006341 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006342 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006343 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006344 }
6345
6346 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006347 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6348 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006349 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006350 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006351 }
6352
6353 // C++ [over.inc]p1:
6354 // The user-defined function called operator++ implements the
6355 // prefix and postfix ++ operator. If this function is a member
6356 // function with no parameters, or a non-member function with one
6357 // parameter of class or enumeration type, it defines the prefix
6358 // increment operator ++ for objects of that type. If the function
6359 // is a member function with one parameter (which shall be of type
6360 // int) or a non-member function with two parameters (the second
6361 // of which shall be of type int), it defines the postfix
6362 // increment operator ++ for objects of that type.
6363 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6364 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6365 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006366 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006367 ParamIsInt = BT->getKind() == BuiltinType::Int;
6368
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006369 if (!ParamIsInt)
6370 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006371 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006372 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006373 }
6374
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006375 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006376}
Chris Lattner5a003a42008-12-17 07:09:26 +00006377
Sean Hunta6c058d2010-01-13 09:01:02 +00006378/// CheckLiteralOperatorDeclaration - Check whether the declaration
6379/// of this literal operator function is well-formed. If so, returns
6380/// false; otherwise, emits appropriate diagnostics and returns true.
6381bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6382 DeclContext *DC = FnDecl->getDeclContext();
6383 Decl::Kind Kind = DC->getDeclKind();
6384 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6385 Kind != Decl::LinkageSpec) {
6386 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6387 << FnDecl->getDeclName();
6388 return true;
6389 }
6390
6391 bool Valid = false;
6392
Sean Hunt216c2782010-04-07 23:11:06 +00006393 // template <char...> type operator "" name() is the only valid template
6394 // signature, and the only valid signature with no parameters.
6395 if (FnDecl->param_size() == 0) {
6396 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6397 // Must have only one template parameter
6398 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6399 if (Params->size() == 1) {
6400 NonTypeTemplateParmDecl *PmDecl =
6401 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006402
Sean Hunt216c2782010-04-07 23:11:06 +00006403 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006404 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6405 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6406 Valid = true;
6407 }
6408 }
6409 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006410 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006411 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6412
Sean Hunta6c058d2010-01-13 09:01:02 +00006413 QualType T = (*Param)->getType();
6414
Sean Hunt30019c02010-04-07 22:57:35 +00006415 // unsigned long long int, long double, and any character type are allowed
6416 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006417 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6418 Context.hasSameType(T, Context.LongDoubleTy) ||
6419 Context.hasSameType(T, Context.CharTy) ||
6420 Context.hasSameType(T, Context.WCharTy) ||
6421 Context.hasSameType(T, Context.Char16Ty) ||
6422 Context.hasSameType(T, Context.Char32Ty)) {
6423 if (++Param == FnDecl->param_end())
6424 Valid = true;
6425 goto FinishedParams;
6426 }
6427
Sean Hunt30019c02010-04-07 22:57:35 +00006428 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006429 const PointerType *PT = T->getAs<PointerType>();
6430 if (!PT)
6431 goto FinishedParams;
6432 T = PT->getPointeeType();
6433 if (!T.isConstQualified())
6434 goto FinishedParams;
6435 T = T.getUnqualifiedType();
6436
6437 // Move on to the second parameter;
6438 ++Param;
6439
6440 // If there is no second parameter, the first must be a const char *
6441 if (Param == FnDecl->param_end()) {
6442 if (Context.hasSameType(T, Context.CharTy))
6443 Valid = true;
6444 goto FinishedParams;
6445 }
6446
6447 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6448 // are allowed as the first parameter to a two-parameter function
6449 if (!(Context.hasSameType(T, Context.CharTy) ||
6450 Context.hasSameType(T, Context.WCharTy) ||
6451 Context.hasSameType(T, Context.Char16Ty) ||
6452 Context.hasSameType(T, Context.Char32Ty)))
6453 goto FinishedParams;
6454
6455 // The second and final parameter must be an std::size_t
6456 T = (*Param)->getType().getUnqualifiedType();
6457 if (Context.hasSameType(T, Context.getSizeType()) &&
6458 ++Param == FnDecl->param_end())
6459 Valid = true;
6460 }
6461
6462 // FIXME: This diagnostic is absolutely terrible.
6463FinishedParams:
6464 if (!Valid) {
6465 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6466 << FnDecl->getDeclName();
6467 return true;
6468 }
6469
6470 return false;
6471}
6472
Douglas Gregor074149e2009-01-05 19:45:36 +00006473/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6474/// linkage specification, including the language and (if present)
6475/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6476/// the location of the language string literal, which is provided
6477/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6478/// the '{' brace. Otherwise, this linkage specification does not
6479/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006480Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6481 SourceLocation LangLoc,
6482 llvm::StringRef Lang,
6483 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006484 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006485 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006486 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006487 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006488 Language = LinkageSpecDecl::lang_cxx;
6489 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006490 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006491 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006492 }
Mike Stump1eb44332009-09-09 15:08:12 +00006493
Chris Lattnercc98eac2008-12-17 07:13:27 +00006494 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006495
Douglas Gregor074149e2009-01-05 19:45:36 +00006496 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006497 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006498 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006499 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006500 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006501 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006502}
6503
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006504/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006505/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6506/// valid, it's the position of the closing '}' brace in a linkage
6507/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006508Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6509 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006510 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006511 if (LinkageSpec)
6512 PopDeclContext();
6513 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006514}
6515
Douglas Gregord308e622009-05-18 20:51:54 +00006516/// \brief Perform semantic analysis for the variable declaration that
6517/// occurs within a C++ catch clause, returning the newly-created
6518/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006519VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006520 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006521 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006522 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006523 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006524 QualType ExDeclType = TInfo->getType();
6525
Sebastian Redl4b07b292008-12-22 19:15:10 +00006526 // Arrays and functions decay.
6527 if (ExDeclType->isArrayType())
6528 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6529 else if (ExDeclType->isFunctionType())
6530 ExDeclType = Context.getPointerType(ExDeclType);
6531
6532 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6533 // The exception-declaration shall not denote a pointer or reference to an
6534 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006535 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006536 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006537 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006538 Invalid = true;
6539 }
Douglas Gregord308e622009-05-18 20:51:54 +00006540
Douglas Gregora2762912010-03-08 01:47:36 +00006541 // GCC allows catching pointers and references to incomplete types
6542 // as an extension; so do we, but we warn by default.
6543
Sebastian Redl4b07b292008-12-22 19:15:10 +00006544 QualType BaseType = ExDeclType;
6545 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006546 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006547 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006548 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006549 BaseType = Ptr->getPointeeType();
6550 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006551 DK = diag::ext_catch_incomplete_ptr;
6552 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006553 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006554 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006555 BaseType = Ref->getPointeeType();
6556 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006557 DK = diag::ext_catch_incomplete_ref;
6558 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006559 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006560 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006561 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6562 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006563 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006564
Mike Stump1eb44332009-09-09 15:08:12 +00006565 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006566 RequireNonAbstractType(Loc, ExDeclType,
6567 diag::err_abstract_type_in_decl,
6568 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006569 Invalid = true;
6570
John McCall5a180392010-07-24 00:37:23 +00006571 // Only the non-fragile NeXT runtime currently supports C++ catches
6572 // of ObjC types, and no runtime supports catching ObjC types by value.
6573 if (!Invalid && getLangOptions().ObjC1) {
6574 QualType T = ExDeclType;
6575 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6576 T = RT->getPointeeType();
6577
6578 if (T->isObjCObjectType()) {
6579 Diag(Loc, diag::err_objc_object_catch);
6580 Invalid = true;
6581 } else if (T->isObjCObjectPointerType()) {
6582 if (!getLangOptions().NeXTRuntime) {
6583 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6584 Invalid = true;
6585 } else if (!getLangOptions().ObjCNonFragileABI) {
6586 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6587 Invalid = true;
6588 }
6589 }
6590 }
6591
Mike Stump1eb44332009-09-09 15:08:12 +00006592 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006593 Name, ExDeclType, TInfo, SC_None,
6594 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006595 ExDecl->setExceptionVariable(true);
6596
Douglas Gregor6d182892010-03-05 23:38:39 +00006597 if (!Invalid) {
6598 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6599 // C++ [except.handle]p16:
6600 // The object declared in an exception-declaration or, if the
6601 // exception-declaration does not specify a name, a temporary (12.2) is
6602 // copy-initialized (8.5) from the exception object. [...]
6603 // The object is destroyed when the handler exits, after the destruction
6604 // of any automatic objects initialized within the handler.
6605 //
6606 // We just pretend to initialize the object with itself, then make sure
6607 // it can be destroyed later.
6608 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6609 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006610 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006611 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6612 SourceLocation());
6613 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006614 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006615 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006616 if (Result.isInvalid())
6617 Invalid = true;
6618 else
6619 FinalizeVarWithDestructor(ExDecl, RecordTy);
6620 }
6621 }
6622
Douglas Gregord308e622009-05-18 20:51:54 +00006623 if (Invalid)
6624 ExDecl->setInvalidDecl();
6625
6626 return ExDecl;
6627}
6628
6629/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6630/// handler.
John McCalld226f652010-08-21 09:40:31 +00006631Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006633 bool Invalid = D.isInvalidType();
6634
6635 // Check for unexpanded parameter packs.
6636 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6637 UPPC_ExceptionType)) {
6638 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6639 D.getIdentifierLoc());
6640 Invalid = true;
6641 }
6642
Sebastian Redl4b07b292008-12-22 19:15:10 +00006643 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006644 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006645 LookupOrdinaryName,
6646 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006647 // The scope should be freshly made just for us. There is just no way
6648 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006649 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006650 if (PrevDecl->isTemplateParameter()) {
6651 // Maybe we will complain about the shadowed template parameter.
6652 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006653 }
6654 }
6655
Chris Lattnereaaebc72009-04-25 08:06:05 +00006656 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006657 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6658 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006659 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006660 }
6661
Douglas Gregor83cb9422010-09-09 17:09:21 +00006662 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006663 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006664 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006665
Chris Lattnereaaebc72009-04-25 08:06:05 +00006666 if (Invalid)
6667 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006668
Sebastian Redl4b07b292008-12-22 19:15:10 +00006669 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006670 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006671 PushOnScopeChains(ExDecl, S);
6672 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006673 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006674
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006675 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006676 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006677}
Anders Carlssonfb311762009-03-14 00:25:26 +00006678
John McCalld226f652010-08-21 09:40:31 +00006679Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006680 Expr *AssertExpr,
6681 Expr *AssertMessageExpr_) {
6682 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006683
Anders Carlssonc3082412009-03-14 00:33:21 +00006684 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6685 llvm::APSInt Value(32);
6686 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6687 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6688 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006689 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006690 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006691
Anders Carlssonc3082412009-03-14 00:33:21 +00006692 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006693 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006694 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006695 }
6696 }
Mike Stump1eb44332009-09-09 15:08:12 +00006697
Douglas Gregor399ad972010-12-15 23:55:21 +00006698 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6699 return 0;
6700
Mike Stump1eb44332009-09-09 15:08:12 +00006701 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006702 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006703
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006704 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006705 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006706}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006707
Douglas Gregor1d869352010-04-07 16:53:43 +00006708/// \brief Perform semantic analysis of the given friend type declaration.
6709///
6710/// \returns A friend declaration that.
6711FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6712 TypeSourceInfo *TSInfo) {
6713 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6714
6715 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006716 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006717
Douglas Gregor06245bf2010-04-07 17:57:12 +00006718 if (!getLangOptions().CPlusPlus0x) {
6719 // C++03 [class.friend]p2:
6720 // An elaborated-type-specifier shall be used in a friend declaration
6721 // for a class.*
6722 //
6723 // * The class-key of the elaborated-type-specifier is required.
6724 if (!ActiveTemplateInstantiations.empty()) {
6725 // Do not complain about the form of friend template types during
6726 // template instantiation; we will already have complained when the
6727 // template was declared.
6728 } else if (!T->isElaboratedTypeSpecifier()) {
6729 // If we evaluated the type to a record type, suggest putting
6730 // a tag in front.
6731 if (const RecordType *RT = T->getAs<RecordType>()) {
6732 RecordDecl *RD = RT->getDecl();
6733
6734 std::string InsertionText = std::string(" ") + RD->getKindName();
6735
6736 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6737 << (unsigned) RD->getTagKind()
6738 << T
6739 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6740 InsertionText);
6741 } else {
6742 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6743 << T
6744 << SourceRange(FriendLoc, TypeRange.getEnd());
6745 }
6746 } else if (T->getAs<EnumType>()) {
6747 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006748 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006749 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006750 }
6751 }
6752
Douglas Gregor06245bf2010-04-07 17:57:12 +00006753 // C++0x [class.friend]p3:
6754 // If the type specifier in a friend declaration designates a (possibly
6755 // cv-qualified) class type, that class is declared as a friend; otherwise,
6756 // the friend declaration is ignored.
6757
6758 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6759 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006760
6761 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6762}
6763
John McCall9a34edb2010-10-19 01:40:49 +00006764/// Handle a friend tag declaration where the scope specifier was
6765/// templated.
6766Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6767 unsigned TagSpec, SourceLocation TagLoc,
6768 CXXScopeSpec &SS,
6769 IdentifierInfo *Name, SourceLocation NameLoc,
6770 AttributeList *Attr,
6771 MultiTemplateParamsArg TempParamLists) {
6772 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6773
6774 bool isExplicitSpecialization = false;
6775 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6776 bool Invalid = false;
6777
6778 if (TemplateParameterList *TemplateParams
6779 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6780 TempParamLists.get(),
6781 TempParamLists.size(),
6782 /*friend*/ true,
6783 isExplicitSpecialization,
6784 Invalid)) {
6785 --NumMatchedTemplateParamLists;
6786
6787 if (TemplateParams->size() > 0) {
6788 // This is a declaration of a class template.
6789 if (Invalid)
6790 return 0;
6791
6792 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6793 SS, Name, NameLoc, Attr,
6794 TemplateParams, AS_public).take();
6795 } else {
6796 // The "template<>" header is extraneous.
6797 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6798 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6799 isExplicitSpecialization = true;
6800 }
6801 }
6802
6803 if (Invalid) return 0;
6804
6805 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6806
6807 bool isAllExplicitSpecializations = true;
6808 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6809 if (TempParamLists.get()[I]->size()) {
6810 isAllExplicitSpecializations = false;
6811 break;
6812 }
6813 }
6814
6815 // FIXME: don't ignore attributes.
6816
6817 // If it's explicit specializations all the way down, just forget
6818 // about the template header and build an appropriate non-templated
6819 // friend. TODO: for source fidelity, remember the headers.
6820 if (isAllExplicitSpecializations) {
6821 ElaboratedTypeKeyword Keyword
6822 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6823 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6824 TagLoc, SS.getRange(), NameLoc);
6825 if (T.isNull())
6826 return 0;
6827
6828 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6829 if (isa<DependentNameType>(T)) {
6830 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6831 TL.setKeywordLoc(TagLoc);
6832 TL.setQualifierRange(SS.getRange());
6833 TL.setNameLoc(NameLoc);
6834 } else {
6835 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6836 TL.setKeywordLoc(TagLoc);
6837 TL.setQualifierRange(SS.getRange());
6838 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6839 }
6840
6841 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6842 TSI, FriendLoc);
6843 Friend->setAccess(AS_public);
6844 CurContext->addDecl(Friend);
6845 return Friend;
6846 }
6847
6848 // Handle the case of a templated-scope friend class. e.g.
6849 // template <class T> class A<T>::B;
6850 // FIXME: we don't support these right now.
6851 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6852 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6853 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6854 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6855 TL.setKeywordLoc(TagLoc);
6856 TL.setQualifierRange(SS.getRange());
6857 TL.setNameLoc(NameLoc);
6858
6859 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6860 TSI, FriendLoc);
6861 Friend->setAccess(AS_public);
6862 Friend->setUnsupportedFriend(true);
6863 CurContext->addDecl(Friend);
6864 return Friend;
6865}
6866
6867
John McCalldd4a3b02009-09-16 22:47:08 +00006868/// Handle a friend type declaration. This works in tandem with
6869/// ActOnTag.
6870///
6871/// Notes on friend class templates:
6872///
6873/// We generally treat friend class declarations as if they were
6874/// declaring a class. So, for example, the elaborated type specifier
6875/// in a friend declaration is required to obey the restrictions of a
6876/// class-head (i.e. no typedefs in the scope chain), template
6877/// parameters are required to match up with simple template-ids, &c.
6878/// However, unlike when declaring a template specialization, it's
6879/// okay to refer to a template specialization without an empty
6880/// template parameter declaration, e.g.
6881/// friend class A<T>::B<unsigned>;
6882/// We permit this as a special case; if there are any template
6883/// parameters present at all, require proper matching, i.e.
6884/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006885Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006886 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006887 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006888
6889 assert(DS.isFriendSpecified());
6890 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6891
John McCalldd4a3b02009-09-16 22:47:08 +00006892 // Try to convert the decl specifier to a type. This works for
6893 // friend templates because ActOnTag never produces a ClassTemplateDecl
6894 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006895 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006896 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6897 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006898 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006899 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006900
Douglas Gregor6ccab972010-12-16 01:14:37 +00006901 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6902 return 0;
6903
John McCalldd4a3b02009-09-16 22:47:08 +00006904 // This is definitely an error in C++98. It's probably meant to
6905 // be forbidden in C++0x, too, but the specification is just
6906 // poorly written.
6907 //
6908 // The problem is with declarations like the following:
6909 // template <T> friend A<T>::foo;
6910 // where deciding whether a class C is a friend or not now hinges
6911 // on whether there exists an instantiation of A that causes
6912 // 'foo' to equal C. There are restrictions on class-heads
6913 // (which we declare (by fiat) elaborated friend declarations to
6914 // be) that makes this tractable.
6915 //
6916 // FIXME: handle "template <> friend class A<T>;", which
6917 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006918 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006919 Diag(Loc, diag::err_tagless_friend_type_template)
6920 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006921 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006922 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006923
John McCall02cace72009-08-28 07:59:38 +00006924 // C++98 [class.friend]p1: A friend of a class is a function
6925 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006926 // This is fixed in DR77, which just barely didn't make the C++03
6927 // deadline. It's also a very silly restriction that seriously
6928 // affects inner classes and which nobody else seems to implement;
6929 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006930 //
6931 // But note that we could warn about it: it's always useless to
6932 // friend one of your own members (it's not, however, worthless to
6933 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006934
John McCalldd4a3b02009-09-16 22:47:08 +00006935 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006936 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006937 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006938 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006939 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006940 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006941 DS.getFriendSpecLoc());
6942 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006943 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6944
6945 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006946 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006947
John McCalldd4a3b02009-09-16 22:47:08 +00006948 D->setAccess(AS_public);
6949 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006950
John McCalld226f652010-08-21 09:40:31 +00006951 return D;
John McCall02cace72009-08-28 07:59:38 +00006952}
6953
John McCall337ec3d2010-10-12 23:13:28 +00006954Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6955 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006956 const DeclSpec &DS = D.getDeclSpec();
6957
6958 assert(DS.isFriendSpecified());
6959 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6960
6961 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006962 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6963 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006964
6965 // C++ [class.friend]p1
6966 // A friend of a class is a function or class....
6967 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006968 // It *doesn't* see through dependent types, which is correct
6969 // according to [temp.arg.type]p3:
6970 // If a declaration acquires a function type through a
6971 // type dependent on a template-parameter and this causes
6972 // a declaration that does not use the syntactic form of a
6973 // function declarator to have a function type, the program
6974 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006975 if (!T->isFunctionType()) {
6976 Diag(Loc, diag::err_unexpected_friend);
6977
6978 // It might be worthwhile to try to recover by creating an
6979 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006980 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006981 }
6982
6983 // C++ [namespace.memdef]p3
6984 // - If a friend declaration in a non-local class first declares a
6985 // class or function, the friend class or function is a member
6986 // of the innermost enclosing namespace.
6987 // - The name of the friend is not found by simple name lookup
6988 // until a matching declaration is provided in that namespace
6989 // scope (either before or after the class declaration granting
6990 // friendship).
6991 // - If a friend function is called, its name may be found by the
6992 // name lookup that considers functions from namespaces and
6993 // classes associated with the types of the function arguments.
6994 // - When looking for a prior declaration of a class or a function
6995 // declared as a friend, scopes outside the innermost enclosing
6996 // namespace scope are not considered.
6997
John McCall337ec3d2010-10-12 23:13:28 +00006998 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7000 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007001 assert(Name);
7002
Douglas Gregor6ccab972010-12-16 01:14:37 +00007003 // Check for unexpanded parameter packs.
7004 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7005 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7006 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7007 return 0;
7008
John McCall67d1a672009-08-06 02:15:43 +00007009 // The context we found the declaration in, or in which we should
7010 // create the declaration.
7011 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007012 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007013 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007014 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007015
John McCall337ec3d2010-10-12 23:13:28 +00007016 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007017
John McCall337ec3d2010-10-12 23:13:28 +00007018 // There are four cases here.
7019 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007020 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007021 // there as appropriate.
7022 // Recover from invalid scope qualifiers as if they just weren't there.
7023 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007024 // C++0x [namespace.memdef]p3:
7025 // If the name in a friend declaration is neither qualified nor
7026 // a template-id and the declaration is a function or an
7027 // elaborated-type-specifier, the lookup to determine whether
7028 // the entity has been previously declared shall not consider
7029 // any scopes outside the innermost enclosing namespace.
7030 // C++0x [class.friend]p11:
7031 // If a friend declaration appears in a local class and the name
7032 // specified is an unqualified name, a prior declaration is
7033 // looked up without considering scopes that are outside the
7034 // innermost enclosing non-class scope. For a friend function
7035 // declaration, if there is no prior declaration, the program is
7036 // ill-formed.
7037 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007038 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007039
John McCall29ae6e52010-10-13 05:45:15 +00007040 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007041 DC = CurContext;
7042 while (true) {
7043 // Skip class contexts. If someone can cite chapter and verse
7044 // for this behavior, that would be nice --- it's what GCC and
7045 // EDG do, and it seems like a reasonable intent, but the spec
7046 // really only says that checks for unqualified existing
7047 // declarations should stop at the nearest enclosing namespace,
7048 // not that they should only consider the nearest enclosing
7049 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007050 while (DC->isRecord())
7051 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007052
John McCall68263142009-11-18 22:49:29 +00007053 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007054
7055 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007056 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007057 break;
John McCall29ae6e52010-10-13 05:45:15 +00007058
John McCall8a407372010-10-14 22:22:28 +00007059 if (isTemplateId) {
7060 if (isa<TranslationUnitDecl>(DC)) break;
7061 } else {
7062 if (DC->isFileContext()) break;
7063 }
John McCall67d1a672009-08-06 02:15:43 +00007064 DC = DC->getParent();
7065 }
7066
7067 // C++ [class.friend]p1: A friend of a class is a function or
7068 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007069 // C++0x changes this for both friend types and functions.
7070 // Most C++ 98 compilers do seem to give an error here, so
7071 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007072 if (!Previous.empty() && DC->Equals(CurContext)
7073 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007074 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007075
John McCall380aaa42010-10-13 06:22:15 +00007076 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007077
John McCall337ec3d2010-10-12 23:13:28 +00007078 // - There's a non-dependent scope specifier, in which case we
7079 // compute it and do a previous lookup there for a function
7080 // or function template.
7081 } else if (!SS.getScopeRep()->isDependent()) {
7082 DC = computeDeclContext(SS);
7083 if (!DC) return 0;
7084
7085 if (RequireCompleteDeclContext(SS, DC)) return 0;
7086
7087 LookupQualifiedName(Previous, DC);
7088
7089 // Ignore things found implicitly in the wrong scope.
7090 // TODO: better diagnostics for this case. Suggesting the right
7091 // qualified scope would be nice...
7092 LookupResult::Filter F = Previous.makeFilter();
7093 while (F.hasNext()) {
7094 NamedDecl *D = F.next();
7095 if (!DC->InEnclosingNamespaceSetOf(
7096 D->getDeclContext()->getRedeclContext()))
7097 F.erase();
7098 }
7099 F.done();
7100
7101 if (Previous.empty()) {
7102 D.setInvalidType();
7103 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7104 return 0;
7105 }
7106
7107 // C++ [class.friend]p1: A friend of a class is a function or
7108 // class that is not a member of the class . . .
7109 if (DC->Equals(CurContext))
7110 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7111
7112 // - There's a scope specifier that does not match any template
7113 // parameter lists, in which case we use some arbitrary context,
7114 // create a method or method template, and wait for instantiation.
7115 // - There's a scope specifier that does match some template
7116 // parameter lists, which we don't handle right now.
7117 } else {
7118 DC = CurContext;
7119 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007120 }
7121
John McCall29ae6e52010-10-13 05:45:15 +00007122 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007123 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007124 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7125 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7126 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007127 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007128 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7129 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007130 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007131 }
John McCall67d1a672009-08-06 02:15:43 +00007132 }
7133
Douglas Gregor182ddf02009-09-28 00:08:27 +00007134 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007135 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007136 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007137 IsDefinition,
7138 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007139 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007140
Douglas Gregor182ddf02009-09-28 00:08:27 +00007141 assert(ND->getDeclContext() == DC);
7142 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007143
John McCallab88d972009-08-31 22:39:49 +00007144 // Add the function declaration to the appropriate lookup tables,
7145 // adjusting the redeclarations list as necessary. We don't
7146 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007147 //
John McCallab88d972009-08-31 22:39:49 +00007148 // Also update the scope-based lookup if the target context's
7149 // lookup context is in lexical scope.
7150 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007151 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007152 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007153 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007154 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007155 }
John McCall02cace72009-08-28 07:59:38 +00007156
7157 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007158 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007159 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007160 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007161 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007162
John McCall337ec3d2010-10-12 23:13:28 +00007163 if (ND->isInvalidDecl())
7164 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007165 else {
7166 FunctionDecl *FD;
7167 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7168 FD = FTD->getTemplatedDecl();
7169 else
7170 FD = cast<FunctionDecl>(ND);
7171
7172 // Mark templated-scope function declarations as unsupported.
7173 if (FD->getNumTemplateParameterLists())
7174 FrD->setUnsupportedFriend(true);
7175 }
John McCall337ec3d2010-10-12 23:13:28 +00007176
John McCalld226f652010-08-21 09:40:31 +00007177 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007178}
7179
John McCalld226f652010-08-21 09:40:31 +00007180void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7181 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007182
Sebastian Redl50de12f2009-03-24 22:27:57 +00007183 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7184 if (!Fn) {
7185 Diag(DelLoc, diag::err_deleted_non_function);
7186 return;
7187 }
7188 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7189 Diag(DelLoc, diag::err_deleted_decl_not_first);
7190 Diag(Prev->getLocation(), diag::note_previous_declaration);
7191 // If the declaration wasn't the first, we delete the function anyway for
7192 // recovery.
7193 }
7194 Fn->setDeleted();
7195}
Sebastian Redl13e88542009-04-27 21:33:24 +00007196
7197static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007198 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007199 Stmt *SubStmt = *CI;
7200 if (!SubStmt)
7201 continue;
7202 if (isa<ReturnStmt>(SubStmt))
7203 Self.Diag(SubStmt->getSourceRange().getBegin(),
7204 diag::err_return_in_constructor_handler);
7205 if (!isa<Expr>(SubStmt))
7206 SearchForReturnInStmt(Self, SubStmt);
7207 }
7208}
7209
7210void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7211 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7212 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7213 SearchForReturnInStmt(*this, Handler);
7214 }
7215}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007216
Mike Stump1eb44332009-09-09 15:08:12 +00007217bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007218 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007219 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7220 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007221
Chandler Carruth73857792010-02-15 11:53:20 +00007222 if (Context.hasSameType(NewTy, OldTy) ||
7223 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007224 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007225
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007226 // Check if the return types are covariant
7227 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007228
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007229 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007230 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7231 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007232 NewClassTy = NewPT->getPointeeType();
7233 OldClassTy = OldPT->getPointeeType();
7234 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007235 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7236 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7237 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7238 NewClassTy = NewRT->getPointeeType();
7239 OldClassTy = OldRT->getPointeeType();
7240 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007241 }
7242 }
Mike Stump1eb44332009-09-09 15:08:12 +00007243
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007244 // The return types aren't either both pointers or references to a class type.
7245 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007246 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007247 diag::err_different_return_type_for_overriding_virtual_function)
7248 << New->getDeclName() << NewTy << OldTy;
7249 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007250
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007251 return true;
7252 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007253
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007254 // C++ [class.virtual]p6:
7255 // If the return type of D::f differs from the return type of B::f, the
7256 // class type in the return type of D::f shall be complete at the point of
7257 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007258 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7259 if (!RT->isBeingDefined() &&
7260 RequireCompleteType(New->getLocation(), NewClassTy,
7261 PDiag(diag::err_covariant_return_incomplete)
7262 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007263 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007264 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007265
Douglas Gregora4923eb2009-11-16 21:35:15 +00007266 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007267 // Check if the new class derives from the old class.
7268 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7269 Diag(New->getLocation(),
7270 diag::err_covariant_return_not_derived)
7271 << New->getDeclName() << NewTy << OldTy;
7272 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7273 return true;
7274 }
Mike Stump1eb44332009-09-09 15:08:12 +00007275
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007276 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007277 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007278 diag::err_covariant_return_inaccessible_base,
7279 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7280 // FIXME: Should this point to the return type?
7281 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007282 // FIXME: this note won't trigger for delayed access control
7283 // diagnostics, and it's impossible to get an undelayed error
7284 // here from access control during the original parse because
7285 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007286 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7287 return true;
7288 }
7289 }
Mike Stump1eb44332009-09-09 15:08:12 +00007290
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007291 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007292 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007293 Diag(New->getLocation(),
7294 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007295 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007296 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7297 return true;
7298 };
Mike Stump1eb44332009-09-09 15:08:12 +00007299
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007300
7301 // The new class type must have the same or less qualifiers as the old type.
7302 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7303 Diag(New->getLocation(),
7304 diag::err_covariant_return_type_class_type_more_qualified)
7305 << New->getDeclName() << NewTy << OldTy;
7306 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7307 return true;
7308 };
Mike Stump1eb44332009-09-09 15:08:12 +00007309
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007310 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007311}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007312
Douglas Gregor4ba31362009-12-01 17:24:26 +00007313/// \brief Mark the given method pure.
7314///
7315/// \param Method the method to be marked pure.
7316///
7317/// \param InitRange the source range that covers the "0" initializer.
7318bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7319 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7320 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007321 return false;
7322 }
7323
7324 if (!Method->isInvalidDecl())
7325 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7326 << Method->getDeclName() << InitRange;
7327 return true;
7328}
7329
John McCall731ad842009-12-19 09:28:58 +00007330/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7331/// an initializer for the out-of-line declaration 'Dcl'. The scope
7332/// is a fresh scope pushed for just this purpose.
7333///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007334/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7335/// static data member of class X, names should be looked up in the scope of
7336/// class X.
John McCalld226f652010-08-21 09:40:31 +00007337void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007338 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007339 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007340
John McCall731ad842009-12-19 09:28:58 +00007341 // We should only get called for declarations with scope specifiers, like:
7342 // int foo::bar;
7343 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007344 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007345}
7346
7347/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007348/// initializer for the out-of-line declaration 'D'.
7349void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007350 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007351 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007352
John McCall731ad842009-12-19 09:28:58 +00007353 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007354 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007355}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007356
7357/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7358/// C++ if/switch/while/for statement.
7359/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007360DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007361 // C++ 6.4p2:
7362 // The declarator shall not specify a function or an array.
7363 // The type-specifier-seq shall not contain typedef and shall not declare a
7364 // new class or enumeration.
7365 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7366 "Parser allowed 'typedef' as storage class of condition decl.");
7367
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007368 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007369 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7370 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007371
7372 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7373 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7374 // would be created and CXXConditionDeclExpr wants a VarDecl.
7375 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7376 << D.getSourceRange();
7377 return DeclResult();
7378 } else if (OwnedTag && OwnedTag->isDefinition()) {
7379 // The type-specifier-seq shall not declare a new class or enumeration.
7380 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7381 }
7382
John McCalld226f652010-08-21 09:40:31 +00007383 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007384 if (!Dcl)
7385 return DeclResult();
7386
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007387 return Dcl;
7388}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007389
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007390void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7391 bool DefinitionRequired) {
7392 // Ignore any vtable uses in unevaluated operands or for classes that do
7393 // not have a vtable.
7394 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7395 CurContext->isDependentContext() ||
7396 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007397 return;
7398
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007399 // Try to insert this class into the map.
7400 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7401 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7402 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7403 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007404 // If we already had an entry, check to see if we are promoting this vtable
7405 // to required a definition. If so, we need to reappend to the VTableUses
7406 // list, since we may have already processed the first entry.
7407 if (DefinitionRequired && !Pos.first->second) {
7408 Pos.first->second = true;
7409 } else {
7410 // Otherwise, we can early exit.
7411 return;
7412 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007413 }
7414
7415 // Local classes need to have their virtual members marked
7416 // immediately. For all other classes, we mark their virtual members
7417 // at the end of the translation unit.
7418 if (Class->isLocalClass())
7419 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007420 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007421 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007422}
7423
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007424bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007425 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007426 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007427
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007428 // Note: The VTableUses vector could grow as a result of marking
7429 // the members of a class as "used", so we check the size each
7430 // time through the loop and prefer indices (with are stable) to
7431 // iterators (which are not).
7432 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007433 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007434 if (!Class)
7435 continue;
7436
7437 SourceLocation Loc = VTableUses[I].second;
7438
7439 // If this class has a key function, but that key function is
7440 // defined in another translation unit, we don't need to emit the
7441 // vtable even though we're using it.
7442 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007443 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007444 switch (KeyFunction->getTemplateSpecializationKind()) {
7445 case TSK_Undeclared:
7446 case TSK_ExplicitSpecialization:
7447 case TSK_ExplicitInstantiationDeclaration:
7448 // The key function is in another translation unit.
7449 continue;
7450
7451 case TSK_ExplicitInstantiationDefinition:
7452 case TSK_ImplicitInstantiation:
7453 // We will be instantiating the key function.
7454 break;
7455 }
7456 } else if (!KeyFunction) {
7457 // If we have a class with no key function that is the subject
7458 // of an explicit instantiation declaration, suppress the
7459 // vtable; it will live with the explicit instantiation
7460 // definition.
7461 bool IsExplicitInstantiationDeclaration
7462 = Class->getTemplateSpecializationKind()
7463 == TSK_ExplicitInstantiationDeclaration;
7464 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7465 REnd = Class->redecls_end();
7466 R != REnd; ++R) {
7467 TemplateSpecializationKind TSK
7468 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7469 if (TSK == TSK_ExplicitInstantiationDeclaration)
7470 IsExplicitInstantiationDeclaration = true;
7471 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7472 IsExplicitInstantiationDeclaration = false;
7473 break;
7474 }
7475 }
7476
7477 if (IsExplicitInstantiationDeclaration)
7478 continue;
7479 }
7480
7481 // Mark all of the virtual members of this class as referenced, so
7482 // that we can build a vtable. Then, tell the AST consumer that a
7483 // vtable for this class is required.
7484 MarkVirtualMembersReferenced(Loc, Class);
7485 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7486 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7487
7488 // Optionally warn if we're emitting a weak vtable.
7489 if (Class->getLinkage() == ExternalLinkage &&
7490 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007491 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007492 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7493 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007494 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007495 VTableUses.clear();
7496
Anders Carlssond6a637f2009-12-07 08:24:59 +00007497 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007498}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007499
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007500void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7501 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007502 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7503 e = RD->method_end(); i != e; ++i) {
7504 CXXMethodDecl *MD = *i;
7505
7506 // C++ [basic.def.odr]p2:
7507 // [...] A virtual member function is used if it is not pure. [...]
7508 if (MD->isVirtual() && !MD->isPure())
7509 MarkDeclarationReferenced(Loc, MD);
7510 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007511
7512 // Only classes that have virtual bases need a VTT.
7513 if (RD->getNumVBases() == 0)
7514 return;
7515
7516 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7517 e = RD->bases_end(); i != e; ++i) {
7518 const CXXRecordDecl *Base =
7519 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007520 if (Base->getNumVBases() == 0)
7521 continue;
7522 MarkVirtualMembersReferenced(Loc, Base);
7523 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007524}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007525
7526/// SetIvarInitializers - This routine builds initialization ASTs for the
7527/// Objective-C implementation whose ivars need be initialized.
7528void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7529 if (!getLangOptions().CPlusPlus)
7530 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007531 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007532 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7533 CollectIvarsToConstructOrDestruct(OID, ivars);
7534 if (ivars.empty())
7535 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007536 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007537 for (unsigned i = 0; i < ivars.size(); i++) {
7538 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007539 if (Field->isInvalidDecl())
7540 continue;
7541
Sean Huntcbb67482011-01-08 20:30:50 +00007542 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007543 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7544 InitializationKind InitKind =
7545 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7546
7547 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007548 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007549 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007550 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007551 // Note, MemberInit could actually come back empty if no initialization
7552 // is required (e.g., because it would call a trivial default constructor)
7553 if (!MemberInit.get() || MemberInit.isInvalid())
7554 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007555
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007556 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007557 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7558 SourceLocation(),
7559 MemberInit.takeAs<Expr>(),
7560 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007561 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007562
7563 // Be sure that the destructor is accessible and is marked as referenced.
7564 if (const RecordType *RecordTy
7565 = Context.getBaseElementType(Field->getType())
7566 ->getAs<RecordType>()) {
7567 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007568 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007569 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7570 CheckDestructorAccess(Field->getLocation(), Destructor,
7571 PDiag(diag::err_access_dtor_ivar)
7572 << Context.getBaseElementType(Field->getType()));
7573 }
7574 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007575 }
7576 ObjCImplementation->setIvarInitializers(Context,
7577 AllToInit.data(), AllToInit.size());
7578 }
7579}