blob: 8b7bbb69540580cee3e79b81936963eac75f9cd6 [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"
Sean Hunt41717662011-02-26 19:13:13 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000031#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000033#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000035#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000036#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000037
38using namespace clang;
39
Chris Lattner8123a952008-04-10 02:22:51 +000040//===----------------------------------------------------------------------===//
41// CheckDefaultArgumentVisitor
42//===----------------------------------------------------------------------===//
43
Chris Lattner9e979552008-04-12 23:52:44 +000044namespace {
45 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
46 /// the default argument of a parameter to determine whether it
47 /// contains any ill-formed subexpressions. For example, this will
48 /// diagnose the use of local variables or parameters within the
49 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000050 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000051 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000052 Expr *DefaultArg;
53 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-04-12 23:52:44 +000055 public:
Mike Stump1eb44332009-09-09 15:08:12 +000056 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000057 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 bool VisitExpr(Expr *Node);
60 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000061 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000062 };
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 /// VisitExpr - Visit all of the children of this expression.
65 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
66 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000067 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000068 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000138
John McCallb4eb64d2010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson9351c172009-08-25 03:18:48 +0000157 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000158}
159
Chris Lattner8123a952008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163void
John McCalld226f652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCalld226f652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6f526752010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlsson66e30672009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump1eb44332009-09-09 15:08:12 +0000192
John McCall9ae2f072010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000194}
195
Douglas Gregor61366e92008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
John McCalld226f652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Anders Carlsson5e300d12009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000211}
212
Douglas Gregor72b505b2008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000218
John McCalld226f652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Anders Carlsson5e300d12009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Anders Carlsson5e300d12009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000224}
225
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner3d1cee32008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregor6cc15182009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCall3d6c1782010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregore13ad832010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000382
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384}
385
Sebastian Redl60618fa2011-03-12 11:50:43 +0000386/// \brief Merge the exception specifications of two variable declarations.
387///
388/// This is called when there's a redeclaration of a VarDecl. The function
389/// checks if the redeclaration might have an exception specification and
390/// validates compatibility and merges the specs if necessary.
391void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
392 // Shortcut if exceptions are disabled.
393 if (!getLangOptions().CXXExceptions)
394 return;
395
396 assert(Context.hasSameType(New->getType(), Old->getType()) &&
397 "Should only be called if types are otherwise the same.");
398
399 QualType NewType = New->getType();
400 QualType OldType = Old->getType();
401
402 // We're only interested in pointers and references to functions, as well
403 // as pointers to member functions.
404 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
405 NewType = R->getPointeeType();
406 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
407 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
408 NewType = P->getPointeeType();
409 OldType = OldType->getAs<PointerType>()->getPointeeType();
410 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
411 NewType = M->getPointeeType();
412 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
413 }
414
415 if (!NewType->isFunctionProtoType())
416 return;
417
418 // There's lots of special cases for functions. For function pointers, system
419 // libraries are hopefully not as broken so that we don't need these
420 // workarounds.
421 if (CheckEquivalentExceptionSpec(
422 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
423 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
424 New->setInvalidDecl();
425 }
426}
427
Chris Lattner3d1cee32008-04-08 05:04:30 +0000428/// CheckCXXDefaultArguments - Verify that the default arguments for a
429/// function declaration are well-formed according to C++
430/// [dcl.fct.default].
431void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
432 unsigned NumParams = FD->getNumParams();
433 unsigned p;
434
435 // Find first parameter with a default argument
436 for (p = 0; p < NumParams; ++p) {
437 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000438 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000439 break;
440 }
441
442 // C++ [dcl.fct.default]p4:
443 // In a given function declaration, all parameters
444 // subsequent to a parameter with a default argument shall
445 // have default arguments supplied in this or previous
446 // declarations. A default argument shall not be redefined
447 // by a later declaration (not even to the same value).
448 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000449 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000450 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000451 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000452 if (Param->isInvalidDecl())
453 /* We already complained about this parameter. */;
454 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000455 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000456 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000457 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000458 else
Mike Stump1eb44332009-09-09 15:08:12 +0000459 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000460 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner3d1cee32008-04-08 05:04:30 +0000462 LastMissingDefaultArg = p;
463 }
464 }
465
466 if (LastMissingDefaultArg > 0) {
467 // Some default arguments were missing. Clear out all of the
468 // default arguments up to (and including) the last missing
469 // default argument, so that we leave the function parameters
470 // in a semantically valid state.
471 for (p = 0; p <= LastMissingDefaultArg; ++p) {
472 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000473 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000474 Param->setDefaultArg(0);
475 }
476 }
477 }
478}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000479
Douglas Gregorb48fe382008-10-31 09:07:45 +0000480/// isCurrentClassName - Determine whether the identifier II is the
481/// name of the class type currently being defined. In the case of
482/// nested classes, this will only return true if II is the name of
483/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000484bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
485 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000486 assert(getLangOptions().CPlusPlus && "No class names in C!");
487
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000488 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000489 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000490 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000491 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
492 } else
493 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
494
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000495 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000496 return &II == CurDecl->getIdentifier();
497 else
498 return false;
499}
500
Mike Stump1eb44332009-09-09 15:08:12 +0000501/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000502///
503/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
504/// and returns NULL otherwise.
505CXXBaseSpecifier *
506Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
507 SourceRange SpecifierRange,
508 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000509 TypeSourceInfo *TInfo,
510 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000511 QualType BaseType = TInfo->getType();
512
Douglas Gregor2943aed2009-03-03 04:44:36 +0000513 // C++ [class.union]p1:
514 // A union shall not have base classes.
515 if (Class->isUnion()) {
516 Diag(Class->getLocation(), diag::err_base_clause_on_union)
517 << SpecifierRange;
518 return 0;
519 }
520
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000521 if (EllipsisLoc.isValid() &&
522 !TInfo->getType()->containsUnexpandedParameterPack()) {
523 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
524 << TInfo->getTypeLoc().getSourceRange();
525 EllipsisLoc = SourceLocation();
526 }
527
Douglas Gregor2943aed2009-03-03 04:44:36 +0000528 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000529 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000530 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000531 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000532
533 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000534
535 // Base specifiers must be record types.
536 if (!BaseType->isRecordType()) {
537 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
538 return 0;
539 }
540
541 // C++ [class.union]p1:
542 // A union shall not be used as a base class.
543 if (BaseType->isUnionType()) {
544 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
545 return 0;
546 }
547
548 // C++ [class.derived]p2:
549 // The class-name in a base-specifier shall not be an incompletely
550 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000551 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000552 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000553 << SpecifierRange)) {
554 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000555 return 0;
John McCall572fc622010-08-17 07:23:57 +0000556 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557
Eli Friedman1d954f62009-08-15 21:55:26 +0000558 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000560 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000561 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000562 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000563 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
564 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000565
Anders Carlssondfc2f102011-01-22 17:51:53 +0000566 // C++ [class.derived]p2:
567 // If a class is marked with the class-virt-specifier final and it appears
568 // as a base-type-specifier in a base-clause (10 class.derived), the program
569 // is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000570 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000571 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
572 << CXXBaseDecl->getDeclName();
573 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
574 << CXXBaseDecl->getDeclName();
575 return 0;
576 }
577
John McCall572fc622010-08-17 07:23:57 +0000578 if (BaseDecl->isInvalidDecl())
579 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000580
581 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000582 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000583 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000584 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000585}
586
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000587/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
588/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000589/// example:
590/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000591/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000592BaseResult
John McCalld226f652010-08-21 09:40:31 +0000593Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000594 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000595 ParsedType basetype, SourceLocation BaseLoc,
596 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000597 if (!classdecl)
598 return true;
599
Douglas Gregor40808ce2009-03-09 23:48:35 +0000600 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000601 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000602 if (!Class)
603 return true;
604
Nick Lewycky56062202010-07-26 16:56:01 +0000605 TypeSourceInfo *TInfo = 0;
606 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000607
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000608 if (EllipsisLoc.isInvalid() &&
609 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000610 UPPC_BaseType))
611 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000612
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000614 Virtual, Access, TInfo,
615 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000619}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000620
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621/// \brief Performs the actual work of attaching the given base class
622/// specifiers to a C++ class.
623bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
624 unsigned NumBases) {
625 if (NumBases == 0)
626 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000627
628 // Used to keep track of which base types we have already seen, so
629 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000630 // that the key is always the unqualified canonical type of the base
631 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000632 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
633
634 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000635 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000637 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000638 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000640 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000641 if (!Class->hasObjectMember()) {
642 if (const RecordType *FDTTy =
643 NewBaseType.getTypePtr()->getAs<RecordType>())
644 if (FDTTy->getDecl()->hasObjectMember())
645 Class->setHasObjectMember(true);
646 }
647
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000648 if (KnownBaseTypes[NewBaseType]) {
649 // C++ [class.mi]p3:
650 // A class shall not be specified as a direct base class of a
651 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000652 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000653 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000654 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000655 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000656
657 // Delete the duplicate base class specifier; we're going to
658 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000659 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000660
661 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000662 } else {
663 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000664 KnownBaseTypes[NewBaseType] = Bases[idx];
665 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000666 }
667 }
668
669 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000670 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000671
672 // Delete the remaining (good) base class specifiers, since their
673 // data has been copied into the CXXRecordDecl.
674 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000675 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000676
677 return Invalid;
678}
679
680/// ActOnBaseSpecifiers - Attach the given base specifiers to the
681/// class, after checking whether there are any duplicate base
682/// classes.
John McCalld226f652010-08-21 09:40:31 +0000683void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000684 unsigned NumBases) {
685 if (!ClassDecl || !Bases || !NumBases)
686 return;
687
688 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000689 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000690 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000691}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000692
John McCall3cb0ebd2010-03-10 03:28:59 +0000693static CXXRecordDecl *GetClassForType(QualType T) {
694 if (const RecordType *RT = T->getAs<RecordType>())
695 return cast<CXXRecordDecl>(RT->getDecl());
696 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
697 return ICT->getDecl();
698 else
699 return 0;
700}
701
Douglas Gregora8f32e02009-10-06 17:59:45 +0000702/// \brief Determine whether the type \p Derived is a C++ class that is
703/// derived from the type \p Base.
704bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
705 if (!getLangOptions().CPlusPlus)
706 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000707
708 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
709 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000710 return false;
711
John McCall3cb0ebd2010-03-10 03:28:59 +0000712 CXXRecordDecl *BaseRD = GetClassForType(Base);
713 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000714 return false;
715
John McCall86ff3082010-02-04 22:26:26 +0000716 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
717 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000718}
719
720/// \brief Determine whether the type \p Derived is a C++ class that is
721/// derived from the type \p Base.
722bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
723 if (!getLangOptions().CPlusPlus)
724 return false;
725
John McCall3cb0ebd2010-03-10 03:28:59 +0000726 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
727 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000728 return false;
729
John McCall3cb0ebd2010-03-10 03:28:59 +0000730 CXXRecordDecl *BaseRD = GetClassForType(Base);
731 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000732 return false;
733
Douglas Gregora8f32e02009-10-06 17:59:45 +0000734 return DerivedRD->isDerivedFrom(BaseRD, Paths);
735}
736
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000737void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000738 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000739 assert(BasePathArray.empty() && "Base path array must be empty!");
740 assert(Paths.isRecordingPaths() && "Must record paths!");
741
742 const CXXBasePath &Path = Paths.front();
743
744 // We first go backward and check if we have a virtual base.
745 // FIXME: It would be better if CXXBasePath had the base specifier for
746 // the nearest virtual base.
747 unsigned Start = 0;
748 for (unsigned I = Path.size(); I != 0; --I) {
749 if (Path[I - 1].Base->isVirtual()) {
750 Start = I - 1;
751 break;
752 }
753 }
754
755 // Now add all bases.
756 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000757 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000758}
759
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000760/// \brief Determine whether the given base path includes a virtual
761/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000762bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
763 for (CXXCastPath::const_iterator B = BasePath.begin(),
764 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000765 B != BEnd; ++B)
766 if ((*B)->isVirtual())
767 return true;
768
769 return false;
770}
771
Douglas Gregora8f32e02009-10-06 17:59:45 +0000772/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
773/// conversion (where Derived and Base are class types) is
774/// well-formed, meaning that the conversion is unambiguous (and
775/// that all of the base classes are accessible). Returns true
776/// and emits a diagnostic if the code is ill-formed, returns false
777/// otherwise. Loc is the location where this routine should point to
778/// if there is an error, and Range is the source range to highlight
779/// if there is an error.
780bool
781Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000782 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000783 unsigned AmbigiousBaseConvID,
784 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000785 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000786 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000787 // First, determine whether the path from Derived to Base is
788 // ambiguous. This is slightly more expensive than checking whether
789 // the Derived to Base conversion exists, because here we need to
790 // explore multiple paths to determine if there is an ambiguity.
791 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
792 /*DetectVirtual=*/false);
793 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
794 assert(DerivationOkay &&
795 "Can only be used with a derived-to-base conversion");
796 (void)DerivationOkay;
797
798 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000799 if (InaccessibleBaseID) {
800 // Check that the base class can be accessed.
801 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
802 InaccessibleBaseID)) {
803 case AR_inaccessible:
804 return true;
805 case AR_accessible:
806 case AR_dependent:
807 case AR_delayed:
808 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000809 }
John McCall6b2accb2010-02-10 09:31:12 +0000810 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000811
812 // Build a base path if necessary.
813 if (BasePath)
814 BuildBasePathArray(Paths, *BasePath);
815 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000816 }
817
818 // We know that the derived-to-base conversion is ambiguous, and
819 // we're going to produce a diagnostic. Perform the derived-to-base
820 // search just one more time to compute all of the possible paths so
821 // that we can print them out. This is more expensive than any of
822 // the previous derived-to-base checks we've done, but at this point
823 // performance isn't as much of an issue.
824 Paths.clear();
825 Paths.setRecordingPaths(true);
826 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
827 assert(StillOkay && "Can only be used with a derived-to-base conversion");
828 (void)StillOkay;
829
830 // Build up a textual representation of the ambiguous paths, e.g.,
831 // D -> B -> A, that will be used to illustrate the ambiguous
832 // conversions in the diagnostic. We only print one of the paths
833 // to each base class subobject.
834 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
835
836 Diag(Loc, AmbigiousBaseConvID)
837 << Derived << Base << PathDisplayStr << Range << Name;
838 return true;
839}
840
841bool
842Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000843 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000844 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000845 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000846 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000847 IgnoreAccess ? 0
848 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000850 Loc, Range, DeclarationName(),
851 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000852}
853
854
855/// @brief Builds a string representing ambiguous paths from a
856/// specific derived class to different subobjects of the same base
857/// class.
858///
859/// This function builds a string that can be used in error messages
860/// to show the different paths that one can take through the
861/// inheritance hierarchy to go from the derived class to different
862/// subobjects of a base class. The result looks something like this:
863/// @code
864/// struct D -> struct B -> struct A
865/// struct D -> struct C -> struct A
866/// @endcode
867std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
868 std::string PathDisplayStr;
869 std::set<unsigned> DisplayedPaths;
870 for (CXXBasePaths::paths_iterator Path = Paths.begin();
871 Path != Paths.end(); ++Path) {
872 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
873 // We haven't displayed a path to this particular base
874 // class subobject yet.
875 PathDisplayStr += "\n ";
876 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
877 for (CXXBasePath::const_iterator Element = Path->begin();
878 Element != Path->end(); ++Element)
879 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
880 }
881 }
882
883 return PathDisplayStr;
884}
885
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000886//===----------------------------------------------------------------------===//
887// C++ class member Handling
888//===----------------------------------------------------------------------===//
889
Abramo Bagnara6206d532010-06-05 05:09:32 +0000890/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000891Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
892 SourceLocation ASLoc,
893 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000894 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000895 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000896 ASLoc, ColonLoc);
897 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000898 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000899}
900
Anders Carlsson9e682d92011-01-20 05:57:14 +0000901/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000902void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000903 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
904 if (!MD || !MD->isVirtual())
905 return;
906
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000907 if (MD->isDependentContext())
908 return;
909
Anders Carlsson9e682d92011-01-20 05:57:14 +0000910 // C++0x [class.virtual]p3:
911 // If a virtual function is marked with the virt-specifier override and does
912 // not override a member function of a base class,
913 // the program is ill-formed.
914 bool HasOverriddenMethods =
915 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000916 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000917 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000918 diag::err_function_marked_override_not_overriding)
919 << MD->getDeclName();
920 return;
921 }
Anders Carlssonaa23d282011-01-22 22:23:37 +0000922
923 // C++0x [class.derived]p8:
924 // In a class definition marked with the class-virt-specifier explicit,
925 // if a virtual member function that is neither implicitly-declared nor a
926 // destructor overrides a member function of a base class and it is not
927 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000928 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
929 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlssonaa23d282011-01-22 22:23:37 +0000930 llvm::SmallVector<const CXXMethodDecl*, 4>
931 OverriddenMethods(MD->begin_overridden_methods(),
932 MD->end_overridden_methods());
933
934 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
935 << MD->getDeclName()
936 << (unsigned)OverriddenMethods.size();
937
938 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
939 Diag(OverriddenMethods[I]->getLocation(),
940 diag::note_overridden_virtual_function);
941 }
Anders Carlsson9e682d92011-01-20 05:57:14 +0000942}
943
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000944/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
945/// function overrides a virtual member function marked 'final', according to
946/// C++0x [class.virtual]p3.
947bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
948 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000949 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000950 return false;
951
952 Diag(New->getLocation(), diag::err_final_function_overridden)
953 << New->getDeclName();
954 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
955 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000956}
957
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000958/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
959/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
960/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000961/// any.
John McCalld226f652010-08-21 09:40:31 +0000962Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000963Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000964 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000965 ExprTy *BW, const VirtSpecifiers &VS,
966 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000967 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000968 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000969 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
970 DeclarationName Name = NameInfo.getName();
971 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000972
973 // For anonymous bitfields, the location should point to the type.
974 if (Loc.isInvalid())
975 Loc = D.getSourceRange().getBegin();
976
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000977 Expr *BitWidth = static_cast<Expr*>(BW);
978 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000979
John McCall4bde1e12010-06-04 08:34:12 +0000980 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000981 assert(!DS.isFriendSpecified());
982
John McCall4bde1e12010-06-04 08:34:12 +0000983 bool isFunc = false;
984 if (D.isFunctionDeclarator())
985 isFunc = true;
986 else if (D.getNumTypeObjects() == 0 &&
987 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000988 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000989 isFunc = TDType->isFunctionType();
990 }
991
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992 // C++ 9.2p6: A member shall not be declared to have automatic storage
993 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000994 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
995 // data members and cannot be applied to names declared const or static,
996 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000997 switch (DS.getStorageClassSpec()) {
998 case DeclSpec::SCS_unspecified:
999 case DeclSpec::SCS_typedef:
1000 case DeclSpec::SCS_static:
1001 // FALL THROUGH.
1002 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001003 case DeclSpec::SCS_mutable:
1004 if (isFunc) {
1005 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001006 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001007 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001008 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Sebastian Redla11f42f2008-11-17 23:24:37 +00001010 // FIXME: It would be nicer if the keyword was ignored only for this
1011 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001012 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001013 }
1014 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001015 default:
1016 if (DS.getStorageClassSpecLoc().isValid())
1017 Diag(DS.getStorageClassSpecLoc(),
1018 diag::err_storageclass_invalid_for_member);
1019 else
1020 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1021 D.getMutableDeclSpec().ClearStorageClassSpecs();
1022 }
1023
Sebastian Redl669d5d72008-11-14 23:42:31 +00001024 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1025 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001026 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001027
1028 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001029 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001030 CXXScopeSpec &SS = D.getCXXScopeSpec();
1031
1032
1033 if (SS.isSet() && !SS.isInvalid()) {
1034 // The user provided a superfluous scope specifier inside a class
1035 // definition:
1036 //
1037 // class X {
1038 // int X::member;
1039 // };
1040 DeclContext *DC = 0;
1041 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1042 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1043 << Name << FixItHint::CreateRemoval(SS.getRange());
1044 else
1045 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1046 << Name << SS.getRange();
1047
1048 SS.clear();
1049 }
1050
Douglas Gregor37b372b2009-08-20 22:52:58 +00001051 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001052 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001053 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1054 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001055 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001056 } else {
John McCalld226f652010-08-21 09:40:31 +00001057 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001058 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001059 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001060 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001061
1062 // Non-instance-fields can't have a bitfield.
1063 if (BitWidth) {
1064 if (Member->isInvalidDecl()) {
1065 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001066 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001067 // C++ 9.6p3: A bit-field shall not be a static member.
1068 // "static member 'A' cannot be a bit-field"
1069 Diag(Loc, diag::err_static_not_bitfield)
1070 << Name << BitWidth->getSourceRange();
1071 } else if (isa<TypedefDecl>(Member)) {
1072 // "typedef member 'x' cannot be a bit-field"
1073 Diag(Loc, diag::err_typedef_not_bitfield)
1074 << Name << BitWidth->getSourceRange();
1075 } else {
1076 // A function typedef ("typedef int f(); f a;").
1077 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1078 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001079 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001080 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattner8b963ef2009-03-05 23:01:03 +00001083 BitWidth = 0;
1084 Member->setInvalidDecl();
1085 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001086
1087 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregor37b372b2009-08-20 22:52:58 +00001089 // If we have declared a member function template, set the access of the
1090 // templated declaration as well.
1091 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1092 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001093 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001094
Anders Carlssonaae5af22011-01-20 04:34:22 +00001095 if (VS.isOverrideSpecified()) {
1096 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1097 if (!MD || !MD->isVirtual()) {
1098 Diag(Member->getLocStart(),
1099 diag::override_keyword_only_allowed_on_virtual_member_functions)
1100 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001101 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001102 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001103 }
1104 if (VS.isFinalSpecified()) {
1105 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1106 if (!MD || !MD->isVirtual()) {
1107 Diag(Member->getLocStart(),
1108 diag::override_keyword_only_allowed_on_virtual_member_functions)
1109 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001110 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001111 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001112 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001113
Douglas Gregorf5251602011-03-08 17:10:18 +00001114 if (VS.getLastLocation().isValid()) {
1115 // Update the end location of a method that has a virt-specifiers.
1116 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1117 MD->setRangeEnd(VS.getLastLocation());
1118 }
1119
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001120 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001121
Douglas Gregor10bd3682008-11-17 22:58:34 +00001122 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001123
Douglas Gregor021c3b32009-03-11 23:00:04 +00001124 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001125 AddInitializerToDecl(Member, Init, false,
1126 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redle2b68332009-04-12 17:16:29 +00001127 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001128 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001129
Richard Smith483b9f32011-02-21 20:05:19 +00001130 FinalizeDeclaration(Member);
1131
John McCallb25b2952011-02-15 07:12:36 +00001132 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001133 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001134 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001135}
1136
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001137/// \brief Find the direct and/or virtual base specifiers that
1138/// correspond to the given base type, for use in base initialization
1139/// within a constructor.
1140static bool FindBaseInitializer(Sema &SemaRef,
1141 CXXRecordDecl *ClassDecl,
1142 QualType BaseType,
1143 const CXXBaseSpecifier *&DirectBaseSpec,
1144 const CXXBaseSpecifier *&VirtualBaseSpec) {
1145 // First, check for a direct base class.
1146 DirectBaseSpec = 0;
1147 for (CXXRecordDecl::base_class_const_iterator Base
1148 = ClassDecl->bases_begin();
1149 Base != ClassDecl->bases_end(); ++Base) {
1150 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1151 // We found a direct base of this type. That's what we're
1152 // initializing.
1153 DirectBaseSpec = &*Base;
1154 break;
1155 }
1156 }
1157
1158 // Check for a virtual base class.
1159 // FIXME: We might be able to short-circuit this if we know in advance that
1160 // there are no virtual bases.
1161 VirtualBaseSpec = 0;
1162 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1163 // We haven't found a base yet; search the class hierarchy for a
1164 // virtual base class.
1165 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1166 /*DetectVirtual=*/false);
1167 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1168 BaseType, Paths)) {
1169 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1170 Path != Paths.end(); ++Path) {
1171 if (Path->back().Base->isVirtual()) {
1172 VirtualBaseSpec = Path->back().Base;
1173 break;
1174 }
1175 }
1176 }
1177 }
1178
1179 return DirectBaseSpec || VirtualBaseSpec;
1180}
1181
Douglas Gregor7ad83902008-11-05 04:29:56 +00001182/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001183MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001184Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001185 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001186 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001187 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001188 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001189 SourceLocation IdLoc,
1190 SourceLocation LParenLoc,
1191 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001192 SourceLocation RParenLoc,
1193 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001194 if (!ConstructorD)
1195 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001197 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
1199 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001200 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001201 if (!Constructor) {
1202 // The user wrote a constructor initializer on a function that is
1203 // not a C++ constructor. Ignore the error for now, because we may
1204 // have more member initializers coming; we'll diagnose it just
1205 // once in ActOnMemInitializers.
1206 return true;
1207 }
1208
1209 CXXRecordDecl *ClassDecl = Constructor->getParent();
1210
1211 // C++ [class.base.init]p2:
1212 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001213 // constructor's class and, if not found in that scope, are looked
1214 // up in the scope containing the constructor's definition.
1215 // [Note: if the constructor's class contains a member with the
1216 // same name as a direct or virtual base class of the class, a
1217 // mem-initializer-id naming the member or base class and composed
1218 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001219 // mem-initializer-id for the hidden base class may be specified
1220 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001221 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001222 // Look for a member, first.
1223 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001224 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001225 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001226 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001227 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001228
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001229 if (Member) {
1230 if (EllipsisLoc.isValid())
1231 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1232 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1233
Francois Pichet00eb3f92010-12-04 09:14:42 +00001234 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001235 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001236 }
1237
Francois Pichet00eb3f92010-12-04 09:14:42 +00001238 // Handle anonymous union case.
1239 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001240 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1241 if (EllipsisLoc.isValid())
1242 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1243 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1244
Francois Pichet00eb3f92010-12-04 09:14:42 +00001245 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1246 NumArgs, IdLoc,
1247 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001248 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001249 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001250 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001251 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001252 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001253 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001254
1255 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001256 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001257 } else {
1258 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1259 LookupParsedName(R, S, &SS);
1260
1261 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1262 if (!TyD) {
1263 if (R.isAmbiguous()) return true;
1264
John McCallfd225442010-04-09 19:01:14 +00001265 // We don't want access-control diagnostics here.
1266 R.suppressDiagnostics();
1267
Douglas Gregor7a886e12010-01-19 06:46:48 +00001268 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1269 bool NotUnknownSpecialization = false;
1270 DeclContext *DC = computeDeclContext(SS, false);
1271 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1272 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1273
1274 if (!NotUnknownSpecialization) {
1275 // When the scope specifier can refer to a member of an unknown
1276 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001277 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1278 SS.getWithLocInContext(Context),
1279 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001280 if (BaseType.isNull())
1281 return true;
1282
Douglas Gregor7a886e12010-01-19 06:46:48 +00001283 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001284 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001285 }
1286 }
1287
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001288 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001289 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001290 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1291 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001292 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001293 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001294 // We have found a non-static data member with a similar
1295 // name to what was typed; complain and initialize that
1296 // member.
1297 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1298 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001299 << FixItHint::CreateReplacement(R.getNameLoc(),
1300 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001301 Diag(Member->getLocation(), diag::note_previous_decl)
1302 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001303
1304 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1305 LParenLoc, RParenLoc);
1306 }
1307 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1308 const CXXBaseSpecifier *DirectBaseSpec;
1309 const CXXBaseSpecifier *VirtualBaseSpec;
1310 if (FindBaseInitializer(*this, ClassDecl,
1311 Context.getTypeDeclType(Type),
1312 DirectBaseSpec, VirtualBaseSpec)) {
1313 // We have found a direct or virtual base class with a
1314 // similar name to what was typed; complain and initialize
1315 // that base class.
1316 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1317 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001318 << FixItHint::CreateReplacement(R.getNameLoc(),
1319 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001320
1321 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1322 : VirtualBaseSpec;
1323 Diag(BaseSpec->getSourceRange().getBegin(),
1324 diag::note_base_class_specified_here)
1325 << BaseSpec->getType()
1326 << BaseSpec->getSourceRange();
1327
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001328 TyD = Type;
1329 }
1330 }
1331 }
1332
Douglas Gregor7a886e12010-01-19 06:46:48 +00001333 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001334 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1335 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1336 return true;
1337 }
John McCall2b194412009-12-21 10:41:20 +00001338 }
1339
Douglas Gregor7a886e12010-01-19 06:46:48 +00001340 if (BaseType.isNull()) {
1341 BaseType = Context.getTypeDeclType(TyD);
1342 if (SS.isSet()) {
1343 NestedNameSpecifier *Qualifier =
1344 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001345
Douglas Gregor7a886e12010-01-19 06:46:48 +00001346 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001347 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001348 }
John McCall2b194412009-12-21 10:41:20 +00001349 }
1350 }
Mike Stump1eb44332009-09-09 15:08:12 +00001351
John McCalla93c9342009-12-07 02:54:59 +00001352 if (!TInfo)
1353 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001354
John McCalla93c9342009-12-07 02:54:59 +00001355 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001356 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001357}
1358
John McCallb4190042009-11-04 23:02:40 +00001359/// Checks an initializer expression for use of uninitialized fields, such as
1360/// containing the field that is being initialized. Returns true if there is an
1361/// uninitialized field was used an updates the SourceLocation parameter; false
1362/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001363static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001364 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001365 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001366 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1367
Nick Lewycky43ad1822010-06-15 07:32:55 +00001368 if (isa<CallExpr>(S)) {
1369 // Do not descend into function calls or constructors, as the use
1370 // of an uninitialized field may be valid. One would have to inspect
1371 // the contents of the function/ctor to determine if it is safe or not.
1372 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1373 // may be safe, depending on what the function/ctor does.
1374 return false;
1375 }
1376 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1377 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001378
1379 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1380 // The member expression points to a static data member.
1381 assert(VD->isStaticDataMember() &&
1382 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001383 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001384 return false;
1385 }
1386
1387 if (isa<EnumConstantDecl>(RhsField)) {
1388 // The member expression points to an enum.
1389 return false;
1390 }
1391
John McCallb4190042009-11-04 23:02:40 +00001392 if (RhsField == LhsField) {
1393 // Initializing a field with itself. Throw a warning.
1394 // But wait; there are exceptions!
1395 // Exception #1: The field may not belong to this record.
1396 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001397 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001398 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1399 // Even though the field matches, it does not belong to this record.
1400 return false;
1401 }
1402 // None of the exceptions triggered; return true to indicate an
1403 // uninitialized field was used.
1404 *L = ME->getMemberLoc();
1405 return true;
1406 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001407 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001408 // sizeof/alignof doesn't reference contents, do not warn.
1409 return false;
1410 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1411 // address-of doesn't reference contents (the pointer may be dereferenced
1412 // in the same expression but it would be rare; and weird).
1413 if (UOE->getOpcode() == UO_AddrOf)
1414 return false;
John McCallb4190042009-11-04 23:02:40 +00001415 }
John McCall7502c1d2011-02-13 04:07:26 +00001416 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001417 if (!*it) {
1418 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001419 continue;
1420 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001421 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1422 return true;
John McCallb4190042009-11-04 23:02:40 +00001423 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001424 return false;
John McCallb4190042009-11-04 23:02:40 +00001425}
1426
John McCallf312b1e2010-08-26 23:41:50 +00001427MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001428Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001429 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001430 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001431 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001432 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1433 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1434 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001435 "Member must be a FieldDecl or IndirectFieldDecl");
1436
Douglas Gregor464b2f02010-11-05 22:21:31 +00001437 if (Member->isInvalidDecl())
1438 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001439
John McCallb4190042009-11-04 23:02:40 +00001440 // Diagnose value-uses of fields to initialize themselves, e.g.
1441 // foo(foo)
1442 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001443 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001444 for (unsigned i = 0; i < NumArgs; ++i) {
1445 SourceLocation L;
1446 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1447 // FIXME: Return true in the case when other fields are used before being
1448 // uninitialized. For example, let this field be the i'th field. When
1449 // initializing the i'th field, throw a warning if any of the >= i'th
1450 // fields are used, as they are not yet initialized.
1451 // Right now we are only handling the case where the i'th field uses
1452 // itself in its initializer.
1453 Diag(L, diag::warn_field_is_uninit);
1454 }
1455 }
1456
Eli Friedman59c04372009-07-29 19:44:27 +00001457 bool HasDependentArg = false;
1458 for (unsigned i = 0; i < NumArgs; i++)
1459 HasDependentArg |= Args[i]->isTypeDependent();
1460
Chandler Carruth894aed92010-12-06 09:23:57 +00001461 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001462 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001463 // Can't check initialization for a member of dependent type or when
1464 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001465 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1466 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001467
1468 // Erase any temporaries within this evaluation context; we're not
1469 // going to track them in the AST, since we'll be rebuilding the
1470 // ASTs during template instantiation.
1471 ExprTemporaries.erase(
1472 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1473 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001474 } else {
1475 // Initialize the member.
1476 InitializedEntity MemberEntity =
1477 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1478 : InitializedEntity::InitializeMember(IndirectMember, 0);
1479 InitializationKind Kind =
1480 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001481
Chandler Carruth894aed92010-12-06 09:23:57 +00001482 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1483
1484 ExprResult MemberInit =
1485 InitSeq.Perform(*this, MemberEntity, Kind,
1486 MultiExprArg(*this, Args, NumArgs), 0);
1487 if (MemberInit.isInvalid())
1488 return true;
1489
1490 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1491
1492 // C++0x [class.base.init]p7:
1493 // The initialization of each base and member constitutes a
1494 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001495 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001496 if (MemberInit.isInvalid())
1497 return true;
1498
1499 // If we are in a dependent context, template instantiation will
1500 // perform this type-checking again. Just save the arguments that we
1501 // received in a ParenListExpr.
1502 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1503 // of the information that we have about the member
1504 // initializer. However, deconstructing the ASTs is a dicey process,
1505 // and this approach is far more likely to get the corner cases right.
1506 if (CurContext->isDependentContext())
1507 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1508 RParenLoc);
1509 else
1510 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001511 }
1512
Chandler Carruth894aed92010-12-06 09:23:57 +00001513 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001514 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001515 IdLoc, LParenLoc, Init,
1516 RParenLoc);
1517 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001518 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001519 IdLoc, LParenLoc, Init,
1520 RParenLoc);
1521 }
Eli Friedman59c04372009-07-29 19:44:27 +00001522}
1523
John McCallf312b1e2010-08-26 23:41:50 +00001524MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001525Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1526 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001527 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001528 SourceLocation LParenLoc,
1529 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001530 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001531 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1532 if (!LangOpts.CPlusPlus0x)
1533 return Diag(Loc, diag::err_delegation_0x_only)
1534 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001535
Sean Hunt41717662011-02-26 19:13:13 +00001536 // Initialize the object.
1537 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1538 QualType(ClassDecl->getTypeForDecl(), 0));
1539 InitializationKind Kind =
1540 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1541
1542 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1543
1544 ExprResult DelegationInit =
1545 InitSeq.Perform(*this, DelegationEntity, Kind,
1546 MultiExprArg(*this, Args, NumArgs), 0);
1547 if (DelegationInit.isInvalid())
1548 return true;
1549
1550 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1551 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1552 assert(Constructor && "Delegating constructor with no target?");
1553
1554 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1555
1556 // C++0x [class.base.init]p7:
1557 // The initialization of each base and member constitutes a
1558 // full-expression.
1559 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1560 if (DelegationInit.isInvalid())
1561 return true;
1562
1563 // If we are in a dependent context, template instantiation will
1564 // perform this type-checking again. Just save the arguments that we
1565 // received in a ParenListExpr.
1566 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1567 // of the information that we have about the base
1568 // initializer. However, deconstructing the ASTs is a dicey process,
1569 // and this approach is far more likely to get the corner cases right.
1570 if (CurContext->isDependentContext()) {
1571 ExprResult Init
1572 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1573 NumArgs, RParenLoc));
1574 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1575 Constructor, Init.takeAs<Expr>(),
1576 RParenLoc);
1577 }
1578
1579 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1580 DelegationInit.takeAs<Expr>(),
1581 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001582}
1583
1584MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001585Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001586 Expr **Args, unsigned NumArgs,
1587 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001588 CXXRecordDecl *ClassDecl,
1589 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001590 bool HasDependentArg = false;
1591 for (unsigned i = 0; i < NumArgs; i++)
1592 HasDependentArg |= Args[i]->isTypeDependent();
1593
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001594 SourceLocation BaseLoc
1595 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1596
1597 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1598 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1599 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1600
1601 // C++ [class.base.init]p2:
1602 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001603 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001604 // of that class, the mem-initializer is ill-formed. A
1605 // mem-initializer-list can initialize a base class using any
1606 // name that denotes that base class type.
1607 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1608
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001609 if (EllipsisLoc.isValid()) {
1610 // This is a pack expansion.
1611 if (!BaseType->containsUnexpandedParameterPack()) {
1612 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1613 << SourceRange(BaseLoc, RParenLoc);
1614
1615 EllipsisLoc = SourceLocation();
1616 }
1617 } else {
1618 // Check for any unexpanded parameter packs.
1619 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1620 return true;
1621
1622 for (unsigned I = 0; I != NumArgs; ++I)
1623 if (DiagnoseUnexpandedParameterPack(Args[I]))
1624 return true;
1625 }
1626
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001627 // Check for direct and virtual base classes.
1628 const CXXBaseSpecifier *DirectBaseSpec = 0;
1629 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1630 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001631 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1632 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001633 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1634 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001635
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001636 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1637 VirtualBaseSpec);
1638
1639 // C++ [base.class.init]p2:
1640 // Unless the mem-initializer-id names a nonstatic data member of the
1641 // constructor's class or a direct or virtual base of that class, the
1642 // mem-initializer is ill-formed.
1643 if (!DirectBaseSpec && !VirtualBaseSpec) {
1644 // If the class has any dependent bases, then it's possible that
1645 // one of those types will resolve to the same type as
1646 // BaseType. Therefore, just treat this as a dependent base
1647 // class initialization. FIXME: Should we try to check the
1648 // initialization anyway? It seems odd.
1649 if (ClassDecl->hasAnyDependentBases())
1650 Dependent = true;
1651 else
1652 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1653 << BaseType << Context.getTypeDeclType(ClassDecl)
1654 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1655 }
1656 }
1657
1658 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001659 // Can't check initialization for a base of dependent type or when
1660 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001661 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001662 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1663 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001664
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001665 // Erase any temporaries within this evaluation context; we're not
1666 // going to track them in the AST, since we'll be rebuilding the
1667 // ASTs during template instantiation.
1668 ExprTemporaries.erase(
1669 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1670 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Sean Huntcbb67482011-01-08 20:30:50 +00001672 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001673 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001674 LParenLoc,
1675 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001676 RParenLoc,
1677 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001678 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001679
1680 // C++ [base.class.init]p2:
1681 // If a mem-initializer-id is ambiguous because it designates both
1682 // a direct non-virtual base class and an inherited virtual base
1683 // class, the mem-initializer is ill-formed.
1684 if (DirectBaseSpec && VirtualBaseSpec)
1685 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001686 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001687
1688 CXXBaseSpecifier *BaseSpec
1689 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1690 if (!BaseSpec)
1691 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1692
1693 // Initialize the base.
1694 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001695 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001696 InitializationKind Kind =
1697 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1698
1699 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1700
John McCall60d7b3a2010-08-24 06:29:42 +00001701 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001702 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001703 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001704 if (BaseInit.isInvalid())
1705 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001706
1707 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001708
1709 // C++0x [class.base.init]p7:
1710 // The initialization of each base and member constitutes a
1711 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001712 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001713 if (BaseInit.isInvalid())
1714 return true;
1715
1716 // If we are in a dependent context, template instantiation will
1717 // perform this type-checking again. Just save the arguments that we
1718 // received in a ParenListExpr.
1719 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1720 // of the information that we have about the base
1721 // initializer. However, deconstructing the ASTs is a dicey process,
1722 // and this approach is far more likely to get the corner cases right.
1723 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001724 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001725 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1726 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001727 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001728 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001729 LParenLoc,
1730 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001731 RParenLoc,
1732 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001733 }
1734
Sean Huntcbb67482011-01-08 20:30:50 +00001735 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001736 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001737 LParenLoc,
1738 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001739 RParenLoc,
1740 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001741}
1742
Anders Carlssone5ef7402010-04-23 03:10:23 +00001743/// ImplicitInitializerKind - How an implicit base or member initializer should
1744/// initialize its base or member.
1745enum ImplicitInitializerKind {
1746 IIK_Default,
1747 IIK_Copy,
1748 IIK_Move
1749};
1750
Anders Carlssondefefd22010-04-23 02:00:02 +00001751static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001752BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001753 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001754 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001755 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001756 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001757 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001758 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1759 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001760
John McCall60d7b3a2010-08-24 06:29:42 +00001761 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001762
1763 switch (ImplicitInitKind) {
1764 case IIK_Default: {
1765 InitializationKind InitKind
1766 = InitializationKind::CreateDefault(Constructor->getLocation());
1767 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1768 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001769 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001770 break;
1771 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001772
Anders Carlssone5ef7402010-04-23 03:10:23 +00001773 case IIK_Copy: {
1774 ParmVarDecl *Param = Constructor->getParamDecl(0);
1775 QualType ParamType = Param->getType().getNonReferenceType();
1776
1777 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001778 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001779 Constructor->getLocation(), ParamType,
1780 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001781
Anders Carlssonc7957502010-04-24 22:02:54 +00001782 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001783 QualType ArgTy =
1784 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1785 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001786
1787 CXXCastPath BasePath;
1788 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001789 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001790 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001791 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001792
Anders Carlssone5ef7402010-04-23 03:10:23 +00001793 InitializationKind InitKind
1794 = InitializationKind::CreateDirect(Constructor->getLocation(),
1795 SourceLocation(), SourceLocation());
1796 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1797 &CopyCtorArg, 1);
1798 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001799 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001800 break;
1801 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001802
Anders Carlssone5ef7402010-04-23 03:10:23 +00001803 case IIK_Move:
1804 assert(false && "Unhandled initializer kind!");
1805 }
John McCall9ae2f072010-08-23 23:25:46 +00001806
Douglas Gregor53c374f2010-12-07 00:41:46 +00001807 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001808 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001809 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001810
Anders Carlssondefefd22010-04-23 02:00:02 +00001811 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001812 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001813 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1814 SourceLocation()),
1815 BaseSpec->isVirtual(),
1816 SourceLocation(),
1817 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001818 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001819 SourceLocation());
1820
Anders Carlssondefefd22010-04-23 02:00:02 +00001821 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001822}
1823
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001824static bool
1825BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001826 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001827 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001828 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001829 if (Field->isInvalidDecl())
1830 return true;
1831
Chandler Carruthf186b542010-06-29 23:50:44 +00001832 SourceLocation Loc = Constructor->getLocation();
1833
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001834 if (ImplicitInitKind == IIK_Copy) {
1835 ParmVarDecl *Param = Constructor->getParamDecl(0);
1836 QualType ParamType = Param->getType().getNonReferenceType();
1837
1838 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001839 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001840 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001841
1842 // Build a reference to this field within the parameter.
1843 CXXScopeSpec SS;
1844 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1845 Sema::LookupMemberName);
1846 MemberLookup.addDecl(Field, AS_public);
1847 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001848 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001849 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001850 ParamType, Loc,
1851 /*IsArrow=*/false,
1852 SS,
1853 /*FirstQualifierInScope=*/0,
1854 MemberLookup,
1855 /*TemplateArgs=*/0);
1856 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001857 return true;
1858
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001859 // When the field we are copying is an array, create index variables for
1860 // each dimension of the array. We use these index variables to subscript
1861 // the source array, and other clients (e.g., CodeGen) will perform the
1862 // necessary iteration with these index variables.
1863 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1864 QualType BaseType = Field->getType();
1865 QualType SizeType = SemaRef.Context.getSizeType();
1866 while (const ConstantArrayType *Array
1867 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1868 // Create the iteration variable for this array index.
1869 IdentifierInfo *IterationVarName = 0;
1870 {
1871 llvm::SmallString<8> Str;
1872 llvm::raw_svector_ostream OS(Str);
1873 OS << "__i" << IndexVariables.size();
1874 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1875 }
1876 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001877 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001878 IterationVarName, SizeType,
1879 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001880 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001881 IndexVariables.push_back(IterationVar);
1882
1883 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001884 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001885 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001886 assert(!IterationVarRef.isInvalid() &&
1887 "Reference to invented variable cannot fail!");
1888
1889 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001890 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001891 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001892 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001893 Loc);
1894 if (CopyCtorArg.isInvalid())
1895 return true;
1896
1897 BaseType = Array->getElementType();
1898 }
1899
1900 // Construct the entity that we will be initializing. For an array, this
1901 // will be first element in the array, which may require several levels
1902 // of array-subscript entities.
1903 llvm::SmallVector<InitializedEntity, 4> Entities;
1904 Entities.reserve(1 + IndexVariables.size());
1905 Entities.push_back(InitializedEntity::InitializeMember(Field));
1906 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1907 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1908 0,
1909 Entities.back()));
1910
1911 // Direct-initialize to use the copy constructor.
1912 InitializationKind InitKind =
1913 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1914
1915 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1916 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1917 &CopyCtorArgE, 1);
1918
John McCall60d7b3a2010-08-24 06:29:42 +00001919 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001920 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001921 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001922 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001923 if (MemberInit.isInvalid())
1924 return true;
1925
1926 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001927 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001928 MemberInit.takeAs<Expr>(), Loc,
1929 IndexVariables.data(),
1930 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001931 return false;
1932 }
1933
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001934 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1935
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001936 QualType FieldBaseElementType =
1937 SemaRef.Context.getBaseElementType(Field->getType());
1938
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001939 if (FieldBaseElementType->isRecordType()) {
1940 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001941 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001942 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001943
1944 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001945 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001946 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001947
Douglas Gregor53c374f2010-12-07 00:41:46 +00001948 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001949 if (MemberInit.isInvalid())
1950 return true;
1951
1952 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001953 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001954 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001955 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001956 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001957 return false;
1958 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001959
1960 if (FieldBaseElementType->isReferenceType()) {
1961 SemaRef.Diag(Constructor->getLocation(),
1962 diag::err_uninitialized_member_in_ctor)
1963 << (int)Constructor->isImplicit()
1964 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1965 << 0 << Field->getDeclName();
1966 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1967 return true;
1968 }
1969
1970 if (FieldBaseElementType.isConstQualified()) {
1971 SemaRef.Diag(Constructor->getLocation(),
1972 diag::err_uninitialized_member_in_ctor)
1973 << (int)Constructor->isImplicit()
1974 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1975 << 1 << Field->getDeclName();
1976 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1977 return true;
1978 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001979
1980 // Nothing to initialize.
1981 CXXMemberInit = 0;
1982 return false;
1983}
John McCallf1860e52010-05-20 23:23:51 +00001984
1985namespace {
1986struct BaseAndFieldInfo {
1987 Sema &S;
1988 CXXConstructorDecl *Ctor;
1989 bool AnyErrorsInInits;
1990 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001991 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1992 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001993
1994 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1995 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1996 // FIXME: Handle implicit move constructors.
1997 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1998 IIK = IIK_Copy;
1999 else
2000 IIK = IIK_Default;
2001 }
2002};
2003}
2004
2005static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2006 FieldDecl *Top, FieldDecl *Field) {
2007
Chandler Carruthe861c602010-06-30 02:59:29 +00002008 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002009 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002010 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002011 return false;
2012 }
2013
2014 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2015 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2016 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002017 CXXRecordDecl *FieldClassDecl
2018 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002019
2020 // Even though union members never have non-trivial default
2021 // constructions in C++03, we still build member initializers for aggregate
2022 // record types which can be union members, and C++0x allows non-trivial
2023 // default constructors for union members, so we ensure that only one
2024 // member is initialized for these.
2025 if (FieldClassDecl->isUnion()) {
2026 // First check for an explicit initializer for one field.
2027 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2028 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002029 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002030 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002031
2032 // Once we've initialized a field of an anonymous union, the union
2033 // field in the class is also initialized, so exit immediately.
2034 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002035 } else if ((*FA)->isAnonymousStructOrUnion()) {
2036 if (CollectFieldInitializer(Info, Top, *FA))
2037 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002038 }
2039 }
2040
2041 // Fallthrough and construct a default initializer for the union as
2042 // a whole, which can call its default constructor if such a thing exists
2043 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2044 // behavior going forward with C++0x, when anonymous unions there are
2045 // finalized, we should revisit this.
2046 } else {
2047 // For structs, we simply descend through to initialize all members where
2048 // necessary.
2049 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2050 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2051 if (CollectFieldInitializer(Info, Top, *FA))
2052 return true;
2053 }
2054 }
John McCallf1860e52010-05-20 23:23:51 +00002055 }
2056
2057 // Don't try to build an implicit initializer if there were semantic
2058 // errors in any of the initializers (and therefore we might be
2059 // missing some that the user actually wrote).
2060 if (Info.AnyErrorsInInits)
2061 return false;
2062
Sean Huntcbb67482011-01-08 20:30:50 +00002063 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002064 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2065 return true;
John McCallf1860e52010-05-20 23:23:51 +00002066
Francois Pichet00eb3f92010-12-04 09:14:42 +00002067 if (Init)
2068 Info.AllToInit.push_back(Init);
2069
John McCallf1860e52010-05-20 23:23:51 +00002070 return false;
2071}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002072
Eli Friedman80c30da2009-11-09 19:20:36 +00002073bool
Sean Huntcbb67482011-01-08 20:30:50 +00002074Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2075 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002076 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002077 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002078 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002079 // Just store the initializers as written, they will be checked during
2080 // instantiation.
2081 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002082 Constructor->setNumCtorInitializers(NumInitializers);
2083 CXXCtorInitializer **baseOrMemberInitializers =
2084 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002085 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002086 NumInitializers * sizeof(CXXCtorInitializer*));
2087 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002088 }
2089
2090 return false;
2091 }
2092
John McCallf1860e52010-05-20 23:23:51 +00002093 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002094
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002095 // We need to build the initializer AST according to order of construction
2096 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002097 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002098 if (!ClassDecl)
2099 return true;
2100
Eli Friedman80c30da2009-11-09 19:20:36 +00002101 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002103 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002104 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002105
2106 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002107 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002108 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002109 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002110 }
2111
Anders Carlsson711f34a2010-04-21 19:52:01 +00002112 // Keep track of the direct virtual bases.
2113 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2114 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2115 E = ClassDecl->bases_end(); I != E; ++I) {
2116 if (I->isVirtual())
2117 DirectVBases.insert(I);
2118 }
2119
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002120 // Push virtual bases before others.
2121 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2122 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2123
Sean Huntcbb67482011-01-08 20:30:50 +00002124 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002125 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2126 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002127 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002128 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002129 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002130 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002131 VBase, IsInheritedVirtualBase,
2132 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002133 HadError = true;
2134 continue;
2135 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002136
John McCallf1860e52010-05-20 23:23:51 +00002137 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002138 }
2139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
John McCallf1860e52010-05-20 23:23:51 +00002141 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002142 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2143 E = ClassDecl->bases_end(); Base != E; ++Base) {
2144 // Virtuals are in the virtual base list and already constructed.
2145 if (Base->isVirtual())
2146 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Sean Huntcbb67482011-01-08 20:30:50 +00002148 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002149 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2150 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002151 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002152 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002153 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002154 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002155 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002156 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002157 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002158 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002159
John McCallf1860e52010-05-20 23:23:51 +00002160 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002161 }
2162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
John McCallf1860e52010-05-20 23:23:51 +00002164 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002165 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002166 E = ClassDecl->field_end(); Field != E; ++Field) {
2167 if ((*Field)->getType()->isIncompleteArrayType()) {
2168 assert(ClassDecl->hasFlexibleArrayMember() &&
2169 "Incomplete array type is not valid");
2170 continue;
2171 }
John McCallf1860e52010-05-20 23:23:51 +00002172 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002173 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002174 }
Mike Stump1eb44332009-09-09 15:08:12 +00002175
John McCallf1860e52010-05-20 23:23:51 +00002176 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002177 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002178 Constructor->setNumCtorInitializers(NumInitializers);
2179 CXXCtorInitializer **baseOrMemberInitializers =
2180 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002181 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002182 NumInitializers * sizeof(CXXCtorInitializer*));
2183 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002184
John McCallef027fe2010-03-16 21:39:52 +00002185 // Constructors implicitly reference the base and member
2186 // destructors.
2187 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2188 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002189 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002190
2191 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002192}
2193
Eli Friedman6347f422009-07-21 19:28:10 +00002194static void *GetKeyForTopLevelField(FieldDecl *Field) {
2195 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002196 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002197 if (RT->getDecl()->isAnonymousStructOrUnion())
2198 return static_cast<void *>(RT->getDecl());
2199 }
2200 return static_cast<void *>(Field);
2201}
2202
Anders Carlssonea356fb2010-04-02 05:42:15 +00002203static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002204 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002205}
2206
Anders Carlssonea356fb2010-04-02 05:42:15 +00002207static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002208 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002209 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002210 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002211
Eli Friedman6347f422009-07-21 19:28:10 +00002212 // For fields injected into the class via declaration of an anonymous union,
2213 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002214 FieldDecl *Field = Member->getAnyMember();
2215
John McCall3c3ccdb2010-04-10 09:28:51 +00002216 // If the field is a member of an anonymous struct or union, our key
2217 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002218 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002219 if (RD->isAnonymousStructOrUnion()) {
2220 while (true) {
2221 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2222 if (Parent->isAnonymousStructOrUnion())
2223 RD = Parent;
2224 else
2225 break;
2226 }
2227
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002228 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002231 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002232}
2233
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002234static void
2235DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002236 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002237 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002238 unsigned NumInits) {
2239 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002240 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002242 // Don't check initializers order unless the warning is enabled at the
2243 // location of at least one initializer.
2244 bool ShouldCheckOrder = false;
2245 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002246 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002247 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2248 Init->getSourceLocation())
2249 != Diagnostic::Ignored) {
2250 ShouldCheckOrder = true;
2251 break;
2252 }
2253 }
2254 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002255 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002256
John McCalld6ca8da2010-04-10 07:37:23 +00002257 // Build the list of bases and members in the order that they'll
2258 // actually be initialized. The explicit initializers should be in
2259 // this same order but may be missing things.
2260 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Anders Carlsson071d6102010-04-02 03:38:04 +00002262 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2263
John McCalld6ca8da2010-04-10 07:37:23 +00002264 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002265 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002266 ClassDecl->vbases_begin(),
2267 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002268 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002269
John McCalld6ca8da2010-04-10 07:37:23 +00002270 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002271 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002272 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002273 if (Base->isVirtual())
2274 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002275 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002276 }
Mike Stump1eb44332009-09-09 15:08:12 +00002277
John McCalld6ca8da2010-04-10 07:37:23 +00002278 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002279 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2280 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002281 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002282
John McCalld6ca8da2010-04-10 07:37:23 +00002283 unsigned NumIdealInits = IdealInitKeys.size();
2284 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002285
Sean Huntcbb67482011-01-08 20:30:50 +00002286 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002287 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002288 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002289 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002290
2291 // Scan forward to try to find this initializer in the idealized
2292 // initializers list.
2293 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2294 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002295 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002296
2297 // If we didn't find this initializer, it must be because we
2298 // scanned past it on a previous iteration. That can only
2299 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002300 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002301 Sema::SemaDiagnosticBuilder D =
2302 SemaRef.Diag(PrevInit->getSourceLocation(),
2303 diag::warn_initializer_out_of_order);
2304
Francois Pichet00eb3f92010-12-04 09:14:42 +00002305 if (PrevInit->isAnyMemberInitializer())
2306 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002307 else
2308 D << 1 << PrevInit->getBaseClassInfo()->getType();
2309
Francois Pichet00eb3f92010-12-04 09:14:42 +00002310 if (Init->isAnyMemberInitializer())
2311 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002312 else
2313 D << 1 << Init->getBaseClassInfo()->getType();
2314
2315 // Move back to the initializer's location in the ideal list.
2316 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2317 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002318 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002319
2320 assert(IdealIndex != NumIdealInits &&
2321 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002322 }
John McCalld6ca8da2010-04-10 07:37:23 +00002323
2324 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002325 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002326}
2327
John McCall3c3ccdb2010-04-10 09:28:51 +00002328namespace {
2329bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002330 CXXCtorInitializer *Init,
2331 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002332 if (!PrevInit) {
2333 PrevInit = Init;
2334 return false;
2335 }
2336
2337 if (FieldDecl *Field = Init->getMember())
2338 S.Diag(Init->getSourceLocation(),
2339 diag::err_multiple_mem_initialization)
2340 << Field->getDeclName()
2341 << Init->getSourceRange();
2342 else {
John McCallf4c73712011-01-19 06:33:43 +00002343 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002344 assert(BaseClass && "neither field nor base");
2345 S.Diag(Init->getSourceLocation(),
2346 diag::err_multiple_base_initialization)
2347 << QualType(BaseClass, 0)
2348 << Init->getSourceRange();
2349 }
2350 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2351 << 0 << PrevInit->getSourceRange();
2352
2353 return true;
2354}
2355
Sean Huntcbb67482011-01-08 20:30:50 +00002356typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002357typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2358
2359bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002360 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002361 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002362 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002363 RecordDecl *Parent = Field->getParent();
2364 if (!Parent->isAnonymousStructOrUnion())
2365 return false;
2366
2367 NamedDecl *Child = Field;
2368 do {
2369 if (Parent->isUnion()) {
2370 UnionEntry &En = Unions[Parent];
2371 if (En.first && En.first != Child) {
2372 S.Diag(Init->getSourceLocation(),
2373 diag::err_multiple_mem_union_initialization)
2374 << Field->getDeclName()
2375 << Init->getSourceRange();
2376 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2377 << 0 << En.second->getSourceRange();
2378 return true;
2379 } else if (!En.first) {
2380 En.first = Child;
2381 En.second = Init;
2382 }
2383 }
2384
2385 Child = Parent;
2386 Parent = cast<RecordDecl>(Parent->getDeclContext());
2387 } while (Parent->isAnonymousStructOrUnion());
2388
2389 return false;
2390}
2391}
2392
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002393/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002394void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002395 SourceLocation ColonLoc,
2396 MemInitTy **meminits, unsigned NumMemInits,
2397 bool AnyErrors) {
2398 if (!ConstructorDecl)
2399 return;
2400
2401 AdjustDeclIfTemplate(ConstructorDecl);
2402
2403 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002404 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002405
2406 if (!Constructor) {
2407 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2408 return;
2409 }
2410
Sean Huntcbb67482011-01-08 20:30:50 +00002411 CXXCtorInitializer **MemInits =
2412 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002413
2414 // Mapping for the duplicate initializers check.
2415 // For member initializers, this is keyed with a FieldDecl*.
2416 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002417 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002418
2419 // Mapping for the inconsistent anonymous-union initializers check.
2420 RedundantUnionMap MemberUnions;
2421
Anders Carlssonea356fb2010-04-02 05:42:15 +00002422 bool HadError = false;
2423 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002424 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002425
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002426 // Set the source order index.
2427 Init->setSourceOrder(i);
2428
Francois Pichet00eb3f92010-12-04 09:14:42 +00002429 if (Init->isAnyMemberInitializer()) {
2430 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002431 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2432 CheckRedundantUnionInit(*this, Init, MemberUnions))
2433 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002434 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002435 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2436 if (CheckRedundantInit(*this, Init, Members[Key]))
2437 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002438 } else {
2439 assert(Init->isDelegatingInitializer());
2440 // This must be the only initializer
2441 if (i != 0 || NumMemInits > 1) {
2442 Diag(MemInits[0]->getSourceLocation(),
2443 diag::err_delegating_initializer_alone)
2444 << MemInits[0]->getSourceRange();
2445 HadError = true;
2446 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002447 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002448 }
2449
Anders Carlssonea356fb2010-04-02 05:42:15 +00002450 if (HadError)
2451 return;
2452
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002453 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002454
Sean Huntcbb67482011-01-08 20:30:50 +00002455 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002456}
2457
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002458void
John McCallef027fe2010-03-16 21:39:52 +00002459Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2460 CXXRecordDecl *ClassDecl) {
2461 // Ignore dependent contexts.
2462 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002463 return;
John McCall58e6f342010-03-16 05:22:47 +00002464
2465 // FIXME: all the access-control diagnostics are positioned on the
2466 // field/base declaration. That's probably good; that said, the
2467 // user might reasonably want to know why the destructor is being
2468 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002469
Anders Carlsson9f853df2009-11-17 04:44:12 +00002470 // Non-static data members.
2471 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2472 E = ClassDecl->field_end(); I != E; ++I) {
2473 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002474 if (Field->isInvalidDecl())
2475 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002476 QualType FieldType = Context.getBaseElementType(Field->getType());
2477
2478 const RecordType* RT = FieldType->getAs<RecordType>();
2479 if (!RT)
2480 continue;
2481
2482 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2483 if (FieldClassDecl->hasTrivialDestructor())
2484 continue;
2485
Douglas Gregordb89f282010-07-01 22:47:18 +00002486 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002487 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002488 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002489 << Field->getDeclName()
2490 << FieldType);
2491
John McCallef027fe2010-03-16 21:39:52 +00002492 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002493 }
2494
John McCall58e6f342010-03-16 05:22:47 +00002495 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2496
Anders Carlsson9f853df2009-11-17 04:44:12 +00002497 // Bases.
2498 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2499 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002500 // Bases are always records in a well-formed non-dependent class.
2501 const RecordType *RT = Base->getType()->getAs<RecordType>();
2502
2503 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002504 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002505 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002506
2507 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002508 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002509 if (BaseClassDecl->hasTrivialDestructor())
2510 continue;
John McCall58e6f342010-03-16 05:22:47 +00002511
Douglas Gregordb89f282010-07-01 22:47:18 +00002512 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002513
2514 // FIXME: caret should be on the start of the class name
2515 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002516 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002517 << Base->getType()
2518 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002519
John McCallef027fe2010-03-16 21:39:52 +00002520 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002521 }
2522
2523 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002524 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2525 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002526
2527 // Bases are always records in a well-formed non-dependent class.
2528 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2529
2530 // Ignore direct virtual bases.
2531 if (DirectVirtualBases.count(RT))
2532 continue;
2533
Anders Carlsson9f853df2009-11-17 04:44:12 +00002534 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002535 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002536 if (BaseClassDecl->hasTrivialDestructor())
2537 continue;
John McCall58e6f342010-03-16 05:22:47 +00002538
Douglas Gregordb89f282010-07-01 22:47:18 +00002539 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002540 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002541 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002542 << VBase->getType());
2543
John McCallef027fe2010-03-16 21:39:52 +00002544 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002545 }
2546}
2547
John McCalld226f652010-08-21 09:40:31 +00002548void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002549 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002550 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Mike Stump1eb44332009-09-09 15:08:12 +00002552 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002553 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002554 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002555}
2556
Mike Stump1eb44332009-09-09 15:08:12 +00002557bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002558 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002559 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002560 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002561 else
John McCall94c3b562010-08-18 09:41:07 +00002562 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002563}
2564
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002565bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002566 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002567 if (!getLangOptions().CPlusPlus)
2568 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Anders Carlsson11f21a02009-03-23 19:10:31 +00002570 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002571 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002572
Ted Kremenek6217b802009-07-29 21:53:49 +00002573 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002574 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002575 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002576 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002578 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002579 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Ted Kremenek6217b802009-07-29 21:53:49 +00002582 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002583 if (!RT)
2584 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002585
John McCall86ff3082010-02-04 22:26:26 +00002586 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002587
John McCall94c3b562010-08-18 09:41:07 +00002588 // We can't answer whether something is abstract until it has a
2589 // definition. If it's currently being defined, we'll walk back
2590 // over all the declarations when we have a full definition.
2591 const CXXRecordDecl *Def = RD->getDefinition();
2592 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002593 return false;
2594
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002595 if (!RD->isAbstract())
2596 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002598 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002599 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002600
John McCall94c3b562010-08-18 09:41:07 +00002601 return true;
2602}
2603
2604void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2605 // Check if we've already emitted the list of pure virtual functions
2606 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002607 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002608 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002610 CXXFinalOverriderMap FinalOverriders;
2611 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002613 // Keep a set of seen pure methods so we won't diagnose the same method
2614 // more than once.
2615 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2616
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002617 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2618 MEnd = FinalOverriders.end();
2619 M != MEnd;
2620 ++M) {
2621 for (OverridingMethods::iterator SO = M->second.begin(),
2622 SOEnd = M->second.end();
2623 SO != SOEnd; ++SO) {
2624 // C++ [class.abstract]p4:
2625 // A class is abstract if it contains or inherits at least one
2626 // pure virtual function for which the final overrider is pure
2627 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002629 //
2630 if (SO->second.size() != 1)
2631 continue;
2632
2633 if (!SO->second.front().Method->isPure())
2634 continue;
2635
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002636 if (!SeenPureMethods.insert(SO->second.front().Method))
2637 continue;
2638
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002639 Diag(SO->second.front().Method->getLocation(),
2640 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002641 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002642 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002643 }
2644
2645 if (!PureVirtualClassDiagSet)
2646 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2647 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002648}
2649
Anders Carlsson8211eff2009-03-24 01:19:16 +00002650namespace {
John McCall94c3b562010-08-18 09:41:07 +00002651struct AbstractUsageInfo {
2652 Sema &S;
2653 CXXRecordDecl *Record;
2654 CanQualType AbstractType;
2655 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002656
John McCall94c3b562010-08-18 09:41:07 +00002657 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2658 : S(S), Record(Record),
2659 AbstractType(S.Context.getCanonicalType(
2660 S.Context.getTypeDeclType(Record))),
2661 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002662
John McCall94c3b562010-08-18 09:41:07 +00002663 void DiagnoseAbstractType() {
2664 if (Invalid) return;
2665 S.DiagnoseAbstractType(Record);
2666 Invalid = true;
2667 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002668
John McCall94c3b562010-08-18 09:41:07 +00002669 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2670};
2671
2672struct CheckAbstractUsage {
2673 AbstractUsageInfo &Info;
2674 const NamedDecl *Ctx;
2675
2676 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2677 : Info(Info), Ctx(Ctx) {}
2678
2679 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2680 switch (TL.getTypeLocClass()) {
2681#define ABSTRACT_TYPELOC(CLASS, PARENT)
2682#define TYPELOC(CLASS, PARENT) \
2683 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2684#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002685 }
John McCall94c3b562010-08-18 09:41:07 +00002686 }
Mike Stump1eb44332009-09-09 15:08:12 +00002687
John McCall94c3b562010-08-18 09:41:07 +00002688 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2689 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2690 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002691 if (!TL.getArg(I))
2692 continue;
2693
John McCall94c3b562010-08-18 09:41:07 +00002694 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2695 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002696 }
John McCall94c3b562010-08-18 09:41:07 +00002697 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002698
John McCall94c3b562010-08-18 09:41:07 +00002699 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2700 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2701 }
Mike Stump1eb44332009-09-09 15:08:12 +00002702
John McCall94c3b562010-08-18 09:41:07 +00002703 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2704 // Visit the type parameters from a permissive context.
2705 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2706 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2707 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2708 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2709 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2710 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002711 }
John McCall94c3b562010-08-18 09:41:07 +00002712 }
Mike Stump1eb44332009-09-09 15:08:12 +00002713
John McCall94c3b562010-08-18 09:41:07 +00002714 // Visit pointee types from a permissive context.
2715#define CheckPolymorphic(Type) \
2716 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2717 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2718 }
2719 CheckPolymorphic(PointerTypeLoc)
2720 CheckPolymorphic(ReferenceTypeLoc)
2721 CheckPolymorphic(MemberPointerTypeLoc)
2722 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002723
John McCall94c3b562010-08-18 09:41:07 +00002724 /// Handle all the types we haven't given a more specific
2725 /// implementation for above.
2726 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2727 // Every other kind of type that we haven't called out already
2728 // that has an inner type is either (1) sugar or (2) contains that
2729 // inner type in some way as a subobject.
2730 if (TypeLoc Next = TL.getNextTypeLoc())
2731 return Visit(Next, Sel);
2732
2733 // If there's no inner type and we're in a permissive context,
2734 // don't diagnose.
2735 if (Sel == Sema::AbstractNone) return;
2736
2737 // Check whether the type matches the abstract type.
2738 QualType T = TL.getType();
2739 if (T->isArrayType()) {
2740 Sel = Sema::AbstractArrayType;
2741 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002742 }
John McCall94c3b562010-08-18 09:41:07 +00002743 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2744 if (CT != Info.AbstractType) return;
2745
2746 // It matched; do some magic.
2747 if (Sel == Sema::AbstractArrayType) {
2748 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2749 << T << TL.getSourceRange();
2750 } else {
2751 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2752 << Sel << T << TL.getSourceRange();
2753 }
2754 Info.DiagnoseAbstractType();
2755 }
2756};
2757
2758void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2759 Sema::AbstractDiagSelID Sel) {
2760 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2761}
2762
2763}
2764
2765/// Check for invalid uses of an abstract type in a method declaration.
2766static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2767 CXXMethodDecl *MD) {
2768 // No need to do the check on definitions, which require that
2769 // the return/param types be complete.
2770 if (MD->isThisDeclarationADefinition())
2771 return;
2772
2773 // For safety's sake, just ignore it if we don't have type source
2774 // information. This should never happen for non-implicit methods,
2775 // but...
2776 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2777 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2778}
2779
2780/// Check for invalid uses of an abstract type within a class definition.
2781static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2782 CXXRecordDecl *RD) {
2783 for (CXXRecordDecl::decl_iterator
2784 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2785 Decl *D = *I;
2786 if (D->isImplicit()) continue;
2787
2788 // Methods and method templates.
2789 if (isa<CXXMethodDecl>(D)) {
2790 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2791 } else if (isa<FunctionTemplateDecl>(D)) {
2792 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2793 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2794
2795 // Fields and static variables.
2796 } else if (isa<FieldDecl>(D)) {
2797 FieldDecl *FD = cast<FieldDecl>(D);
2798 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2799 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2800 } else if (isa<VarDecl>(D)) {
2801 VarDecl *VD = cast<VarDecl>(D);
2802 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2803 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2804
2805 // Nested classes and class templates.
2806 } else if (isa<CXXRecordDecl>(D)) {
2807 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2808 } else if (isa<ClassTemplateDecl>(D)) {
2809 CheckAbstractClassUsage(Info,
2810 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2811 }
2812 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002813}
2814
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002815/// \brief Perform semantic checks on a class definition that has been
2816/// completing, introducing implicitly-declared members, checking for
2817/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002818void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002819 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002820 return;
2821
John McCall94c3b562010-08-18 09:41:07 +00002822 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2823 AbstractUsageInfo Info(*this, Record);
2824 CheckAbstractClassUsage(Info, Record);
2825 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002826
2827 // If this is not an aggregate type and has no user-declared constructor,
2828 // complain about any non-static data members of reference or const scalar
2829 // type, since they will never get initializers.
2830 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2831 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2832 bool Complained = false;
2833 for (RecordDecl::field_iterator F = Record->field_begin(),
2834 FEnd = Record->field_end();
2835 F != FEnd; ++F) {
2836 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002837 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002838 if (!Complained) {
2839 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2840 << Record->getTagKind() << Record;
2841 Complained = true;
2842 }
2843
2844 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2845 << F->getType()->isReferenceType()
2846 << F->getDeclName();
2847 }
2848 }
2849 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002850
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002851 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002852 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002853
2854 if (Record->getIdentifier()) {
2855 // C++ [class.mem]p13:
2856 // If T is the name of a class, then each of the following shall have a
2857 // name different from T:
2858 // - every member of every anonymous union that is a member of class T.
2859 //
2860 // C++ [class.mem]p14:
2861 // In addition, if class T has a user-declared constructor (12.1), every
2862 // non-static data member of class T shall have a name different from T.
2863 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002864 R.first != R.second; ++R.first) {
2865 NamedDecl *D = *R.first;
2866 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2867 isa<IndirectFieldDecl>(D)) {
2868 Diag(D->getLocation(), diag::err_member_name_of_class)
2869 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002870 break;
2871 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002872 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002873 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002874
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002875 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002876 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002877 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002878 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002879 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2880 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2881 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002882
2883 // See if a method overloads virtual methods in a base
2884 /// class without overriding any.
2885 if (!Record->isDependentType()) {
2886 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2887 MEnd = Record->method_end();
2888 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002889 if (!(*M)->isStatic())
2890 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002891 }
2892 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002893
2894 // Declare inherited constructors. We do this eagerly here because:
2895 // - The standard requires an eager diagnostic for conflicting inherited
2896 // constructors from different classes.
2897 // - The lazy declaration of the other implicit constructors is so as to not
2898 // waste space and performance on classes that are not meant to be
2899 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2900 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002901 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002902}
2903
2904/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00002905namespace {
2906 struct FindHiddenVirtualMethodData {
2907 Sema *S;
2908 CXXMethodDecl *Method;
2909 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2910 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2911 };
2912}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002913
2914/// \brief Member lookup function that determines whether a given C++
2915/// method overloads virtual methods in a base class without overriding any,
2916/// to be used with CXXRecordDecl::lookupInBases().
2917static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2918 CXXBasePath &Path,
2919 void *UserData) {
2920 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2921
2922 FindHiddenVirtualMethodData &Data
2923 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2924
2925 DeclarationName Name = Data.Method->getDeclName();
2926 assert(Name.getNameKind() == DeclarationName::Identifier);
2927
2928 bool foundSameNameMethod = false;
2929 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2930 for (Path.Decls = BaseRecord->lookup(Name);
2931 Path.Decls.first != Path.Decls.second;
2932 ++Path.Decls.first) {
2933 NamedDecl *D = *Path.Decls.first;
2934 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002935 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002936 foundSameNameMethod = true;
2937 // Interested only in hidden virtual methods.
2938 if (!MD->isVirtual())
2939 continue;
2940 // If the method we are checking overrides a method from its base
2941 // don't warn about the other overloaded methods.
2942 if (!Data.S->IsOverload(Data.Method, MD, false))
2943 return true;
2944 // Collect the overload only if its hidden.
2945 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2946 overloadedMethods.push_back(MD);
2947 }
2948 }
2949
2950 if (foundSameNameMethod)
2951 Data.OverloadedMethods.append(overloadedMethods.begin(),
2952 overloadedMethods.end());
2953 return foundSameNameMethod;
2954}
2955
2956/// \brief See if a method overloads virtual methods in a base class without
2957/// overriding any.
2958void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2959 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2960 MD->getLocation()) == Diagnostic::Ignored)
2961 return;
2962 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2963 return;
2964
2965 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2966 /*bool RecordPaths=*/false,
2967 /*bool DetectVirtual=*/false);
2968 FindHiddenVirtualMethodData Data;
2969 Data.Method = MD;
2970 Data.S = this;
2971
2972 // Keep the base methods that were overriden or introduced in the subclass
2973 // by 'using' in a set. A base method not in this set is hidden.
2974 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2975 res.first != res.second; ++res.first) {
2976 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2977 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2978 E = MD->end_overridden_methods();
2979 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002980 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002981 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2982 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002983 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002984 }
2985
2986 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2987 !Data.OverloadedMethods.empty()) {
2988 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2989 << MD << (Data.OverloadedMethods.size() > 1);
2990
2991 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2992 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2993 Diag(overloadedMD->getLocation(),
2994 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2995 }
2996 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002997}
2998
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002999void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00003000 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003001 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003002 SourceLocation RBrac,
3003 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003004 if (!TagDecl)
3005 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Douglas Gregor42af25f2009-05-11 19:58:34 +00003007 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003008
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003009 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003010 // strict aliasing violation!
3011 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003012 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003013
Douglas Gregor23c94db2010-07-02 17:43:08 +00003014 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003015 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003016}
3017
Douglas Gregord92ec472010-07-01 05:10:53 +00003018namespace {
3019 /// \brief Helper class that collects exception specifications for
3020 /// implicitly-declared special member functions.
3021 class ImplicitExceptionSpecification {
3022 ASTContext &Context;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003023 // We order exception specifications thus:
3024 // noexcept is the most restrictive, but is only used in C++0x.
3025 // throw() comes next.
3026 // Then a throw(collected exceptions)
3027 // Finally no specification.
3028 // throw(...) is used instead if any called function uses it.
3029 ExceptionSpecificationType ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003030 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3031 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003032
3033 void ClearExceptions() {
3034 ExceptionsSeen.clear();
3035 Exceptions.clear();
3036 }
3037
Douglas Gregord92ec472010-07-01 05:10:53 +00003038 public:
3039 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redl60618fa2011-03-12 11:50:43 +00003040 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3041 if (!Context.getLangOptions().CPlusPlus0x)
3042 ComputedEST = EST_DynamicNone;
Douglas Gregord92ec472010-07-01 05:10:53 +00003043 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003044
3045 /// \brief Get the computed exception specification type.
3046 ExceptionSpecificationType getExceptionSpecType() const {
3047 assert(ComputedEST != EST_ComputedNoexcept &&
3048 "noexcept(expr) should not be a possible result");
3049 return ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003050 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003051
Douglas Gregord92ec472010-07-01 05:10:53 +00003052 /// \brief The number of exceptions in the exception specification.
3053 unsigned size() const { return Exceptions.size(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003054
Douglas Gregord92ec472010-07-01 05:10:53 +00003055 /// \brief The set of exceptions in the exception specification.
3056 const QualType *data() const { return Exceptions.data(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003057
3058 /// \brief Integrate another called method into the collected data.
Douglas Gregord92ec472010-07-01 05:10:53 +00003059 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00003060 // If we have an MSAny spec already, don't bother.
3061 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregord92ec472010-07-01 05:10:53 +00003062 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003063
Douglas Gregord92ec472010-07-01 05:10:53 +00003064 const FunctionProtoType *Proto
3065 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003066
3067 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3068
Douglas Gregord92ec472010-07-01 05:10:53 +00003069 // If this function can throw any exceptions, make a note of that.
Sebastian Redl60618fa2011-03-12 11:50:43 +00003070 if (EST == EST_MSAny || EST == EST_None) {
3071 ClearExceptions();
3072 ComputedEST = EST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003073 return;
3074 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003075
3076 // If this function has a basic noexcept, it doesn't affect the outcome.
3077 if (EST == EST_BasicNoexcept)
3078 return;
3079
3080 // If we have a throw-all spec at this point, ignore the function.
3081 if (ComputedEST == EST_None)
3082 return;
3083
3084 // If we're still at noexcept(true) and there's a nothrow() callee,
3085 // change to that specification.
3086 if (EST == EST_DynamicNone) {
3087 if (ComputedEST == EST_BasicNoexcept)
3088 ComputedEST = EST_DynamicNone;
3089 return;
3090 }
3091
3092 // Check out noexcept specs.
3093 if (EST == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003094 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +00003095 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3096 "Must have noexcept result for EST_ComputedNoexcept.");
3097 assert(NR != FunctionProtoType::NR_Dependent &&
3098 "Should not generate implicit declarations for dependent cases, "
3099 "and don't know how to handle them anyway.");
3100
3101 // noexcept(false) -> no spec on the new function
3102 if (NR == FunctionProtoType::NR_Throw) {
3103 ClearExceptions();
3104 ComputedEST = EST_None;
3105 }
3106 // noexcept(true) won't change anything either.
3107 return;
3108 }
3109
3110 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3111 assert(ComputedEST != EST_None &&
3112 "Shouldn't collect exceptions when throw-all is guaranteed.");
3113 ComputedEST = EST_Dynamic;
Douglas Gregord92ec472010-07-01 05:10:53 +00003114 // Record the exceptions in this function's exception specification.
3115 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3116 EEnd = Proto->exception_end();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003117 E != EEnd; ++E)
Douglas Gregord92ec472010-07-01 05:10:53 +00003118 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3119 Exceptions.push_back(*E);
3120 }
3121 };
3122}
3123
3124
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003125/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3126/// special functions, such as the default constructor, copy
3127/// constructor, or destructor, to the given C++ class (C++
3128/// [special]p1). This routine can only be executed just before the
3129/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003130void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003131 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003132 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003133
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003134 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003135 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003136
Douglas Gregora376d102010-07-02 21:50:04 +00003137 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3138 ++ASTContext::NumImplicitCopyAssignmentOperators;
3139
3140 // If we have a dynamic class, then the copy assignment operator may be
3141 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3142 // it shows up in the right place in the vtable and that we diagnose
3143 // problems with the implicit exception specification.
3144 if (ClassDecl->isDynamicClass())
3145 DeclareImplicitCopyAssignment(ClassDecl);
3146 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003147
Douglas Gregor4923aa22010-07-02 20:37:36 +00003148 if (!ClassDecl->hasUserDeclaredDestructor()) {
3149 ++ASTContext::NumImplicitDestructors;
3150
3151 // If we have a dynamic class, then the destructor may be virtual, so we
3152 // have to declare the destructor immediately. This ensures that, e.g., it
3153 // shows up in the right place in the vtable and that we diagnose problems
3154 // with the implicit exception specification.
3155 if (ClassDecl->isDynamicClass())
3156 DeclareImplicitDestructor(ClassDecl);
3157 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003158}
3159
John McCalld226f652010-08-21 09:40:31 +00003160void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003161 if (!D)
3162 return;
3163
3164 TemplateParameterList *Params = 0;
3165 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3166 Params = Template->getTemplateParameters();
3167 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3168 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3169 Params = PartialSpec->getTemplateParameters();
3170 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003171 return;
3172
Douglas Gregor6569d682009-05-27 23:11:45 +00003173 for (TemplateParameterList::iterator Param = Params->begin(),
3174 ParamEnd = Params->end();
3175 Param != ParamEnd; ++Param) {
3176 NamedDecl *Named = cast<NamedDecl>(*Param);
3177 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003178 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003179 IdResolver.AddDecl(Named);
3180 }
3181 }
3182}
3183
John McCalld226f652010-08-21 09:40:31 +00003184void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003185 if (!RecordD) return;
3186 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003187 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003188 PushDeclContext(S, Record);
3189}
3190
John McCalld226f652010-08-21 09:40:31 +00003191void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003192 if (!RecordD) return;
3193 PopDeclContext();
3194}
3195
Douglas Gregor72b505b2008-12-16 21:30:33 +00003196/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3197/// parsing a top-level (non-nested) C++ class, and we are now
3198/// parsing those parts of the given Method declaration that could
3199/// not be parsed earlier (C++ [class.mem]p2), such as default
3200/// arguments. This action should enter the scope of the given
3201/// Method declaration as if we had just parsed the qualified method
3202/// name. However, it should not bring the parameters into scope;
3203/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003204void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003205}
3206
3207/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3208/// C++ method declaration. We're (re-)introducing the given
3209/// function parameter into scope for use in parsing later parts of
3210/// the method declaration. For example, we could see an
3211/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003212void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003213 if (!ParamD)
3214 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003215
John McCalld226f652010-08-21 09:40:31 +00003216 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003217
3218 // If this parameter has an unparsed default argument, clear it out
3219 // to make way for the parsed default argument.
3220 if (Param->hasUnparsedDefaultArg())
3221 Param->setDefaultArg(0);
3222
John McCalld226f652010-08-21 09:40:31 +00003223 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003224 if (Param->getDeclName())
3225 IdResolver.AddDecl(Param);
3226}
3227
3228/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3229/// processing the delayed method declaration for Method. The method
3230/// declaration is now considered finished. There may be a separate
3231/// ActOnStartOfFunctionDef action later (not necessarily
3232/// immediately!) for this method, if it was also defined inside the
3233/// class body.
John McCalld226f652010-08-21 09:40:31 +00003234void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003235 if (!MethodD)
3236 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003238 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003239
John McCalld226f652010-08-21 09:40:31 +00003240 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003241
3242 // Now that we have our default arguments, check the constructor
3243 // again. It could produce additional diagnostics or affect whether
3244 // the class has implicitly-declared destructors, among other
3245 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003246 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3247 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003248
3249 // Check the default arguments, which we may have added.
3250 if (!Method->isInvalidDecl())
3251 CheckCXXDefaultArguments(Method);
3252}
3253
Douglas Gregor42a552f2008-11-05 20:51:48 +00003254/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003255/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003256/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003257/// emit diagnostics and set the invalid bit to true. In any case, the type
3258/// will be updated to reflect a well-formed type for the constructor and
3259/// returned.
3260QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003261 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003262 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003263
3264 // C++ [class.ctor]p3:
3265 // A constructor shall not be virtual (10.3) or static (9.4). A
3266 // constructor can be invoked for a const, volatile or const
3267 // volatile object. A constructor shall not be declared const,
3268 // volatile, or const volatile (9.3.2).
3269 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003270 if (!D.isInvalidType())
3271 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3272 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3273 << SourceRange(D.getIdentifierLoc());
3274 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003275 }
John McCalld931b082010-08-26 03:08:43 +00003276 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003277 if (!D.isInvalidType())
3278 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3279 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3280 << SourceRange(D.getIdentifierLoc());
3281 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003282 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003283 }
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003285 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003286 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003287 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003288 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3289 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003290 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003291 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3292 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003293 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003294 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3295 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003296 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003297 }
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Douglas Gregorc938c162011-01-26 05:01:58 +00003299 // C++0x [class.ctor]p4:
3300 // A constructor shall not be declared with a ref-qualifier.
3301 if (FTI.hasRefQualifier()) {
3302 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3303 << FTI.RefQualifierIsLValueRef
3304 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3305 D.setInvalidType();
3306 }
3307
Douglas Gregor42a552f2008-11-05 20:51:48 +00003308 // Rebuild the function type "R" without any type qualifiers (in
3309 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003310 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003311 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003312 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3313 return R;
3314
3315 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3316 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003317 EPI.RefQualifier = RQ_None;
3318
Chris Lattner65401802009-04-25 08:28:21 +00003319 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003320 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003321}
3322
Douglas Gregor72b505b2008-12-16 21:30:33 +00003323/// CheckConstructor - Checks a fully-formed constructor for
3324/// well-formedness, issuing any diagnostics required. Returns true if
3325/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003326void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003327 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003328 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3329 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003330 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003331
3332 // C++ [class.copy]p3:
3333 // A declaration of a constructor for a class X is ill-formed if
3334 // its first parameter is of type (optionally cv-qualified) X and
3335 // either there are no other parameters or else all other
3336 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003337 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003338 ((Constructor->getNumParams() == 1) ||
3339 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003340 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3341 Constructor->getTemplateSpecializationKind()
3342 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003343 QualType ParamType = Constructor->getParamDecl(0)->getType();
3344 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3345 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003346 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003347 const char *ConstRef
3348 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3349 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003350 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003351 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003352
3353 // FIXME: Rather that making the constructor invalid, we should endeavor
3354 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003355 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003356 }
3357 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003358}
3359
John McCall15442822010-08-04 01:04:25 +00003360/// CheckDestructor - Checks a fully-formed destructor definition for
3361/// well-formedness, issuing any diagnostics required. Returns true
3362/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003363bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003364 CXXRecordDecl *RD = Destructor->getParent();
3365
3366 if (Destructor->isVirtual()) {
3367 SourceLocation Loc;
3368
3369 if (!Destructor->isImplicit())
3370 Loc = Destructor->getLocation();
3371 else
3372 Loc = RD->getLocation();
3373
3374 // If we have a virtual destructor, look up the deallocation function
3375 FunctionDecl *OperatorDelete = 0;
3376 DeclarationName Name =
3377 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003378 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003379 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003380
3381 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003382
3383 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003384 }
Anders Carlsson37909802009-11-30 21:24:50 +00003385
3386 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003387}
3388
Mike Stump1eb44332009-09-09 15:08:12 +00003389static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003390FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3391 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3392 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003393 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003394}
3395
Douglas Gregor42a552f2008-11-05 20:51:48 +00003396/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3397/// the well-formednes of the destructor declarator @p D with type @p
3398/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003399/// emit diagnostics and set the declarator to invalid. Even if this happens,
3400/// will be updated to reflect a well-formed type for the destructor and
3401/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003402QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003403 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003404 // C++ [class.dtor]p1:
3405 // [...] A typedef-name that names a class is a class-name
3406 // (7.1.3); however, a typedef-name that names a class shall not
3407 // be used as the identifier in the declarator for a destructor
3408 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003409 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003410 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003411 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003412 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003413
3414 // C++ [class.dtor]p2:
3415 // A destructor is used to destroy objects of its class type. A
3416 // destructor takes no parameters, and no return type can be
3417 // specified for it (not even void). The address of a destructor
3418 // shall not be taken. A destructor shall not be static. A
3419 // destructor can be invoked for a const, volatile or const
3420 // volatile object. A destructor shall not be declared const,
3421 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003422 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003423 if (!D.isInvalidType())
3424 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3425 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003426 << SourceRange(D.getIdentifierLoc())
3427 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3428
John McCalld931b082010-08-26 03:08:43 +00003429 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003430 }
Chris Lattner65401802009-04-25 08:28:21 +00003431 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003432 // Destructors don't have return types, but the parser will
3433 // happily parse something like:
3434 //
3435 // class X {
3436 // float ~X();
3437 // };
3438 //
3439 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003440 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3441 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3442 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003443 }
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003445 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003446 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003447 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003448 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3449 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003450 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003451 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3452 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003453 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003454 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3455 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003456 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003457 }
3458
Douglas Gregorc938c162011-01-26 05:01:58 +00003459 // C++0x [class.dtor]p2:
3460 // A destructor shall not be declared with a ref-qualifier.
3461 if (FTI.hasRefQualifier()) {
3462 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3463 << FTI.RefQualifierIsLValueRef
3464 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3465 D.setInvalidType();
3466 }
3467
Douglas Gregor42a552f2008-11-05 20:51:48 +00003468 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003469 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003470 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3471
3472 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003473 FTI.freeArgs();
3474 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003475 }
3476
Mike Stump1eb44332009-09-09 15:08:12 +00003477 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003478 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003479 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003480 D.setInvalidType();
3481 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003482
3483 // Rebuild the function type "R" without any type qualifiers or
3484 // parameters (in case any of the errors above fired) and with
3485 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003486 // types.
John McCalle23cf432010-12-14 08:05:40 +00003487 if (!D.isInvalidType())
3488 return R;
3489
Douglas Gregord92ec472010-07-01 05:10:53 +00003490 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003491 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3492 EPI.Variadic = false;
3493 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003494 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003495 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003496}
3497
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003498/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3499/// well-formednes of the conversion function declarator @p D with
3500/// type @p R. If there are any errors in the declarator, this routine
3501/// will emit diagnostics and return true. Otherwise, it will return
3502/// false. Either way, the type @p R will be updated to reflect a
3503/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003504void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003505 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003506 // C++ [class.conv.fct]p1:
3507 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003508 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003509 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003510 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003511 if (!D.isInvalidType())
3512 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3513 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3514 << SourceRange(D.getIdentifierLoc());
3515 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003516 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003517 }
John McCalla3f81372010-04-13 00:04:31 +00003518
3519 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3520
Chris Lattner6e475012009-04-25 08:35:12 +00003521 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003522 // Conversion functions don't have return types, but the parser will
3523 // happily parse something like:
3524 //
3525 // class X {
3526 // float operator bool();
3527 // };
3528 //
3529 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003530 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3531 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3532 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003533 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003534 }
3535
John McCalla3f81372010-04-13 00:04:31 +00003536 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3537
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003538 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003539 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003540 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3541
3542 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003543 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003544 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003545 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003546 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003547 D.setInvalidType();
3548 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003549
John McCalla3f81372010-04-13 00:04:31 +00003550 // Diagnose "&operator bool()" and other such nonsense. This
3551 // is actually a gcc extension which we don't support.
3552 if (Proto->getResultType() != ConvType) {
3553 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3554 << Proto->getResultType();
3555 D.setInvalidType();
3556 ConvType = Proto->getResultType();
3557 }
3558
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003559 // C++ [class.conv.fct]p4:
3560 // The conversion-type-id shall not represent a function type nor
3561 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003562 if (ConvType->isArrayType()) {
3563 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3564 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003565 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003566 } else if (ConvType->isFunctionType()) {
3567 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3568 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003569 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003570 }
3571
3572 // Rebuild the function type "R" without any parameters (in case any
3573 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003574 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003575 if (D.isInvalidType())
3576 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003577
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003578 // C++0x explicit conversion operators.
3579 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003580 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003581 diag::warn_explicit_conversion_functions)
3582 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003583}
3584
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003585/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3586/// the declaration of the given C++ conversion function. This routine
3587/// is responsible for recording the conversion function in the C++
3588/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003589Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003590 assert(Conversion && "Expected to receive a conversion function declaration");
3591
Douglas Gregor9d350972008-12-12 08:25:50 +00003592 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003593
3594 // Make sure we aren't redeclaring the conversion function.
3595 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003596
3597 // C++ [class.conv.fct]p1:
3598 // [...] A conversion function is never used to convert a
3599 // (possibly cv-qualified) object to the (possibly cv-qualified)
3600 // same object type (or a reference to it), to a (possibly
3601 // cv-qualified) base class of that type (or a reference to it),
3602 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003603 // FIXME: Suppress this warning if the conversion function ends up being a
3604 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003605 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003606 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003607 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003608 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003609 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3610 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003611 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003612 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003613 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3614 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003615 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003616 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003617 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003618 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003619 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003620 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003621 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003622 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003623 }
3624
Douglas Gregore80622f2010-09-29 04:25:11 +00003625 if (FunctionTemplateDecl *ConversionTemplate
3626 = Conversion->getDescribedFunctionTemplate())
3627 return ConversionTemplate;
3628
John McCalld226f652010-08-21 09:40:31 +00003629 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003630}
3631
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003632//===----------------------------------------------------------------------===//
3633// Namespace Handling
3634//===----------------------------------------------------------------------===//
3635
John McCallea318642010-08-26 09:15:37 +00003636
3637
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003638/// ActOnStartNamespaceDef - This is called at the start of a namespace
3639/// definition.
John McCalld226f652010-08-21 09:40:31 +00003640Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003641 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003642 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00003643 SourceLocation IdentLoc,
3644 IdentifierInfo *II,
3645 SourceLocation LBrace,
3646 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003647 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3648 // For anonymous namespace, take the location of the left brace.
3649 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00003650 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003651 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003652 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003653
3654 Scope *DeclRegionScope = NamespcScope->getParent();
3655
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003656 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3657
John McCall90f14502010-12-10 02:59:44 +00003658 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3659 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003660
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003661 if (II) {
3662 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003663 // The identifier in an original-namespace-definition shall not
3664 // have been previously defined in the declarative region in
3665 // which the original-namespace-definition appears. The
3666 // identifier in an original-namespace-definition is the name of
3667 // the namespace. Subsequently in that declarative region, it is
3668 // treated as an original-namespace-name.
3669 //
3670 // Since namespace names are unique in their scope, and we don't
3671 // look through using directives, just
3672 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3673 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Douglas Gregor44b43212008-12-11 16:49:14 +00003675 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3676 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003677 if (Namespc->isInline() != OrigNS->isInline()) {
3678 // inline-ness must match
3679 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3680 << Namespc->isInline();
3681 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3682 Namespc->setInvalidDecl();
3683 // Recover by ignoring the new namespace's inline status.
3684 Namespc->setInline(OrigNS->isInline());
3685 }
3686
Douglas Gregor44b43212008-12-11 16:49:14 +00003687 // Attach this namespace decl to the chain of extended namespace
3688 // definitions.
3689 OrigNS->setNextNamespace(Namespc);
3690 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003691
Mike Stump1eb44332009-09-09 15:08:12 +00003692 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003693 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003694 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003695 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003696 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003697 } else if (PrevDecl) {
3698 // This is an invalid name redefinition.
3699 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3700 << Namespc->getDeclName();
3701 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3702 Namespc->setInvalidDecl();
3703 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003704 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003705 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003706 // This is the first "real" definition of the namespace "std", so update
3707 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003708 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003709 // We had already defined a dummy namespace "std". Link this new
3710 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003711 StdNS->setNextNamespace(Namespc);
3712 StdNS->setLocation(IdentLoc);
3713 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003714 }
3715
3716 // Make our StdNamespace cache point at the first real definition of the
3717 // "std" namespace.
3718 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003719 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003720
3721 PushOnScopeChains(Namespc, DeclRegionScope);
3722 } else {
John McCall9aeed322009-10-01 00:25:31 +00003723 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003724 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003725
3726 // Link the anonymous namespace into its parent.
3727 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003728 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003729 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3730 PrevDecl = TU->getAnonymousNamespace();
3731 TU->setAnonymousNamespace(Namespc);
3732 } else {
3733 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3734 PrevDecl = ND->getAnonymousNamespace();
3735 ND->setAnonymousNamespace(Namespc);
3736 }
3737
3738 // Link the anonymous namespace with its previous declaration.
3739 if (PrevDecl) {
3740 assert(PrevDecl->isAnonymousNamespace());
3741 assert(!PrevDecl->getNextNamespace());
3742 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3743 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003744
3745 if (Namespc->isInline() != PrevDecl->isInline()) {
3746 // inline-ness must match
3747 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3748 << Namespc->isInline();
3749 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3750 Namespc->setInvalidDecl();
3751 // Recover by ignoring the new namespace's inline status.
3752 Namespc->setInline(PrevDecl->isInline());
3753 }
John McCall5fdd7642009-12-16 02:06:49 +00003754 }
John McCall9aeed322009-10-01 00:25:31 +00003755
Douglas Gregora4181472010-03-24 00:46:35 +00003756 CurContext->addDecl(Namespc);
3757
John McCall9aeed322009-10-01 00:25:31 +00003758 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3759 // behaves as if it were replaced by
3760 // namespace unique { /* empty body */ }
3761 // using namespace unique;
3762 // namespace unique { namespace-body }
3763 // where all occurrences of 'unique' in a translation unit are
3764 // replaced by the same identifier and this identifier differs
3765 // from all other identifiers in the entire program.
3766
3767 // We just create the namespace with an empty name and then add an
3768 // implicit using declaration, just like the standard suggests.
3769 //
3770 // CodeGen enforces the "universally unique" aspect by giving all
3771 // declarations semantically contained within an anonymous
3772 // namespace internal linkage.
3773
John McCall5fdd7642009-12-16 02:06:49 +00003774 if (!PrevDecl) {
3775 UsingDirectiveDecl* UD
3776 = UsingDirectiveDecl::Create(Context, CurContext,
3777 /* 'using' */ LBrace,
3778 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00003779 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00003780 /* identifier */ SourceLocation(),
3781 Namespc,
3782 /* Ancestor */ CurContext);
3783 UD->setImplicit();
3784 CurContext->addDecl(UD);
3785 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003786 }
3787
3788 // Although we could have an invalid decl (i.e. the namespace name is a
3789 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003790 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3791 // for the namespace has the declarations that showed up in that particular
3792 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003793 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003794 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003795}
3796
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003797/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3798/// is a namespace alias, returns the namespace it points to.
3799static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3800 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3801 return AD->getNamespace();
3802 return dyn_cast_or_null<NamespaceDecl>(D);
3803}
3804
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003805/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3806/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003807void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003808 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3809 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003810 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003811 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003812 if (Namespc->hasAttr<VisibilityAttr>())
3813 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003814}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003815
John McCall384aff82010-08-25 07:42:41 +00003816CXXRecordDecl *Sema::getStdBadAlloc() const {
3817 return cast_or_null<CXXRecordDecl>(
3818 StdBadAlloc.get(Context.getExternalSource()));
3819}
3820
3821NamespaceDecl *Sema::getStdNamespace() const {
3822 return cast_or_null<NamespaceDecl>(
3823 StdNamespace.get(Context.getExternalSource()));
3824}
3825
Douglas Gregor66992202010-06-29 17:53:46 +00003826/// \brief Retrieve the special "std" namespace, which may require us to
3827/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003828NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003829 if (!StdNamespace) {
3830 // The "std" namespace has not yet been defined, so build one implicitly.
3831 StdNamespace = NamespaceDecl::Create(Context,
3832 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003833 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00003834 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003835 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003836 }
3837
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003838 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003839}
3840
John McCalld226f652010-08-21 09:40:31 +00003841Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003842 SourceLocation UsingLoc,
3843 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003844 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003845 SourceLocation IdentLoc,
3846 IdentifierInfo *NamespcName,
3847 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003848 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3849 assert(NamespcName && "Invalid NamespcName.");
3850 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003851
3852 // This can only happen along a recovery path.
3853 while (S->getFlags() & Scope::TemplateParamScope)
3854 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003855 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003856
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003857 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003858 NestedNameSpecifier *Qualifier = 0;
3859 if (SS.isSet())
3860 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3861
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003862 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003863 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3864 LookupParsedName(R, S, &SS);
3865 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003866 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003867
Douglas Gregor66992202010-06-29 17:53:46 +00003868 if (R.empty()) {
3869 // Allow "using namespace std;" or "using namespace ::std;" even if
3870 // "std" hasn't been defined yet, for GCC compatibility.
3871 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3872 NamespcName->isStr("std")) {
3873 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003874 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003875 R.resolveKind();
3876 }
3877 // Otherwise, attempt typo correction.
3878 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3879 CTC_NoKeywords, 0)) {
3880 if (R.getAsSingle<NamespaceDecl>() ||
3881 R.getAsSingle<NamespaceAliasDecl>()) {
3882 if (DeclContext *DC = computeDeclContext(SS, false))
3883 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3884 << NamespcName << DC << Corrected << SS.getRange()
3885 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3886 else
3887 Diag(IdentLoc, diag::err_using_directive_suggest)
3888 << NamespcName << Corrected
3889 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3890 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3891 << Corrected;
3892
3893 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003894 } else {
3895 R.clear();
3896 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003897 }
3898 }
3899 }
3900
John McCallf36e02d2009-10-09 21:13:30 +00003901 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003902 NamedDecl *Named = R.getFoundDecl();
3903 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3904 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003905 // C++ [namespace.udir]p1:
3906 // A using-directive specifies that the names in the nominated
3907 // namespace can be used in the scope in which the
3908 // using-directive appears after the using-directive. During
3909 // unqualified name lookup (3.4.1), the names appear as if they
3910 // were declared in the nearest enclosing namespace which
3911 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003912 // namespace. [Note: in this context, "contains" means "contains
3913 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003914
3915 // Find enclosing context containing both using-directive and
3916 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003917 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003918 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3919 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3920 CommonAncestor = CommonAncestor->getParent();
3921
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003922 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00003923 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003924 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003925
3926 if (CurContext->getDeclKind() == Decl::TranslationUnit &&
3927 !SourceMgr.isFromMainFile(IdentLoc)) {
3928 Diag(IdentLoc, diag::warn_using_directive_in_header);
3929 }
3930
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003931 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003932 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003933 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003934 }
3935
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003936 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003937 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003938}
3939
3940void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3941 // If scope has associated entity, then using directive is at namespace
3942 // or translation unit scope. We add UsingDirectiveDecls, into
3943 // it's lookup structure.
3944 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003945 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003946 else
3947 // Otherwise it is block-sope. using-directives will affect lookup
3948 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003949 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003950}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003951
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003952
John McCalld226f652010-08-21 09:40:31 +00003953Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003954 AccessSpecifier AS,
3955 bool HasUsingKeyword,
3956 SourceLocation UsingLoc,
3957 CXXScopeSpec &SS,
3958 UnqualifiedId &Name,
3959 AttributeList *AttrList,
3960 bool IsTypeName,
3961 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003962 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Douglas Gregor12c118a2009-11-04 16:30:06 +00003964 switch (Name.getKind()) {
3965 case UnqualifiedId::IK_Identifier:
3966 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003967 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003968 case UnqualifiedId::IK_ConversionFunctionId:
3969 break;
3970
3971 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003972 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003973 // C++0x inherited constructors.
3974 if (getLangOptions().CPlusPlus0x) break;
3975
Douglas Gregor12c118a2009-11-04 16:30:06 +00003976 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3977 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003978 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003979
3980 case UnqualifiedId::IK_DestructorName:
3981 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3982 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003983 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003984
3985 case UnqualifiedId::IK_TemplateId:
3986 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3987 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003988 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003989 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003990
3991 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3992 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003993 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003994 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003995
John McCall60fa3cf2009-12-11 02:10:03 +00003996 // Warn about using declarations.
3997 // TODO: store that the declaration was written without 'using' and
3998 // talk about access decls instead of using decls in the
3999 // diagnostics.
4000 if (!HasUsingKeyword) {
4001 UsingLoc = Name.getSourceRange().getBegin();
4002
4003 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004004 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004005 }
4006
Douglas Gregor56c04582010-12-16 00:46:58 +00004007 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4008 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4009 return 0;
4010
John McCall9488ea12009-11-17 05:59:44 +00004011 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004012 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004013 /* IsInstantiation */ false,
4014 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004015 if (UD)
4016 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
John McCalld226f652010-08-21 09:40:31 +00004018 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004019}
4020
Douglas Gregor09acc982010-07-07 23:08:52 +00004021/// \brief Determine whether a using declaration considers the given
4022/// declarations as "equivalent", e.g., if they are redeclarations of
4023/// the same entity or are both typedefs of the same type.
4024static bool
4025IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4026 bool &SuppressRedeclaration) {
4027 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4028 SuppressRedeclaration = false;
4029 return true;
4030 }
4031
4032 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
4033 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
4034 SuppressRedeclaration = true;
4035 return Context.hasSameType(TD1->getUnderlyingType(),
4036 TD2->getUnderlyingType());
4037 }
4038
4039 return false;
4040}
4041
4042
John McCall9f54ad42009-12-10 09:41:52 +00004043/// Determines whether to create a using shadow decl for a particular
4044/// decl, given the set of decls existing prior to this using lookup.
4045bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4046 const LookupResult &Previous) {
4047 // Diagnose finding a decl which is not from a base class of the
4048 // current class. We do this now because there are cases where this
4049 // function will silently decide not to build a shadow decl, which
4050 // will pre-empt further diagnostics.
4051 //
4052 // We don't need to do this in C++0x because we do the check once on
4053 // the qualifier.
4054 //
4055 // FIXME: diagnose the following if we care enough:
4056 // struct A { int foo; };
4057 // struct B : A { using A::foo; };
4058 // template <class T> struct C : A {};
4059 // template <class T> struct D : C<T> { using B::foo; } // <---
4060 // This is invalid (during instantiation) in C++03 because B::foo
4061 // resolves to the using decl in B, which is not a base class of D<T>.
4062 // We can't diagnose it immediately because C<T> is an unknown
4063 // specialization. The UsingShadowDecl in D<T> then points directly
4064 // to A::foo, which will look well-formed when we instantiate.
4065 // The right solution is to not collapse the shadow-decl chain.
4066 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4067 DeclContext *OrigDC = Orig->getDeclContext();
4068
4069 // Handle enums and anonymous structs.
4070 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4071 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4072 while (OrigRec->isAnonymousStructOrUnion())
4073 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4074
4075 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4076 if (OrigDC == CurContext) {
4077 Diag(Using->getLocation(),
4078 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004079 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004080 Diag(Orig->getLocation(), diag::note_using_decl_target);
4081 return true;
4082 }
4083
Douglas Gregordc355712011-02-25 00:36:19 +00004084 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004085 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004086 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004087 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004088 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004089 Diag(Orig->getLocation(), diag::note_using_decl_target);
4090 return true;
4091 }
4092 }
4093
4094 if (Previous.empty()) return false;
4095
4096 NamedDecl *Target = Orig;
4097 if (isa<UsingShadowDecl>(Target))
4098 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4099
John McCalld7533ec2009-12-11 02:33:26 +00004100 // If the target happens to be one of the previous declarations, we
4101 // don't have a conflict.
4102 //
4103 // FIXME: but we might be increasing its access, in which case we
4104 // should redeclare it.
4105 NamedDecl *NonTag = 0, *Tag = 0;
4106 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4107 I != E; ++I) {
4108 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004109 bool Result;
4110 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4111 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004112
4113 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4114 }
4115
John McCall9f54ad42009-12-10 09:41:52 +00004116 if (Target->isFunctionOrFunctionTemplate()) {
4117 FunctionDecl *FD;
4118 if (isa<FunctionTemplateDecl>(Target))
4119 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4120 else
4121 FD = cast<FunctionDecl>(Target);
4122
4123 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004124 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004125 case Ovl_Overload:
4126 return false;
4127
4128 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004129 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004130 break;
4131
4132 // We found a decl with the exact signature.
4133 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004134 // If we're in a record, we want to hide the target, so we
4135 // return true (without a diagnostic) to tell the caller not to
4136 // build a shadow decl.
4137 if (CurContext->isRecord())
4138 return true;
4139
4140 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004141 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004142 break;
4143 }
4144
4145 Diag(Target->getLocation(), diag::note_using_decl_target);
4146 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4147 return true;
4148 }
4149
4150 // Target is not a function.
4151
John McCall9f54ad42009-12-10 09:41:52 +00004152 if (isa<TagDecl>(Target)) {
4153 // No conflict between a tag and a non-tag.
4154 if (!Tag) return false;
4155
John McCall41ce66f2009-12-10 19:51:03 +00004156 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004157 Diag(Target->getLocation(), diag::note_using_decl_target);
4158 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4159 return true;
4160 }
4161
4162 // No conflict between a tag and a non-tag.
4163 if (!NonTag) return false;
4164
John McCall41ce66f2009-12-10 19:51:03 +00004165 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004166 Diag(Target->getLocation(), diag::note_using_decl_target);
4167 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4168 return true;
4169}
4170
John McCall9488ea12009-11-17 05:59:44 +00004171/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004172UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004173 UsingDecl *UD,
4174 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004175
4176 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004177 NamedDecl *Target = Orig;
4178 if (isa<UsingShadowDecl>(Target)) {
4179 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4180 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004181 }
4182
4183 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004184 = UsingShadowDecl::Create(Context, CurContext,
4185 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004186 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004187
4188 Shadow->setAccess(UD->getAccess());
4189 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4190 Shadow->setInvalidDecl();
4191
John McCall9488ea12009-11-17 05:59:44 +00004192 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004193 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004194 else
John McCall604e7f12009-12-08 07:46:18 +00004195 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004196
John McCall604e7f12009-12-08 07:46:18 +00004197
John McCall9f54ad42009-12-10 09:41:52 +00004198 return Shadow;
4199}
John McCall604e7f12009-12-08 07:46:18 +00004200
John McCall9f54ad42009-12-10 09:41:52 +00004201/// Hides a using shadow declaration. This is required by the current
4202/// using-decl implementation when a resolvable using declaration in a
4203/// class is followed by a declaration which would hide or override
4204/// one or more of the using decl's targets; for example:
4205///
4206/// struct Base { void foo(int); };
4207/// struct Derived : Base {
4208/// using Base::foo;
4209/// void foo(int);
4210/// };
4211///
4212/// The governing language is C++03 [namespace.udecl]p12:
4213///
4214/// When a using-declaration brings names from a base class into a
4215/// derived class scope, member functions in the derived class
4216/// override and/or hide member functions with the same name and
4217/// parameter types in a base class (rather than conflicting).
4218///
4219/// There are two ways to implement this:
4220/// (1) optimistically create shadow decls when they're not hidden
4221/// by existing declarations, or
4222/// (2) don't create any shadow decls (or at least don't make them
4223/// visible) until we've fully parsed/instantiated the class.
4224/// The problem with (1) is that we might have to retroactively remove
4225/// a shadow decl, which requires several O(n) operations because the
4226/// decl structures are (very reasonably) not designed for removal.
4227/// (2) avoids this but is very fiddly and phase-dependent.
4228void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004229 if (Shadow->getDeclName().getNameKind() ==
4230 DeclarationName::CXXConversionFunctionName)
4231 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4232
John McCall9f54ad42009-12-10 09:41:52 +00004233 // Remove it from the DeclContext...
4234 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004235
John McCall9f54ad42009-12-10 09:41:52 +00004236 // ...and the scope, if applicable...
4237 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004238 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004239 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004240 }
4241
John McCall9f54ad42009-12-10 09:41:52 +00004242 // ...and the using decl.
4243 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4244
4245 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004246 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004247}
4248
John McCall7ba107a2009-11-18 02:36:19 +00004249/// Builds a using declaration.
4250///
4251/// \param IsInstantiation - Whether this call arises from an
4252/// instantiation of an unresolved using declaration. We treat
4253/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004254NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4255 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004256 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004257 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004258 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004259 bool IsInstantiation,
4260 bool IsTypeName,
4261 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004262 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004263 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004264 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004265
Anders Carlsson550b14b2009-08-28 05:49:21 +00004266 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004268 if (SS.isEmpty()) {
4269 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004270 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004271 }
Mike Stump1eb44332009-09-09 15:08:12 +00004272
John McCall9f54ad42009-12-10 09:41:52 +00004273 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004274 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004275 ForRedeclaration);
4276 Previous.setHideTags(false);
4277 if (S) {
4278 LookupName(Previous, S);
4279
4280 // It is really dumb that we have to do this.
4281 LookupResult::Filter F = Previous.makeFilter();
4282 while (F.hasNext()) {
4283 NamedDecl *D = F.next();
4284 if (!isDeclInScope(D, CurContext, S))
4285 F.erase();
4286 }
4287 F.done();
4288 } else {
4289 assert(IsInstantiation && "no scope in non-instantiation");
4290 assert(CurContext->isRecord() && "scope not record in instantiation");
4291 LookupQualifiedName(Previous, CurContext);
4292 }
4293
John McCall9f54ad42009-12-10 09:41:52 +00004294 // Check for invalid redeclarations.
4295 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4296 return 0;
4297
4298 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004299 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4300 return 0;
4301
John McCallaf8e6ed2009-11-12 03:15:40 +00004302 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004303 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004304 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004305 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004306 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004307 // FIXME: not all declaration name kinds are legal here
4308 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4309 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004310 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004311 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004312 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004313 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4314 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004315 }
John McCalled976492009-12-04 22:46:56 +00004316 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004317 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4318 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004319 }
John McCalled976492009-12-04 22:46:56 +00004320 D->setAccess(AS);
4321 CurContext->addDecl(D);
4322
4323 if (!LookupContext) return D;
4324 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004325
John McCall77bb1aa2010-05-01 00:40:08 +00004326 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004327 UD->setInvalidDecl();
4328 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004329 }
4330
Sebastian Redlf677ea32011-02-05 19:23:19 +00004331 // Constructor inheriting using decls get special treatment.
4332 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004333 if (CheckInheritedConstructorUsingDecl(UD))
4334 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004335 return UD;
4336 }
4337
4338 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004339
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004340 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004341
John McCall604e7f12009-12-08 07:46:18 +00004342 // Unlike most lookups, we don't always want to hide tag
4343 // declarations: tag names are visible through the using declaration
4344 // even if hidden by ordinary names, *except* in a dependent context
4345 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004346 if (!IsInstantiation)
4347 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004348
John McCalla24dc2e2009-11-17 02:14:36 +00004349 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004350
John McCallf36e02d2009-10-09 21:13:30 +00004351 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004352 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004353 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004354 UD->setInvalidDecl();
4355 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004356 }
4357
John McCalled976492009-12-04 22:46:56 +00004358 if (R.isAmbiguous()) {
4359 UD->setInvalidDecl();
4360 return UD;
4361 }
Mike Stump1eb44332009-09-09 15:08:12 +00004362
John McCall7ba107a2009-11-18 02:36:19 +00004363 if (IsTypeName) {
4364 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004365 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004366 Diag(IdentLoc, diag::err_using_typename_non_type);
4367 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4368 Diag((*I)->getUnderlyingDecl()->getLocation(),
4369 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004370 UD->setInvalidDecl();
4371 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004372 }
4373 } else {
4374 // If we asked for a non-typename and we got a type, error out,
4375 // but only if this is an instantiation of an unresolved using
4376 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004377 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004378 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4379 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004380 UD->setInvalidDecl();
4381 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004382 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004383 }
4384
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004385 // C++0x N2914 [namespace.udecl]p6:
4386 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004387 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004388 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4389 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004390 UD->setInvalidDecl();
4391 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004392 }
Mike Stump1eb44332009-09-09 15:08:12 +00004393
John McCall9f54ad42009-12-10 09:41:52 +00004394 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4395 if (!CheckUsingShadowDecl(UD, *I, Previous))
4396 BuildUsingShadowDecl(S, UD, *I);
4397 }
John McCall9488ea12009-11-17 05:59:44 +00004398
4399 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004400}
4401
Sebastian Redlf677ea32011-02-05 19:23:19 +00004402/// Additional checks for a using declaration referring to a constructor name.
4403bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4404 if (UD->isTypeName()) {
4405 // FIXME: Cannot specify typename when specifying constructor
4406 return true;
4407 }
4408
Douglas Gregordc355712011-02-25 00:36:19 +00004409 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004410 assert(SourceType &&
4411 "Using decl naming constructor doesn't have type in scope spec.");
4412 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4413
4414 // Check whether the named type is a direct base class.
4415 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4416 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4417 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4418 BaseIt != BaseE; ++BaseIt) {
4419 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4420 if (CanonicalSourceType == BaseType)
4421 break;
4422 }
4423
4424 if (BaseIt == BaseE) {
4425 // Did not find SourceType in the bases.
4426 Diag(UD->getUsingLocation(),
4427 diag::err_using_decl_constructor_not_in_direct_base)
4428 << UD->getNameInfo().getSourceRange()
4429 << QualType(SourceType, 0) << TargetClass;
4430 return true;
4431 }
4432
4433 BaseIt->setInheritConstructors();
4434
4435 return false;
4436}
4437
John McCall9f54ad42009-12-10 09:41:52 +00004438/// Checks that the given using declaration is not an invalid
4439/// redeclaration. Note that this is checking only for the using decl
4440/// itself, not for any ill-formedness among the UsingShadowDecls.
4441bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4442 bool isTypeName,
4443 const CXXScopeSpec &SS,
4444 SourceLocation NameLoc,
4445 const LookupResult &Prev) {
4446 // C++03 [namespace.udecl]p8:
4447 // C++0x [namespace.udecl]p10:
4448 // A using-declaration is a declaration and can therefore be used
4449 // repeatedly where (and only where) multiple declarations are
4450 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004451 //
John McCall8a726212010-11-29 18:01:58 +00004452 // That's in non-member contexts.
4453 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004454 return false;
4455
4456 NestedNameSpecifier *Qual
4457 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4458
4459 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4460 NamedDecl *D = *I;
4461
4462 bool DTypename;
4463 NestedNameSpecifier *DQual;
4464 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4465 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004466 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004467 } else if (UnresolvedUsingValueDecl *UD
4468 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4469 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004470 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004471 } else if (UnresolvedUsingTypenameDecl *UD
4472 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4473 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004474 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004475 } else continue;
4476
4477 // using decls differ if one says 'typename' and the other doesn't.
4478 // FIXME: non-dependent using decls?
4479 if (isTypeName != DTypename) continue;
4480
4481 // using decls differ if they name different scopes (but note that
4482 // template instantiation can cause this check to trigger when it
4483 // didn't before instantiation).
4484 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4485 Context.getCanonicalNestedNameSpecifier(DQual))
4486 continue;
4487
4488 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004489 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004490 return true;
4491 }
4492
4493 return false;
4494}
4495
John McCall604e7f12009-12-08 07:46:18 +00004496
John McCalled976492009-12-04 22:46:56 +00004497/// Checks that the given nested-name qualifier used in a using decl
4498/// in the current context is appropriately related to the current
4499/// scope. If an error is found, diagnoses it and returns true.
4500bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4501 const CXXScopeSpec &SS,
4502 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004503 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004504
John McCall604e7f12009-12-08 07:46:18 +00004505 if (!CurContext->isRecord()) {
4506 // C++03 [namespace.udecl]p3:
4507 // C++0x [namespace.udecl]p8:
4508 // A using-declaration for a class member shall be a member-declaration.
4509
4510 // If we weren't able to compute a valid scope, it must be a
4511 // dependent class scope.
4512 if (!NamedContext || NamedContext->isRecord()) {
4513 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4514 << SS.getRange();
4515 return true;
4516 }
4517
4518 // Otherwise, everything is known to be fine.
4519 return false;
4520 }
4521
4522 // The current scope is a record.
4523
4524 // If the named context is dependent, we can't decide much.
4525 if (!NamedContext) {
4526 // FIXME: in C++0x, we can diagnose if we can prove that the
4527 // nested-name-specifier does not refer to a base class, which is
4528 // still possible in some cases.
4529
4530 // Otherwise we have to conservatively report that things might be
4531 // okay.
4532 return false;
4533 }
4534
4535 if (!NamedContext->isRecord()) {
4536 // Ideally this would point at the last name in the specifier,
4537 // but we don't have that level of source info.
4538 Diag(SS.getRange().getBegin(),
4539 diag::err_using_decl_nested_name_specifier_is_not_class)
4540 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4541 return true;
4542 }
4543
Douglas Gregor6fb07292010-12-21 07:41:49 +00004544 if (!NamedContext->isDependentContext() &&
4545 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4546 return true;
4547
John McCall604e7f12009-12-08 07:46:18 +00004548 if (getLangOptions().CPlusPlus0x) {
4549 // C++0x [namespace.udecl]p3:
4550 // In a using-declaration used as a member-declaration, the
4551 // nested-name-specifier shall name a base class of the class
4552 // being defined.
4553
4554 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4555 cast<CXXRecordDecl>(NamedContext))) {
4556 if (CurContext == NamedContext) {
4557 Diag(NameLoc,
4558 diag::err_using_decl_nested_name_specifier_is_current_class)
4559 << SS.getRange();
4560 return true;
4561 }
4562
4563 Diag(SS.getRange().getBegin(),
4564 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4565 << (NestedNameSpecifier*) SS.getScopeRep()
4566 << cast<CXXRecordDecl>(CurContext)
4567 << SS.getRange();
4568 return true;
4569 }
4570
4571 return false;
4572 }
4573
4574 // C++03 [namespace.udecl]p4:
4575 // A using-declaration used as a member-declaration shall refer
4576 // to a member of a base class of the class being defined [etc.].
4577
4578 // Salient point: SS doesn't have to name a base class as long as
4579 // lookup only finds members from base classes. Therefore we can
4580 // diagnose here only if we can prove that that can't happen,
4581 // i.e. if the class hierarchies provably don't intersect.
4582
4583 // TODO: it would be nice if "definitely valid" results were cached
4584 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4585 // need to be repeated.
4586
4587 struct UserData {
4588 llvm::DenseSet<const CXXRecordDecl*> Bases;
4589
4590 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4591 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4592 Data->Bases.insert(Base);
4593 return true;
4594 }
4595
4596 bool hasDependentBases(const CXXRecordDecl *Class) {
4597 return !Class->forallBases(collect, this);
4598 }
4599
4600 /// Returns true if the base is dependent or is one of the
4601 /// accumulated base classes.
4602 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4603 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4604 return !Data->Bases.count(Base);
4605 }
4606
4607 bool mightShareBases(const CXXRecordDecl *Class) {
4608 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4609 }
4610 };
4611
4612 UserData Data;
4613
4614 // Returns false if we find a dependent base.
4615 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4616 return false;
4617
4618 // Returns false if the class has a dependent base or if it or one
4619 // of its bases is present in the base set of the current context.
4620 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4621 return false;
4622
4623 Diag(SS.getRange().getBegin(),
4624 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4625 << (NestedNameSpecifier*) SS.getScopeRep()
4626 << cast<CXXRecordDecl>(CurContext)
4627 << SS.getRange();
4628
4629 return true;
John McCalled976492009-12-04 22:46:56 +00004630}
4631
John McCalld226f652010-08-21 09:40:31 +00004632Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004633 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004634 SourceLocation AliasLoc,
4635 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004636 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004637 SourceLocation IdentLoc,
4638 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004639
Anders Carlsson81c85c42009-03-28 23:53:49 +00004640 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004641 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4642 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004643
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004644 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004645 NamedDecl *PrevDecl
4646 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4647 ForRedeclaration);
4648 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4649 PrevDecl = 0;
4650
4651 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004652 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004653 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004654 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004655 // FIXME: At some point, we'll want to create the (redundant)
4656 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004657 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004658 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004659 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004660 }
Mike Stump1eb44332009-09-09 15:08:12 +00004661
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004662 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4663 diag::err_redefinition_different_kind;
4664 Diag(AliasLoc, DiagID) << Alias;
4665 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004666 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004667 }
4668
John McCalla24dc2e2009-11-17 02:14:36 +00004669 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004670 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004671
John McCallf36e02d2009-10-09 21:13:30 +00004672 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004673 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4674 CTC_NoKeywords, 0)) {
4675 if (R.getAsSingle<NamespaceDecl>() ||
4676 R.getAsSingle<NamespaceAliasDecl>()) {
4677 if (DeclContext *DC = computeDeclContext(SS, false))
4678 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4679 << Ident << DC << Corrected << SS.getRange()
4680 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4681 else
4682 Diag(IdentLoc, diag::err_using_directive_suggest)
4683 << Ident << Corrected
4684 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4685
4686 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4687 << Corrected;
4688
4689 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004690 } else {
4691 R.clear();
4692 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004693 }
4694 }
4695
4696 if (R.empty()) {
4697 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004698 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004699 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004700 }
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004702 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004703 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00004704 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00004705 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004706
John McCall3dbd3d52010-02-16 06:53:13 +00004707 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004708 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004709}
4710
Douglas Gregor39957dc2010-05-01 15:04:51 +00004711namespace {
4712 /// \brief Scoped object used to handle the state changes required in Sema
4713 /// to implicitly define the body of a C++ member function;
4714 class ImplicitlyDefinedFunctionScope {
4715 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004716 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004717
4718 public:
4719 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004720 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004721 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004722 S.PushFunctionScope();
4723 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4724 }
4725
4726 ~ImplicitlyDefinedFunctionScope() {
4727 S.PopExpressionEvaluationContext();
4728 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004729 }
4730 };
4731}
4732
Sebastian Redl751025d2010-09-13 22:02:47 +00004733static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4734 CXXRecordDecl *D) {
4735 ASTContext &Context = Self.Context;
4736 QualType ClassType = Context.getTypeDeclType(D);
4737 DeclarationName ConstructorName
4738 = Context.DeclarationNames.getCXXConstructorName(
4739 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4740
4741 DeclContext::lookup_const_iterator Con, ConEnd;
4742 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4743 Con != ConEnd; ++Con) {
4744 // FIXME: In C++0x, a constructor template can be a default constructor.
4745 if (isa<FunctionTemplateDecl>(*Con))
4746 continue;
4747
4748 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4749 if (Constructor->isDefaultConstructor())
4750 return Constructor;
4751 }
4752 return 0;
4753}
4754
Douglas Gregor23c94db2010-07-02 17:43:08 +00004755CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4756 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004757 // C++ [class.ctor]p5:
4758 // A default constructor for a class X is a constructor of class X
4759 // that can be called without an argument. If there is no
4760 // user-declared constructor for class X, a default constructor is
4761 // implicitly declared. An implicitly-declared default constructor
4762 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004763 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4764 "Should not build implicit default constructor!");
4765
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004766 // C++ [except.spec]p14:
4767 // An implicitly declared special member function (Clause 12) shall have an
4768 // exception-specification. [...]
4769 ImplicitExceptionSpecification ExceptSpec(Context);
4770
Sebastian Redl60618fa2011-03-12 11:50:43 +00004771 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004772 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4773 BEnd = ClassDecl->bases_end();
4774 B != BEnd; ++B) {
4775 if (B->isVirtual()) // Handled below.
4776 continue;
4777
Douglas Gregor18274032010-07-03 00:47:00 +00004778 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4779 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4780 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4781 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004782 else if (CXXConstructorDecl *Constructor
4783 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004784 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004785 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004786 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004787
4788 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004789 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4790 BEnd = ClassDecl->vbases_end();
4791 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004792 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4793 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4794 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4795 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4796 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004797 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004798 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004799 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004800 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004801
4802 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004803 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4804 FEnd = ClassDecl->field_end();
4805 F != FEnd; ++F) {
4806 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004807 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4808 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4809 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4810 ExceptSpec.CalledDecl(
4811 DeclareImplicitDefaultConstructor(FieldClassDecl));
4812 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004813 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004814 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004815 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004816 }
John McCalle23cf432010-12-14 08:05:40 +00004817
4818 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00004819 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00004820 EPI.NumExceptions = ExceptSpec.size();
4821 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00004822
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004823 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004824 CanQualType ClassType
4825 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004826 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00004827 DeclarationName Name
4828 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004829 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00004830 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004831 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004832 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004833 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004834 /*TInfo=*/0,
4835 /*isExplicit=*/false,
4836 /*isInline=*/true,
4837 /*isImplicitlyDeclared=*/true);
4838 DefaultCon->setAccess(AS_public);
4839 DefaultCon->setImplicit();
4840 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004841
4842 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004843 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4844
Douglas Gregor23c94db2010-07-02 17:43:08 +00004845 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004846 PushOnScopeChains(DefaultCon, S, false);
4847 ClassDecl->addDecl(DefaultCon);
4848
Douglas Gregor32df23e2010-07-01 22:02:46 +00004849 return DefaultCon;
4850}
4851
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004852void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4853 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004854 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004855 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004856 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004858 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004859 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004860
Douglas Gregor39957dc2010-05-01 15:04:51 +00004861 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004862 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004863 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004864 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004865 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004866 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004867 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004868 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004869 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004870
4871 SourceLocation Loc = Constructor->getLocation();
4872 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4873
4874 Constructor->setUsed();
4875 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004876}
4877
Sebastian Redlf677ea32011-02-05 19:23:19 +00004878void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4879 // We start with an initial pass over the base classes to collect those that
4880 // inherit constructors from. If there are none, we can forgo all further
4881 // processing.
4882 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4883 BasesVector BasesToInheritFrom;
4884 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4885 BaseE = ClassDecl->bases_end();
4886 BaseIt != BaseE; ++BaseIt) {
4887 if (BaseIt->getInheritConstructors()) {
4888 QualType Base = BaseIt->getType();
4889 if (Base->isDependentType()) {
4890 // If we inherit constructors from anything that is dependent, just
4891 // abort processing altogether. We'll get another chance for the
4892 // instantiations.
4893 return;
4894 }
4895 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4896 }
4897 }
4898 if (BasesToInheritFrom.empty())
4899 return;
4900
4901 // Now collect the constructors that we already have in the current class.
4902 // Those take precedence over inherited constructors.
4903 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4904 // unless there is a user-declared constructor with the same signature in
4905 // the class where the using-declaration appears.
4906 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4907 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4908 CtorE = ClassDecl->ctor_end();
4909 CtorIt != CtorE; ++CtorIt) {
4910 ExistingConstructors.insert(
4911 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4912 }
4913
4914 Scope *S = getScopeForContext(ClassDecl);
4915 DeclarationName CreatedCtorName =
4916 Context.DeclarationNames.getCXXConstructorName(
4917 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4918
4919 // Now comes the true work.
4920 // First, we keep a map from constructor types to the base that introduced
4921 // them. Needed for finding conflicting constructors. We also keep the
4922 // actually inserted declarations in there, for pretty diagnostics.
4923 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4924 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4925 ConstructorToSourceMap InheritedConstructors;
4926 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4927 BaseE = BasesToInheritFrom.end();
4928 BaseIt != BaseE; ++BaseIt) {
4929 const RecordType *Base = *BaseIt;
4930 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4931 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4932 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4933 CtorE = BaseDecl->ctor_end();
4934 CtorIt != CtorE; ++CtorIt) {
4935 // Find the using declaration for inheriting this base's constructors.
4936 DeclarationName Name =
4937 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4938 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4939 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4940 SourceLocation UsingLoc = UD ? UD->getLocation() :
4941 ClassDecl->getLocation();
4942
4943 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4944 // from the class X named in the using-declaration consists of actual
4945 // constructors and notional constructors that result from the
4946 // transformation of defaulted parameters as follows:
4947 // - all non-template default constructors of X, and
4948 // - for each non-template constructor of X that has at least one
4949 // parameter with a default argument, the set of constructors that
4950 // results from omitting any ellipsis parameter specification and
4951 // successively omitting parameters with a default argument from the
4952 // end of the parameter-type-list.
4953 CXXConstructorDecl *BaseCtor = *CtorIt;
4954 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4955 const FunctionProtoType *BaseCtorType =
4956 BaseCtor->getType()->getAs<FunctionProtoType>();
4957
4958 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4959 maxParams = BaseCtor->getNumParams();
4960 params <= maxParams; ++params) {
4961 // Skip default constructors. They're never inherited.
4962 if (params == 0)
4963 continue;
4964 // Skip copy and move constructors for the same reason.
4965 if (CanBeCopyOrMove && params == 1)
4966 continue;
4967
4968 // Build up a function type for this particular constructor.
4969 // FIXME: The working paper does not consider that the exception spec
4970 // for the inheriting constructor might be larger than that of the
4971 // source. This code doesn't yet, either.
4972 const Type *NewCtorType;
4973 if (params == maxParams)
4974 NewCtorType = BaseCtorType;
4975 else {
4976 llvm::SmallVector<QualType, 16> Args;
4977 for (unsigned i = 0; i < params; ++i) {
4978 Args.push_back(BaseCtorType->getArgType(i));
4979 }
4980 FunctionProtoType::ExtProtoInfo ExtInfo =
4981 BaseCtorType->getExtProtoInfo();
4982 ExtInfo.Variadic = false;
4983 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4984 Args.data(), params, ExtInfo)
4985 .getTypePtr();
4986 }
4987 const Type *CanonicalNewCtorType =
4988 Context.getCanonicalType(NewCtorType);
4989
4990 // Now that we have the type, first check if the class already has a
4991 // constructor with this signature.
4992 if (ExistingConstructors.count(CanonicalNewCtorType))
4993 continue;
4994
4995 // Then we check if we have already declared an inherited constructor
4996 // with this signature.
4997 std::pair<ConstructorToSourceMap::iterator, bool> result =
4998 InheritedConstructors.insert(std::make_pair(
4999 CanonicalNewCtorType,
5000 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5001 if (!result.second) {
5002 // Already in the map. If it came from a different class, that's an
5003 // error. Not if it's from the same.
5004 CanQualType PreviousBase = result.first->second.first;
5005 if (CanonicalBase != PreviousBase) {
5006 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5007 const CXXConstructorDecl *PrevBaseCtor =
5008 PrevCtor->getInheritedConstructor();
5009 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5010
5011 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5012 Diag(BaseCtor->getLocation(),
5013 diag::note_using_decl_constructor_conflict_current_ctor);
5014 Diag(PrevBaseCtor->getLocation(),
5015 diag::note_using_decl_constructor_conflict_previous_ctor);
5016 Diag(PrevCtor->getLocation(),
5017 diag::note_using_decl_constructor_conflict_previous_using);
5018 }
5019 continue;
5020 }
5021
5022 // OK, we're there, now add the constructor.
5023 // C++0x [class.inhctor]p8: [...] that would be performed by a
5024 // user-writtern inline constructor [...]
5025 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5026 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005027 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5028 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005029 /*ImplicitlyDeclared=*/true);
5030 NewCtor->setAccess(BaseCtor->getAccess());
5031
5032 // Build up the parameter decls and add them.
5033 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5034 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005035 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5036 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005037 /*IdentifierInfo=*/0,
5038 BaseCtorType->getArgType(i),
5039 /*TInfo=*/0, SC_None,
5040 SC_None, /*DefaultArg=*/0));
5041 }
5042 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5043 NewCtor->setInheritedConstructor(BaseCtor);
5044
5045 PushOnScopeChains(NewCtor, S, false);
5046 ClassDecl->addDecl(NewCtor);
5047 result.first->second.second = NewCtor;
5048 }
5049 }
5050 }
5051}
5052
Douglas Gregor23c94db2010-07-02 17:43:08 +00005053CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005054 // C++ [class.dtor]p2:
5055 // If a class has no user-declared destructor, a destructor is
5056 // declared implicitly. An implicitly-declared destructor is an
5057 // inline public member of its class.
5058
5059 // C++ [except.spec]p14:
5060 // An implicitly declared special member function (Clause 12) shall have
5061 // an exception-specification.
5062 ImplicitExceptionSpecification ExceptSpec(Context);
5063
5064 // Direct base-class destructors.
5065 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5066 BEnd = ClassDecl->bases_end();
5067 B != BEnd; ++B) {
5068 if (B->isVirtual()) // Handled below.
5069 continue;
5070
5071 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5072 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005073 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005074 }
5075
5076 // Virtual base-class destructors.
5077 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5078 BEnd = ClassDecl->vbases_end();
5079 B != BEnd; ++B) {
5080 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5081 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005082 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005083 }
5084
5085 // Field destructors.
5086 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5087 FEnd = ClassDecl->field_end();
5088 F != FEnd; ++F) {
5089 if (const RecordType *RecordTy
5090 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5091 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005092 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005093 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005094
Douglas Gregor4923aa22010-07-02 20:37:36 +00005095 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005096 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005097 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005098 EPI.NumExceptions = ExceptSpec.size();
5099 EPI.Exceptions = ExceptSpec.data();
5100 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005101
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005102 CanQualType ClassType
5103 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005104 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005105 DeclarationName Name
5106 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005107 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005108 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005109 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5110 /*isInline=*/true,
5111 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005112 Destructor->setAccess(AS_public);
5113 Destructor->setImplicit();
5114 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005115
5116 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005117 ++ASTContext::NumImplicitDestructorsDeclared;
5118
5119 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005120 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005121 PushOnScopeChains(Destructor, S, false);
5122 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005123
5124 // This could be uniqued if it ever proves significant.
5125 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5126
5127 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005128
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005129 return Destructor;
5130}
5131
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005132void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005133 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00005134 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005135 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005136 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005137 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005138
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005139 if (Destructor->isInvalidDecl())
5140 return;
5141
Douglas Gregor39957dc2010-05-01 15:04:51 +00005142 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005143
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005144 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005145 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5146 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005147
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005148 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005149 Diag(CurrentLocation, diag::note_member_synthesized_at)
5150 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5151
5152 Destructor->setInvalidDecl();
5153 return;
5154 }
5155
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005156 SourceLocation Loc = Destructor->getLocation();
5157 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5158
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005159 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005160 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005161}
5162
Douglas Gregor06a9f362010-05-01 20:49:11 +00005163/// \brief Builds a statement that copies the given entity from \p From to
5164/// \c To.
5165///
5166/// This routine is used to copy the members of a class with an
5167/// implicitly-declared copy assignment operator. When the entities being
5168/// copied are arrays, this routine builds for loops to copy them.
5169///
5170/// \param S The Sema object used for type-checking.
5171///
5172/// \param Loc The location where the implicit copy is being generated.
5173///
5174/// \param T The type of the expressions being copied. Both expressions must
5175/// have this type.
5176///
5177/// \param To The expression we are copying to.
5178///
5179/// \param From The expression we are copying from.
5180///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005181/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5182/// Otherwise, it's a non-static member subobject.
5183///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005184/// \param Depth Internal parameter recording the depth of the recursion.
5185///
5186/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005187static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005188BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005189 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005190 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005191 // C++0x [class.copy]p30:
5192 // Each subobject is assigned in the manner appropriate to its type:
5193 //
5194 // - if the subobject is of class type, the copy assignment operator
5195 // for the class is used (as if by explicit qualification; that is,
5196 // ignoring any possible virtual overriding functions in more derived
5197 // classes);
5198 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5199 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5200
5201 // Look for operator=.
5202 DeclarationName Name
5203 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5204 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5205 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5206
5207 // Filter out any result that isn't a copy-assignment operator.
5208 LookupResult::Filter F = OpLookup.makeFilter();
5209 while (F.hasNext()) {
5210 NamedDecl *D = F.next();
5211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5212 if (Method->isCopyAssignmentOperator())
5213 continue;
5214
5215 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005216 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005217 F.done();
5218
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005219 // Suppress the protected check (C++ [class.protected]) for each of the
5220 // assignment operators we found. This strange dance is required when
5221 // we're assigning via a base classes's copy-assignment operator. To
5222 // ensure that we're getting the right base class subobject (without
5223 // ambiguities), we need to cast "this" to that subobject type; to
5224 // ensure that we don't go through the virtual call mechanism, we need
5225 // to qualify the operator= name with the base class (see below). However,
5226 // this means that if the base class has a protected copy assignment
5227 // operator, the protected member access check will fail. So, we
5228 // rewrite "protected" access to "public" access in this case, since we
5229 // know by construction that we're calling from a derived class.
5230 if (CopyingBaseSubobject) {
5231 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5232 L != LEnd; ++L) {
5233 if (L.getAccess() == AS_protected)
5234 L.setAccess(AS_public);
5235 }
5236 }
5237
Douglas Gregor06a9f362010-05-01 20:49:11 +00005238 // Create the nested-name-specifier that will be used to qualify the
5239 // reference to operator=; this is required to suppress the virtual
5240 // call mechanism.
5241 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005242 SS.MakeTrivial(S.Context,
5243 NestedNameSpecifier::Create(S.Context, 0, false,
5244 T.getTypePtr()),
5245 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005246
5247 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005248 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005249 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005250 /*FirstQualifierInScope=*/0, OpLookup,
5251 /*TemplateArgs=*/0,
5252 /*SuppressQualifierCheck=*/true);
5253 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005254 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005255
5256 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005257
John McCall60d7b3a2010-08-24 06:29:42 +00005258 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005259 OpEqualRef.takeAs<Expr>(),
5260 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005261 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005262 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005263
5264 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005265 }
John McCallb0207482010-03-16 06:11:48 +00005266
Douglas Gregor06a9f362010-05-01 20:49:11 +00005267 // - if the subobject is of scalar type, the built-in assignment
5268 // operator is used.
5269 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5270 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005271 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005272 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005273 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005274
5275 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005276 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005277
5278 // - if the subobject is an array, each element is assigned, in the
5279 // manner appropriate to the element type;
5280
5281 // Construct a loop over the array bounds, e.g.,
5282 //
5283 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5284 //
5285 // that will copy each of the array elements.
5286 QualType SizeType = S.Context.getSizeType();
5287
5288 // Create the iteration variable.
5289 IdentifierInfo *IterationVarName = 0;
5290 {
5291 llvm::SmallString<8> Str;
5292 llvm::raw_svector_ostream OS(Str);
5293 OS << "__i" << Depth;
5294 IterationVarName = &S.Context.Idents.get(OS.str());
5295 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005296 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005297 IterationVarName, SizeType,
5298 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005299 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005300
5301 // Initialize the iteration variable to zero.
5302 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005303 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005304
5305 // Create a reference to the iteration variable; we'll use this several
5306 // times throughout.
5307 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005308 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005309 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5310
5311 // Create the DeclStmt that holds the iteration variable.
5312 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5313
5314 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005315 llvm::APInt Upper
5316 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005317 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005318 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005319 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5320 BO_NE, S.Context.BoolTy,
5321 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005322
5323 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005324 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005325 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5326 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005327
5328 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005329 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5330 IterationVarRef, Loc));
5331 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5332 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005333
5334 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005335 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5336 To, From, CopyingBaseSubobject,
5337 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005338 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005339 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005340
5341 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005342 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005343 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005344 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005345 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005346}
5347
Douglas Gregora376d102010-07-02 21:50:04 +00005348/// \brief Determine whether the given class has a copy assignment operator
5349/// that accepts a const-qualified argument.
5350static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5351 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5352
5353 if (!Class->hasDeclaredCopyAssignment())
5354 S.DeclareImplicitCopyAssignment(Class);
5355
5356 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5357 DeclarationName OpName
5358 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5359
5360 DeclContext::lookup_const_iterator Op, OpEnd;
5361 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5362 // C++ [class.copy]p9:
5363 // A user-declared copy assignment operator is a non-static non-template
5364 // member function of class X with exactly one parameter of type X, X&,
5365 // const X&, volatile X& or const volatile X&.
5366 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5367 if (!Method)
5368 continue;
5369
5370 if (Method->isStatic())
5371 continue;
5372 if (Method->getPrimaryTemplate())
5373 continue;
5374 const FunctionProtoType *FnType =
5375 Method->getType()->getAs<FunctionProtoType>();
5376 assert(FnType && "Overloaded operator has no prototype.");
5377 // Don't assert on this; an invalid decl might have been left in the AST.
5378 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5379 continue;
5380 bool AcceptsConst = true;
5381 QualType ArgType = FnType->getArgType(0);
5382 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5383 ArgType = Ref->getPointeeType();
5384 // Is it a non-const lvalue reference?
5385 if (!ArgType.isConstQualified())
5386 AcceptsConst = false;
5387 }
5388 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5389 continue;
5390
5391 // We have a single argument of type cv X or cv X&, i.e. we've found the
5392 // copy assignment operator. Return whether it accepts const arguments.
5393 return AcceptsConst;
5394 }
5395 assert(Class->isInvalidDecl() &&
5396 "No copy assignment operator declared in valid code.");
5397 return false;
5398}
5399
Douglas Gregor23c94db2010-07-02 17:43:08 +00005400CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005401 // Note: The following rules are largely analoguous to the copy
5402 // constructor rules. Note that virtual bases are not taken into account
5403 // for determining the argument type of the operator. Note also that
5404 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005405
5406
Douglas Gregord3c35902010-07-01 16:36:15 +00005407 // C++ [class.copy]p10:
5408 // If the class definition does not explicitly declare a copy
5409 // assignment operator, one is declared implicitly.
5410 // The implicitly-defined copy assignment operator for a class X
5411 // will have the form
5412 //
5413 // X& X::operator=(const X&)
5414 //
5415 // if
5416 bool HasConstCopyAssignment = true;
5417
5418 // -- each direct base class B of X has a copy assignment operator
5419 // whose parameter is of type const B&, const volatile B& or B,
5420 // and
5421 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5422 BaseEnd = ClassDecl->bases_end();
5423 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5424 assert(!Base->getType()->isDependentType() &&
5425 "Cannot generate implicit members for class with dependent bases.");
5426 const CXXRecordDecl *BaseClassDecl
5427 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005428 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005429 }
5430
5431 // -- for all the nonstatic data members of X that are of a class
5432 // type M (or array thereof), each such class type has a copy
5433 // assignment operator whose parameter is of type const M&,
5434 // const volatile M& or M.
5435 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5436 FieldEnd = ClassDecl->field_end();
5437 HasConstCopyAssignment && Field != FieldEnd;
5438 ++Field) {
5439 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5440 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5441 const CXXRecordDecl *FieldClassDecl
5442 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005443 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005444 }
5445 }
5446
5447 // Otherwise, the implicitly declared copy assignment operator will
5448 // have the form
5449 //
5450 // X& X::operator=(X&)
5451 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5452 QualType RetType = Context.getLValueReferenceType(ArgType);
5453 if (HasConstCopyAssignment)
5454 ArgType = ArgType.withConst();
5455 ArgType = Context.getLValueReferenceType(ArgType);
5456
Douglas Gregorb87786f2010-07-01 17:48:08 +00005457 // C++ [except.spec]p14:
5458 // An implicitly declared special member function (Clause 12) shall have an
5459 // exception-specification. [...]
5460 ImplicitExceptionSpecification ExceptSpec(Context);
5461 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5462 BaseEnd = ClassDecl->bases_end();
5463 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005464 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005465 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005466
5467 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5468 DeclareImplicitCopyAssignment(BaseClassDecl);
5469
Douglas Gregorb87786f2010-07-01 17:48:08 +00005470 if (CXXMethodDecl *CopyAssign
5471 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5472 ExceptSpec.CalledDecl(CopyAssign);
5473 }
5474 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5475 FieldEnd = ClassDecl->field_end();
5476 Field != FieldEnd;
5477 ++Field) {
5478 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5479 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005480 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005481 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005482
5483 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5484 DeclareImplicitCopyAssignment(FieldClassDecl);
5485
Douglas Gregorb87786f2010-07-01 17:48:08 +00005486 if (CXXMethodDecl *CopyAssign
5487 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5488 ExceptSpec.CalledDecl(CopyAssign);
5489 }
5490 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005491
Douglas Gregord3c35902010-07-01 16:36:15 +00005492 // An implicitly-declared copy assignment operator is an inline public
5493 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005494 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005495 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005496 EPI.NumExceptions = ExceptSpec.size();
5497 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005498 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005499 SourceLocation ClassLoc = ClassDecl->getLocation();
5500 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00005501 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005502 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005503 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005504 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005505 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00005506 /*isInline=*/true,
5507 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005508 CopyAssignment->setAccess(AS_public);
5509 CopyAssignment->setImplicit();
5510 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005511
5512 // Add the parameter to the operator.
5513 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005514 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00005515 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005516 SC_None,
5517 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005518 CopyAssignment->setParams(&FromParam, 1);
5519
Douglas Gregora376d102010-07-02 21:50:04 +00005520 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005521 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5522
Douglas Gregor23c94db2010-07-02 17:43:08 +00005523 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005524 PushOnScopeChains(CopyAssignment, S, false);
5525 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005526
5527 AddOverriddenMethods(ClassDecl, CopyAssignment);
5528 return CopyAssignment;
5529}
5530
Douglas Gregor06a9f362010-05-01 20:49:11 +00005531void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5532 CXXMethodDecl *CopyAssignOperator) {
5533 assert((CopyAssignOperator->isImplicit() &&
5534 CopyAssignOperator->isOverloadedOperator() &&
5535 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005536 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005537 "DefineImplicitCopyAssignment called for wrong function");
5538
5539 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5540
5541 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5542 CopyAssignOperator->setInvalidDecl();
5543 return;
5544 }
5545
5546 CopyAssignOperator->setUsed();
5547
5548 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005549 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005550
5551 // C++0x [class.copy]p30:
5552 // The implicitly-defined or explicitly-defaulted copy assignment operator
5553 // for a non-union class X performs memberwise copy assignment of its
5554 // subobjects. The direct base classes of X are assigned first, in the
5555 // order of their declaration in the base-specifier-list, and then the
5556 // immediate non-static data members of X are assigned, in the order in
5557 // which they were declared in the class definition.
5558
5559 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005560 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005561
5562 // The parameter for the "other" object, which we are copying from.
5563 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5564 Qualifiers OtherQuals = Other->getType().getQualifiers();
5565 QualType OtherRefType = Other->getType();
5566 if (const LValueReferenceType *OtherRef
5567 = OtherRefType->getAs<LValueReferenceType>()) {
5568 OtherRefType = OtherRef->getPointeeType();
5569 OtherQuals = OtherRefType.getQualifiers();
5570 }
5571
5572 // Our location for everything implicitly-generated.
5573 SourceLocation Loc = CopyAssignOperator->getLocation();
5574
5575 // Construct a reference to the "other" object. We'll be using this
5576 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005577 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005578 assert(OtherRef && "Reference to parameter cannot fail!");
5579
5580 // Construct the "this" pointer. We'll be using this throughout the generated
5581 // ASTs.
5582 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5583 assert(This && "Reference to this cannot fail!");
5584
5585 // Assign base classes.
5586 bool Invalid = false;
5587 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5588 E = ClassDecl->bases_end(); Base != E; ++Base) {
5589 // Form the assignment:
5590 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5591 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005592 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005593 Invalid = true;
5594 continue;
5595 }
5596
John McCallf871d0c2010-08-07 06:22:56 +00005597 CXXCastPath BasePath;
5598 BasePath.push_back(Base);
5599
Douglas Gregor06a9f362010-05-01 20:49:11 +00005600 // Construct the "from" expression, which is an implicit cast to the
5601 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005602 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005603 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005604 CK_UncheckedDerivedToBase,
5605 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005606
5607 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005608 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005609
5610 // Implicitly cast "this" to the appropriately-qualified base type.
5611 Expr *ToE = To.takeAs<Expr>();
5612 ImpCastExprToType(ToE,
5613 Context.getCVRQualifiedType(BaseType,
5614 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005615 CK_UncheckedDerivedToBase,
5616 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005617 To = Owned(ToE);
5618
5619 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005620 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005621 To.get(), From,
5622 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005623 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005624 Diag(CurrentLocation, diag::note_member_synthesized_at)
5625 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5626 CopyAssignOperator->setInvalidDecl();
5627 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005628 }
5629
5630 // Success! Record the copy.
5631 Statements.push_back(Copy.takeAs<Expr>());
5632 }
5633
5634 // \brief Reference to the __builtin_memcpy function.
5635 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005636 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005637 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005638
5639 // Assign non-static members.
5640 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5641 FieldEnd = ClassDecl->field_end();
5642 Field != FieldEnd; ++Field) {
5643 // Check for members of reference type; we can't copy those.
5644 if (Field->getType()->isReferenceType()) {
5645 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5646 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5647 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005648 Diag(CurrentLocation, diag::note_member_synthesized_at)
5649 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005650 Invalid = true;
5651 continue;
5652 }
5653
5654 // Check for members of const-qualified, non-class type.
5655 QualType BaseType = Context.getBaseElementType(Field->getType());
5656 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5657 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5658 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5659 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005660 Diag(CurrentLocation, diag::note_member_synthesized_at)
5661 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005662 Invalid = true;
5663 continue;
5664 }
5665
5666 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005667 if (FieldType->isIncompleteArrayType()) {
5668 assert(ClassDecl->hasFlexibleArrayMember() &&
5669 "Incomplete array type is not valid");
5670 continue;
5671 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005672
5673 // Build references to the field in the object we're copying from and to.
5674 CXXScopeSpec SS; // Intentionally empty
5675 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5676 LookupMemberName);
5677 MemberLookup.addDecl(*Field);
5678 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005679 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005680 Loc, /*IsArrow=*/false,
5681 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005682 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005683 Loc, /*IsArrow=*/true,
5684 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005685 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5686 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5687
5688 // If the field should be copied with __builtin_memcpy rather than via
5689 // explicit assignments, do so. This optimization only applies for arrays
5690 // of scalars and arrays of class type with trivial copy-assignment
5691 // operators.
5692 if (FieldType->isArrayType() &&
5693 (!BaseType->isRecordType() ||
5694 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5695 ->hasTrivialCopyAssignment())) {
5696 // Compute the size of the memory buffer to be copied.
5697 QualType SizeType = Context.getSizeType();
5698 llvm::APInt Size(Context.getTypeSize(SizeType),
5699 Context.getTypeSizeInChars(BaseType).getQuantity());
5700 for (const ConstantArrayType *Array
5701 = Context.getAsConstantArrayType(FieldType);
5702 Array;
5703 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005704 llvm::APInt ArraySize
5705 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005706 Size *= ArraySize;
5707 }
5708
5709 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005710 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5711 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005712
5713 bool NeedsCollectableMemCpy =
5714 (BaseType->isRecordType() &&
5715 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5716
5717 if (NeedsCollectableMemCpy) {
5718 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005719 // Create a reference to the __builtin_objc_memmove_collectable function.
5720 LookupResult R(*this,
5721 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005722 Loc, LookupOrdinaryName);
5723 LookupName(R, TUScope, true);
5724
5725 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5726 if (!CollectableMemCpy) {
5727 // Something went horribly wrong earlier, and we will have
5728 // complained about it.
5729 Invalid = true;
5730 continue;
5731 }
5732
5733 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5734 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005735 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005736 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5737 }
5738 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005739 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005740 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005741 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5742 LookupOrdinaryName);
5743 LookupName(R, TUScope, true);
5744
5745 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5746 if (!BuiltinMemCpy) {
5747 // Something went horribly wrong earlier, and we will have complained
5748 // about it.
5749 Invalid = true;
5750 continue;
5751 }
5752
5753 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5754 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005755 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005756 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5757 }
5758
John McCallca0408f2010-08-23 06:44:23 +00005759 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005760 CallArgs.push_back(To.takeAs<Expr>());
5761 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005762 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005763 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005764 if (NeedsCollectableMemCpy)
5765 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005766 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005767 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005768 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005769 else
5770 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005771 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005772 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005773 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005774
Douglas Gregor06a9f362010-05-01 20:49:11 +00005775 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5776 Statements.push_back(Call.takeAs<Expr>());
5777 continue;
5778 }
5779
5780 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005781 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005782 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005783 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005784 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005785 Diag(CurrentLocation, diag::note_member_synthesized_at)
5786 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5787 CopyAssignOperator->setInvalidDecl();
5788 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005789 }
5790
5791 // Success! Record the copy.
5792 Statements.push_back(Copy.takeAs<Stmt>());
5793 }
5794
5795 if (!Invalid) {
5796 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005797 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005798
John McCall60d7b3a2010-08-24 06:29:42 +00005799 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005800 if (Return.isInvalid())
5801 Invalid = true;
5802 else {
5803 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005804
5805 if (Trap.hasErrorOccurred()) {
5806 Diag(CurrentLocation, diag::note_member_synthesized_at)
5807 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5808 Invalid = true;
5809 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005810 }
5811 }
5812
5813 if (Invalid) {
5814 CopyAssignOperator->setInvalidDecl();
5815 return;
5816 }
5817
John McCall60d7b3a2010-08-24 06:29:42 +00005818 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005819 /*isStmtExpr=*/false);
5820 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5821 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005822}
5823
Douglas Gregor23c94db2010-07-02 17:43:08 +00005824CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5825 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005826 // C++ [class.copy]p4:
5827 // If the class definition does not explicitly declare a copy
5828 // constructor, one is declared implicitly.
5829
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005830 // C++ [class.copy]p5:
5831 // The implicitly-declared copy constructor for a class X will
5832 // have the form
5833 //
5834 // X::X(const X&)
5835 //
5836 // if
5837 bool HasConstCopyConstructor = true;
5838
5839 // -- each direct or virtual base class B of X has a copy
5840 // constructor whose first parameter is of type const B& or
5841 // const volatile B&, and
5842 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5843 BaseEnd = ClassDecl->bases_end();
5844 HasConstCopyConstructor && Base != BaseEnd;
5845 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005846 // Virtual bases are handled below.
5847 if (Base->isVirtual())
5848 continue;
5849
Douglas Gregor22584312010-07-02 23:41:54 +00005850 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005851 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005852 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5853 DeclareImplicitCopyConstructor(BaseClassDecl);
5854
Douglas Gregor598a8542010-07-01 18:27:03 +00005855 HasConstCopyConstructor
5856 = BaseClassDecl->hasConstCopyConstructor(Context);
5857 }
5858
5859 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5860 BaseEnd = ClassDecl->vbases_end();
5861 HasConstCopyConstructor && Base != BaseEnd;
5862 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005863 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005864 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005865 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5866 DeclareImplicitCopyConstructor(BaseClassDecl);
5867
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005868 HasConstCopyConstructor
5869 = BaseClassDecl->hasConstCopyConstructor(Context);
5870 }
5871
5872 // -- for all the nonstatic data members of X that are of a
5873 // class type M (or array thereof), each such class type
5874 // has a copy constructor whose first parameter is of type
5875 // const M& or const volatile M&.
5876 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5877 FieldEnd = ClassDecl->field_end();
5878 HasConstCopyConstructor && Field != FieldEnd;
5879 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005880 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005881 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005882 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005883 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005884 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5885 DeclareImplicitCopyConstructor(FieldClassDecl);
5886
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005887 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005888 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005889 }
5890 }
5891
5892 // Otherwise, the implicitly declared copy constructor will have
5893 // the form
5894 //
5895 // X::X(X&)
5896 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5897 QualType ArgType = ClassType;
5898 if (HasConstCopyConstructor)
5899 ArgType = ArgType.withConst();
5900 ArgType = Context.getLValueReferenceType(ArgType);
5901
Douglas Gregor0d405db2010-07-01 20:59:04 +00005902 // C++ [except.spec]p14:
5903 // An implicitly declared special member function (Clause 12) shall have an
5904 // exception-specification. [...]
5905 ImplicitExceptionSpecification ExceptSpec(Context);
5906 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5907 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5908 BaseEnd = ClassDecl->bases_end();
5909 Base != BaseEnd;
5910 ++Base) {
5911 // Virtual bases are handled below.
5912 if (Base->isVirtual())
5913 continue;
5914
Douglas Gregor22584312010-07-02 23:41:54 +00005915 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005916 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005917 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5918 DeclareImplicitCopyConstructor(BaseClassDecl);
5919
Douglas Gregor0d405db2010-07-01 20:59:04 +00005920 if (CXXConstructorDecl *CopyConstructor
5921 = BaseClassDecl->getCopyConstructor(Context, Quals))
5922 ExceptSpec.CalledDecl(CopyConstructor);
5923 }
5924 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5925 BaseEnd = ClassDecl->vbases_end();
5926 Base != BaseEnd;
5927 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005928 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005929 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005930 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5931 DeclareImplicitCopyConstructor(BaseClassDecl);
5932
Douglas Gregor0d405db2010-07-01 20:59:04 +00005933 if (CXXConstructorDecl *CopyConstructor
5934 = BaseClassDecl->getCopyConstructor(Context, Quals))
5935 ExceptSpec.CalledDecl(CopyConstructor);
5936 }
5937 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5938 FieldEnd = ClassDecl->field_end();
5939 Field != FieldEnd;
5940 ++Field) {
5941 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5942 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005943 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005944 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005945 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5946 DeclareImplicitCopyConstructor(FieldClassDecl);
5947
Douglas Gregor0d405db2010-07-01 20:59:04 +00005948 if (CXXConstructorDecl *CopyConstructor
5949 = FieldClassDecl->getCopyConstructor(Context, Quals))
5950 ExceptSpec.CalledDecl(CopyConstructor);
5951 }
5952 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005953
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005954 // An implicitly-declared copy constructor is an inline public
5955 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005956 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005957 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005958 EPI.NumExceptions = ExceptSpec.size();
5959 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005960 DeclarationName Name
5961 = Context.DeclarationNames.getCXXConstructorName(
5962 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005963 SourceLocation ClassLoc = ClassDecl->getLocation();
5964 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005965 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005966 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005967 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005968 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005969 /*TInfo=*/0,
5970 /*isExplicit=*/false,
5971 /*isInline=*/true,
5972 /*isImplicitlyDeclared=*/true);
5973 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005974 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5975
Douglas Gregor22584312010-07-02 23:41:54 +00005976 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005977 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5978
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005979 // Add the parameter to the constructor.
5980 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005981 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005982 /*IdentifierInfo=*/0,
5983 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005984 SC_None,
5985 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005986 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005987 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005988 PushOnScopeChains(CopyConstructor, S, false);
5989 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005990
5991 return CopyConstructor;
5992}
5993
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005994void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5995 CXXConstructorDecl *CopyConstructor,
5996 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005997 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005998 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005999 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006000 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006001
Anders Carlsson63010a72010-04-23 16:24:12 +00006002 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006003 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006004
Douglas Gregor39957dc2010-05-01 15:04:51 +00006005 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006006 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006007
Sean Huntcbb67482011-01-08 20:30:50 +00006008 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006009 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006010 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006011 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006012 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006013 } else {
6014 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6015 CopyConstructor->getLocation(),
6016 MultiStmtArg(*this, 0, 0),
6017 /*isStmtExpr=*/false)
6018 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006019 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006020
6021 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006022}
6023
John McCall60d7b3a2010-08-24 06:29:42 +00006024ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006025Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006026 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006027 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006028 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006029 unsigned ConstructKind,
6030 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006031 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006032
Douglas Gregor2f599792010-04-02 18:24:57 +00006033 // C++0x [class.copy]p34:
6034 // When certain criteria are met, an implementation is allowed to
6035 // omit the copy/move construction of a class object, even if the
6036 // copy/move constructor and/or destructor for the object have
6037 // side effects. [...]
6038 // - when a temporary class object that has not been bound to a
6039 // reference (12.2) would be copied/moved to a class object
6040 // with the same cv-unqualified type, the copy/move operation
6041 // can be omitted by constructing the temporary object
6042 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006043 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006044 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006045 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006046 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006047 }
Mike Stump1eb44332009-09-09 15:08:12 +00006048
6049 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006050 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006051 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006052}
6053
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006054/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6055/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006056ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006057Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6058 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006059 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006060 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006061 unsigned ConstructKind,
6062 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006063 unsigned NumExprs = ExprArgs.size();
6064 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006065
Douglas Gregor7edfb692009-11-23 12:27:39 +00006066 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006067 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006068 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006069 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006070 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6071 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006072}
6073
Mike Stump1eb44332009-09-09 15:08:12 +00006074bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006075 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006076 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006077 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006078 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006079 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006080 move(Exprs), false, CXXConstructExpr::CK_Complete,
6081 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006082 if (TempResult.isInvalid())
6083 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006084
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006085 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006086 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006087 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006088 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006089 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006090
Anders Carlssonfe2de492009-08-25 05:18:00 +00006091 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006092}
6093
John McCall68c6c9a2010-02-02 09:10:11 +00006094void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
6095 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00006096 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00006097 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00006098 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00006099 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00006100 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006101 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00006102 << VD->getDeclName()
6103 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00006104
John McCallae792222010-09-18 05:25:11 +00006105 // TODO: this should be re-enabled for static locals by !CXAAtExit
6106 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00006107 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00006108 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006109}
6110
Mike Stump1eb44332009-09-09 15:08:12 +00006111/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006112/// ActOnDeclarator, when a C++ direct initializer is present.
6113/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006114void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006115 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006116 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006117 SourceLocation RParenLoc,
6118 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006119 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006120
6121 // If there is no declaration, there was an error parsing it. Just ignore
6122 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006123 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006124 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006125
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006126 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6127 if (!VDecl) {
6128 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6129 RealDecl->setInvalidDecl();
6130 return;
6131 }
6132
Richard Smith34b41d92011-02-20 03:19:35 +00006133 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6134 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006135 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6136 if (Exprs.size() > 1) {
6137 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6138 diag::err_auto_var_init_multiple_expressions)
6139 << VDecl->getDeclName() << VDecl->getType()
6140 << VDecl->getSourceRange();
6141 RealDecl->setInvalidDecl();
6142 return;
6143 }
6144
6145 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006146 TypeSourceInfo *DeducedType = 0;
6147 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006148 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6149 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6150 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006151 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006152 RealDecl->setInvalidDecl();
6153 return;
6154 }
Richard Smitha085da82011-03-17 16:11:59 +00006155 VDecl->setTypeSourceInfo(DeducedType);
6156 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006157
6158 // If this is a redeclaration, check that the type we just deduced matches
6159 // the previously declared type.
6160 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6161 MergeVarDeclTypes(VDecl, Old);
6162 }
6163
Douglas Gregor83ddad32009-08-26 21:14:46 +00006164 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006165 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006166 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6167 //
6168 // Clients that want to distinguish between the two forms, can check for
6169 // direct initializer using VarDecl::hasCXXDirectInitializer().
6170 // A major benefit is that clients that don't particularly care about which
6171 // exactly form was it (like the CodeGen) can handle both cases without
6172 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006173
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006174 // C++ 8.5p11:
6175 // The form of initialization (using parentheses or '=') is generally
6176 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006177 // class type.
6178
Douglas Gregor4dffad62010-02-11 22:55:30 +00006179 if (!VDecl->getType()->isDependentType() &&
6180 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006181 diag::err_typecheck_decl_incomplete_type)) {
6182 VDecl->setInvalidDecl();
6183 return;
6184 }
6185
Douglas Gregor90f93822009-12-22 22:17:25 +00006186 // The variable can not have an abstract class type.
6187 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6188 diag::err_abstract_type_in_decl,
6189 AbstractVariableType))
6190 VDecl->setInvalidDecl();
6191
Sebastian Redl31310a22010-02-01 20:16:42 +00006192 const VarDecl *Def;
6193 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006194 Diag(VDecl->getLocation(), diag::err_redefinition)
6195 << VDecl->getDeclName();
6196 Diag(Def->getLocation(), diag::note_previous_definition);
6197 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006198 return;
6199 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006200
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006201 // C++ [class.static.data]p4
6202 // If a static data member is of const integral or const
6203 // enumeration type, its declaration in the class definition can
6204 // specify a constant-initializer which shall be an integral
6205 // constant expression (5.19). In that case, the member can appear
6206 // in integral constant expressions. The member shall still be
6207 // defined in a namespace scope if it is used in the program and the
6208 // namespace scope definition shall not contain an initializer.
6209 //
6210 // We already performed a redefinition check above, but for static
6211 // data members we also need to check whether there was an in-class
6212 // declaration with an initializer.
6213 const VarDecl* PrevInit = 0;
6214 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6215 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6216 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6217 return;
6218 }
6219
Douglas Gregora31040f2010-12-16 01:31:22 +00006220 bool IsDependent = false;
6221 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6222 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6223 VDecl->setInvalidDecl();
6224 return;
6225 }
6226
6227 if (Exprs.get()[I]->isTypeDependent())
6228 IsDependent = true;
6229 }
6230
Douglas Gregor4dffad62010-02-11 22:55:30 +00006231 // If either the declaration has a dependent type or if any of the
6232 // expressions is type-dependent, we represent the initialization
6233 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006234 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006235 // Let clients know that initialization was done with a direct initializer.
6236 VDecl->setCXXDirectInitializer(true);
6237
6238 // Store the initialization expressions as a ParenListExpr.
6239 unsigned NumExprs = Exprs.size();
6240 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6241 (Expr **)Exprs.release(),
6242 NumExprs, RParenLoc));
6243 return;
6244 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006245
6246 // Capture the variable that is being initialized and the style of
6247 // initialization.
6248 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6249
6250 // FIXME: Poor source location information.
6251 InitializationKind Kind
6252 = InitializationKind::CreateDirect(VDecl->getLocation(),
6253 LParenLoc, RParenLoc);
6254
6255 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006256 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006257 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006258 if (Result.isInvalid()) {
6259 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006260 return;
6261 }
John McCallb4eb64d2010-10-08 02:01:28 +00006262
6263 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006264
Douglas Gregor53c374f2010-12-07 00:41:46 +00006265 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006266 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006267 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006268
John McCall2998d6b2011-01-19 11:48:09 +00006269 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006270}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006271
Douglas Gregor39da0b82009-09-09 23:08:42 +00006272/// \brief Given a constructor and the set of arguments provided for the
6273/// constructor, convert the arguments and add any required default arguments
6274/// to form a proper call to this constructor.
6275///
6276/// \returns true if an error occurred, false otherwise.
6277bool
6278Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6279 MultiExprArg ArgsPtr,
6280 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006281 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006282 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6283 unsigned NumArgs = ArgsPtr.size();
6284 Expr **Args = (Expr **)ArgsPtr.get();
6285
6286 const FunctionProtoType *Proto
6287 = Constructor->getType()->getAs<FunctionProtoType>();
6288 assert(Proto && "Constructor without a prototype?");
6289 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006290
6291 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006292 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006293 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006294 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006295 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006296
6297 VariadicCallType CallType =
6298 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6299 llvm::SmallVector<Expr *, 8> AllArgs;
6300 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6301 Proto, 0, Args, NumArgs, AllArgs,
6302 CallType);
6303 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6304 ConvertedArgs.push_back(AllArgs[i]);
6305 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006306}
6307
Anders Carlsson20d45d22009-12-12 00:32:00 +00006308static inline bool
6309CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6310 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006311 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006312 if (isa<NamespaceDecl>(DC)) {
6313 return SemaRef.Diag(FnDecl->getLocation(),
6314 diag::err_operator_new_delete_declared_in_namespace)
6315 << FnDecl->getDeclName();
6316 }
6317
6318 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006319 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006320 return SemaRef.Diag(FnDecl->getLocation(),
6321 diag::err_operator_new_delete_declared_static)
6322 << FnDecl->getDeclName();
6323 }
6324
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006325 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006326}
6327
Anders Carlsson156c78e2009-12-13 17:53:43 +00006328static inline bool
6329CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6330 CanQualType ExpectedResultType,
6331 CanQualType ExpectedFirstParamType,
6332 unsigned DependentParamTypeDiag,
6333 unsigned InvalidParamTypeDiag) {
6334 QualType ResultType =
6335 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6336
6337 // Check that the result type is not dependent.
6338 if (ResultType->isDependentType())
6339 return SemaRef.Diag(FnDecl->getLocation(),
6340 diag::err_operator_new_delete_dependent_result_type)
6341 << FnDecl->getDeclName() << ExpectedResultType;
6342
6343 // Check that the result type is what we expect.
6344 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6345 return SemaRef.Diag(FnDecl->getLocation(),
6346 diag::err_operator_new_delete_invalid_result_type)
6347 << FnDecl->getDeclName() << ExpectedResultType;
6348
6349 // A function template must have at least 2 parameters.
6350 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6351 return SemaRef.Diag(FnDecl->getLocation(),
6352 diag::err_operator_new_delete_template_too_few_parameters)
6353 << FnDecl->getDeclName();
6354
6355 // The function decl must have at least 1 parameter.
6356 if (FnDecl->getNumParams() == 0)
6357 return SemaRef.Diag(FnDecl->getLocation(),
6358 diag::err_operator_new_delete_too_few_parameters)
6359 << FnDecl->getDeclName();
6360
6361 // Check the the first parameter type is not dependent.
6362 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6363 if (FirstParamType->isDependentType())
6364 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6365 << FnDecl->getDeclName() << ExpectedFirstParamType;
6366
6367 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006368 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006369 ExpectedFirstParamType)
6370 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6371 << FnDecl->getDeclName() << ExpectedFirstParamType;
6372
6373 return false;
6374}
6375
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006376static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006377CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006378 // C++ [basic.stc.dynamic.allocation]p1:
6379 // A program is ill-formed if an allocation function is declared in a
6380 // namespace scope other than global scope or declared static in global
6381 // scope.
6382 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6383 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006384
6385 CanQualType SizeTy =
6386 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6387
6388 // C++ [basic.stc.dynamic.allocation]p1:
6389 // The return type shall be void*. The first parameter shall have type
6390 // std::size_t.
6391 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6392 SizeTy,
6393 diag::err_operator_new_dependent_param_type,
6394 diag::err_operator_new_param_type))
6395 return true;
6396
6397 // C++ [basic.stc.dynamic.allocation]p1:
6398 // The first parameter shall not have an associated default argument.
6399 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006400 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006401 diag::err_operator_new_default_arg)
6402 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6403
6404 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006405}
6406
6407static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006408CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6409 // C++ [basic.stc.dynamic.deallocation]p1:
6410 // A program is ill-formed if deallocation functions are declared in a
6411 // namespace scope other than global scope or declared static in global
6412 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006413 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6414 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006415
6416 // C++ [basic.stc.dynamic.deallocation]p2:
6417 // Each deallocation function shall return void and its first parameter
6418 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006419 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6420 SemaRef.Context.VoidPtrTy,
6421 diag::err_operator_delete_dependent_param_type,
6422 diag::err_operator_delete_param_type))
6423 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006424
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006425 return false;
6426}
6427
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006428/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6429/// of this overloaded operator is well-formed. If so, returns false;
6430/// otherwise, emits appropriate diagnostics and returns true.
6431bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006432 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006433 "Expected an overloaded operator declaration");
6434
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006435 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6436
Mike Stump1eb44332009-09-09 15:08:12 +00006437 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006438 // The allocation and deallocation functions, operator new,
6439 // operator new[], operator delete and operator delete[], are
6440 // described completely in 3.7.3. The attributes and restrictions
6441 // found in the rest of this subclause do not apply to them unless
6442 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006443 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006444 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006445
Anders Carlssona3ccda52009-12-12 00:26:23 +00006446 if (Op == OO_New || Op == OO_Array_New)
6447 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006448
6449 // C++ [over.oper]p6:
6450 // An operator function shall either be a non-static member
6451 // function or be a non-member function and have at least one
6452 // parameter whose type is a class, a reference to a class, an
6453 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006454 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6455 if (MethodDecl->isStatic())
6456 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006457 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006458 } else {
6459 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006460 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6461 ParamEnd = FnDecl->param_end();
6462 Param != ParamEnd; ++Param) {
6463 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006464 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6465 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006466 ClassOrEnumParam = true;
6467 break;
6468 }
6469 }
6470
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006471 if (!ClassOrEnumParam)
6472 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006473 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006474 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006475 }
6476
6477 // C++ [over.oper]p8:
6478 // An operator function cannot have default arguments (8.3.6),
6479 // except where explicitly stated below.
6480 //
Mike Stump1eb44332009-09-09 15:08:12 +00006481 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006482 // (C++ [over.call]p1).
6483 if (Op != OO_Call) {
6484 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6485 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006486 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006487 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006488 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006489 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006490 }
6491 }
6492
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006493 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6494 { false, false, false }
6495#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6496 , { Unary, Binary, MemberOnly }
6497#include "clang/Basic/OperatorKinds.def"
6498 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006499
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006500 bool CanBeUnaryOperator = OperatorUses[Op][0];
6501 bool CanBeBinaryOperator = OperatorUses[Op][1];
6502 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006503
6504 // C++ [over.oper]p8:
6505 // [...] Operator functions cannot have more or fewer parameters
6506 // than the number required for the corresponding operator, as
6507 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006508 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006509 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006510 if (Op != OO_Call &&
6511 ((NumParams == 1 && !CanBeUnaryOperator) ||
6512 (NumParams == 2 && !CanBeBinaryOperator) ||
6513 (NumParams < 1) || (NumParams > 2))) {
6514 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006515 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006516 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006517 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006518 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006519 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006520 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006521 assert(CanBeBinaryOperator &&
6522 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006523 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006524 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006525
Chris Lattner416e46f2008-11-21 07:57:12 +00006526 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006527 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006528 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006529
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006530 // Overloaded operators other than operator() cannot be variadic.
6531 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006532 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006533 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006534 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006535 }
6536
6537 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006538 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6539 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006540 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006541 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006542 }
6543
6544 // C++ [over.inc]p1:
6545 // The user-defined function called operator++ implements the
6546 // prefix and postfix ++ operator. If this function is a member
6547 // function with no parameters, or a non-member function with one
6548 // parameter of class or enumeration type, it defines the prefix
6549 // increment operator ++ for objects of that type. If the function
6550 // is a member function with one parameter (which shall be of type
6551 // int) or a non-member function with two parameters (the second
6552 // of which shall be of type int), it defines the postfix
6553 // increment operator ++ for objects of that type.
6554 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6555 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6556 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006557 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006558 ParamIsInt = BT->getKind() == BuiltinType::Int;
6559
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006560 if (!ParamIsInt)
6561 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006562 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006563 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006564 }
6565
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006566 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006567}
Chris Lattner5a003a42008-12-17 07:09:26 +00006568
Sean Hunta6c058d2010-01-13 09:01:02 +00006569/// CheckLiteralOperatorDeclaration - Check whether the declaration
6570/// of this literal operator function is well-formed. If so, returns
6571/// false; otherwise, emits appropriate diagnostics and returns true.
6572bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6573 DeclContext *DC = FnDecl->getDeclContext();
6574 Decl::Kind Kind = DC->getDeclKind();
6575 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6576 Kind != Decl::LinkageSpec) {
6577 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6578 << FnDecl->getDeclName();
6579 return true;
6580 }
6581
6582 bool Valid = false;
6583
Sean Hunt216c2782010-04-07 23:11:06 +00006584 // template <char...> type operator "" name() is the only valid template
6585 // signature, and the only valid signature with no parameters.
6586 if (FnDecl->param_size() == 0) {
6587 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6588 // Must have only one template parameter
6589 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6590 if (Params->size() == 1) {
6591 NonTypeTemplateParmDecl *PmDecl =
6592 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006593
Sean Hunt216c2782010-04-07 23:11:06 +00006594 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006595 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6596 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6597 Valid = true;
6598 }
6599 }
6600 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006601 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006602 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6603
Sean Hunta6c058d2010-01-13 09:01:02 +00006604 QualType T = (*Param)->getType();
6605
Sean Hunt30019c02010-04-07 22:57:35 +00006606 // unsigned long long int, long double, and any character type are allowed
6607 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006608 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6609 Context.hasSameType(T, Context.LongDoubleTy) ||
6610 Context.hasSameType(T, Context.CharTy) ||
6611 Context.hasSameType(T, Context.WCharTy) ||
6612 Context.hasSameType(T, Context.Char16Ty) ||
6613 Context.hasSameType(T, Context.Char32Ty)) {
6614 if (++Param == FnDecl->param_end())
6615 Valid = true;
6616 goto FinishedParams;
6617 }
6618
Sean Hunt30019c02010-04-07 22:57:35 +00006619 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006620 const PointerType *PT = T->getAs<PointerType>();
6621 if (!PT)
6622 goto FinishedParams;
6623 T = PT->getPointeeType();
6624 if (!T.isConstQualified())
6625 goto FinishedParams;
6626 T = T.getUnqualifiedType();
6627
6628 // Move on to the second parameter;
6629 ++Param;
6630
6631 // If there is no second parameter, the first must be a const char *
6632 if (Param == FnDecl->param_end()) {
6633 if (Context.hasSameType(T, Context.CharTy))
6634 Valid = true;
6635 goto FinishedParams;
6636 }
6637
6638 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6639 // are allowed as the first parameter to a two-parameter function
6640 if (!(Context.hasSameType(T, Context.CharTy) ||
6641 Context.hasSameType(T, Context.WCharTy) ||
6642 Context.hasSameType(T, Context.Char16Ty) ||
6643 Context.hasSameType(T, Context.Char32Ty)))
6644 goto FinishedParams;
6645
6646 // The second and final parameter must be an std::size_t
6647 T = (*Param)->getType().getUnqualifiedType();
6648 if (Context.hasSameType(T, Context.getSizeType()) &&
6649 ++Param == FnDecl->param_end())
6650 Valid = true;
6651 }
6652
6653 // FIXME: This diagnostic is absolutely terrible.
6654FinishedParams:
6655 if (!Valid) {
6656 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6657 << FnDecl->getDeclName();
6658 return true;
6659 }
6660
6661 return false;
6662}
6663
Douglas Gregor074149e2009-01-05 19:45:36 +00006664/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6665/// linkage specification, including the language and (if present)
6666/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6667/// the location of the language string literal, which is provided
6668/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6669/// the '{' brace. Otherwise, this linkage specification does not
6670/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006671Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6672 SourceLocation LangLoc,
6673 llvm::StringRef Lang,
6674 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006675 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006676 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006677 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006678 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006679 Language = LinkageSpecDecl::lang_cxx;
6680 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006681 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006682 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006683 }
Mike Stump1eb44332009-09-09 15:08:12 +00006684
Chris Lattnercc98eac2008-12-17 07:13:27 +00006685 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006686
Douglas Gregor074149e2009-01-05 19:45:36 +00006687 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006688 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006689 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006690 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006691 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006692}
6693
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006694/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006695/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6696/// valid, it's the position of the closing '}' brace in a linkage
6697/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006698Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006699 Decl *LinkageSpec,
6700 SourceLocation RBraceLoc) {
6701 if (LinkageSpec) {
6702 if (RBraceLoc.isValid()) {
6703 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6704 LSDecl->setRBraceLoc(RBraceLoc);
6705 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006706 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006707 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006708 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006709}
6710
Douglas Gregord308e622009-05-18 20:51:54 +00006711/// \brief Perform semantic analysis for the variable declaration that
6712/// occurs within a C++ catch clause, returning the newly-created
6713/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006714VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006715 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006716 SourceLocation StartLoc,
6717 SourceLocation Loc,
6718 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00006719 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006720 QualType ExDeclType = TInfo->getType();
6721
Sebastian Redl4b07b292008-12-22 19:15:10 +00006722 // Arrays and functions decay.
6723 if (ExDeclType->isArrayType())
6724 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6725 else if (ExDeclType->isFunctionType())
6726 ExDeclType = Context.getPointerType(ExDeclType);
6727
6728 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6729 // The exception-declaration shall not denote a pointer or reference to an
6730 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006731 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006732 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006733 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006734 Invalid = true;
6735 }
Douglas Gregord308e622009-05-18 20:51:54 +00006736
Douglas Gregora2762912010-03-08 01:47:36 +00006737 // GCC allows catching pointers and references to incomplete types
6738 // as an extension; so do we, but we warn by default.
6739
Sebastian Redl4b07b292008-12-22 19:15:10 +00006740 QualType BaseType = ExDeclType;
6741 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006742 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006743 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006744 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006745 BaseType = Ptr->getPointeeType();
6746 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006747 DK = diag::ext_catch_incomplete_ptr;
6748 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006749 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006750 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006751 BaseType = Ref->getPointeeType();
6752 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006753 DK = diag::ext_catch_incomplete_ref;
6754 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006755 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006756 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006757 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6758 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006759 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006760
Mike Stump1eb44332009-09-09 15:08:12 +00006761 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006762 RequireNonAbstractType(Loc, ExDeclType,
6763 diag::err_abstract_type_in_decl,
6764 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006765 Invalid = true;
6766
John McCall5a180392010-07-24 00:37:23 +00006767 // Only the non-fragile NeXT runtime currently supports C++ catches
6768 // of ObjC types, and no runtime supports catching ObjC types by value.
6769 if (!Invalid && getLangOptions().ObjC1) {
6770 QualType T = ExDeclType;
6771 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6772 T = RT->getPointeeType();
6773
6774 if (T->isObjCObjectType()) {
6775 Diag(Loc, diag::err_objc_object_catch);
6776 Invalid = true;
6777 } else if (T->isObjCObjectPointerType()) {
6778 if (!getLangOptions().NeXTRuntime) {
6779 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6780 Invalid = true;
6781 } else if (!getLangOptions().ObjCNonFragileABI) {
6782 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6783 Invalid = true;
6784 }
6785 }
6786 }
6787
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006788 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6789 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006790 ExDecl->setExceptionVariable(true);
6791
Douglas Gregor6d182892010-03-05 23:38:39 +00006792 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00006793 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00006794 // C++ [except.handle]p16:
6795 // The object declared in an exception-declaration or, if the
6796 // exception-declaration does not specify a name, a temporary (12.2) is
6797 // copy-initialized (8.5) from the exception object. [...]
6798 // The object is destroyed when the handler exits, after the destruction
6799 // of any automatic objects initialized within the handler.
6800 //
6801 // We just pretend to initialize the object with itself, then make sure
6802 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00006803 QualType initType = ExDeclType;
6804
6805 InitializedEntity entity =
6806 InitializedEntity::InitializeVariable(ExDecl);
6807 InitializationKind initKind =
6808 InitializationKind::CreateCopy(Loc, SourceLocation());
6809
6810 Expr *opaqueValue =
6811 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6812 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6813 ExprResult result = sequence.Perform(*this, entity, initKind,
6814 MultiExprArg(&opaqueValue, 1));
6815 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00006816 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00006817 else {
6818 // If the constructor used was non-trivial, set this as the
6819 // "initializer".
6820 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6821 if (!construct->getConstructor()->isTrivial()) {
6822 Expr *init = MaybeCreateExprWithCleanups(construct);
6823 ExDecl->setInit(init);
6824 }
6825
6826 // And make sure it's destructable.
6827 FinalizeVarWithDestructor(ExDecl, recordType);
6828 }
Douglas Gregor6d182892010-03-05 23:38:39 +00006829 }
6830 }
6831
Douglas Gregord308e622009-05-18 20:51:54 +00006832 if (Invalid)
6833 ExDecl->setInvalidDecl();
6834
6835 return ExDecl;
6836}
6837
6838/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6839/// handler.
John McCalld226f652010-08-21 09:40:31 +00006840Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006841 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006842 bool Invalid = D.isInvalidType();
6843
6844 // Check for unexpanded parameter packs.
6845 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6846 UPPC_ExceptionType)) {
6847 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6848 D.getIdentifierLoc());
6849 Invalid = true;
6850 }
6851
Sebastian Redl4b07b292008-12-22 19:15:10 +00006852 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006853 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006854 LookupOrdinaryName,
6855 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006856 // The scope should be freshly made just for us. There is just no way
6857 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006858 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006859 if (PrevDecl->isTemplateParameter()) {
6860 // Maybe we will complain about the shadowed template parameter.
6861 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006862 }
6863 }
6864
Chris Lattnereaaebc72009-04-25 08:06:05 +00006865 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006866 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6867 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006868 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006869 }
6870
Douglas Gregor83cb9422010-09-09 17:09:21 +00006871 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006872 D.getSourceRange().getBegin(),
6873 D.getIdentifierLoc(),
6874 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00006875 if (Invalid)
6876 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006877
Sebastian Redl4b07b292008-12-22 19:15:10 +00006878 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006879 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006880 PushOnScopeChains(ExDecl, S);
6881 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006882 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006883
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006884 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006885 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006886}
Anders Carlssonfb311762009-03-14 00:25:26 +00006887
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006888Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006889 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006890 Expr *AssertMessageExpr_,
6891 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00006892 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006893
Anders Carlssonc3082412009-03-14 00:33:21 +00006894 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6895 llvm::APSInt Value(32);
6896 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006897 Diag(StaticAssertLoc,
6898 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00006899 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006900 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006901 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006902
Anders Carlssonc3082412009-03-14 00:33:21 +00006903 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006904 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006905 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006906 }
6907 }
Mike Stump1eb44332009-09-09 15:08:12 +00006908
Douglas Gregor399ad972010-12-15 23:55:21 +00006909 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6910 return 0;
6911
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006912 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
6913 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00006914
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006915 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006916 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006917}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006918
Douglas Gregor1d869352010-04-07 16:53:43 +00006919/// \brief Perform semantic analysis of the given friend type declaration.
6920///
6921/// \returns A friend declaration that.
6922FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6923 TypeSourceInfo *TSInfo) {
6924 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6925
6926 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006927 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006928
Douglas Gregor06245bf2010-04-07 17:57:12 +00006929 if (!getLangOptions().CPlusPlus0x) {
6930 // C++03 [class.friend]p2:
6931 // An elaborated-type-specifier shall be used in a friend declaration
6932 // for a class.*
6933 //
6934 // * The class-key of the elaborated-type-specifier is required.
6935 if (!ActiveTemplateInstantiations.empty()) {
6936 // Do not complain about the form of friend template types during
6937 // template instantiation; we will already have complained when the
6938 // template was declared.
6939 } else if (!T->isElaboratedTypeSpecifier()) {
6940 // If we evaluated the type to a record type, suggest putting
6941 // a tag in front.
6942 if (const RecordType *RT = T->getAs<RecordType>()) {
6943 RecordDecl *RD = RT->getDecl();
6944
6945 std::string InsertionText = std::string(" ") + RD->getKindName();
6946
6947 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6948 << (unsigned) RD->getTagKind()
6949 << T
6950 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6951 InsertionText);
6952 } else {
6953 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6954 << T
6955 << SourceRange(FriendLoc, TypeRange.getEnd());
6956 }
6957 } else if (T->getAs<EnumType>()) {
6958 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006959 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006960 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006961 }
6962 }
6963
Douglas Gregor06245bf2010-04-07 17:57:12 +00006964 // C++0x [class.friend]p3:
6965 // If the type specifier in a friend declaration designates a (possibly
6966 // cv-qualified) class type, that class is declared as a friend; otherwise,
6967 // the friend declaration is ignored.
6968
6969 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6970 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006971
6972 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6973}
6974
John McCall9a34edb2010-10-19 01:40:49 +00006975/// Handle a friend tag declaration where the scope specifier was
6976/// templated.
6977Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6978 unsigned TagSpec, SourceLocation TagLoc,
6979 CXXScopeSpec &SS,
6980 IdentifierInfo *Name, SourceLocation NameLoc,
6981 AttributeList *Attr,
6982 MultiTemplateParamsArg TempParamLists) {
6983 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6984
6985 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00006986 bool Invalid = false;
6987
6988 if (TemplateParameterList *TemplateParams
6989 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6990 TempParamLists.get(),
6991 TempParamLists.size(),
6992 /*friend*/ true,
6993 isExplicitSpecialization,
6994 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00006995 if (TemplateParams->size() > 0) {
6996 // This is a declaration of a class template.
6997 if (Invalid)
6998 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00006999
John McCall9a34edb2010-10-19 01:40:49 +00007000 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7001 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007002 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007003 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007004 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007005 } else {
7006 // The "template<>" header is extraneous.
7007 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7008 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7009 isExplicitSpecialization = true;
7010 }
7011 }
7012
7013 if (Invalid) return 0;
7014
7015 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7016
7017 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007018 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007019 if (TempParamLists.get()[I]->size()) {
7020 isAllExplicitSpecializations = false;
7021 break;
7022 }
7023 }
7024
7025 // FIXME: don't ignore attributes.
7026
7027 // If it's explicit specializations all the way down, just forget
7028 // about the template header and build an appropriate non-templated
7029 // friend. TODO: for source fidelity, remember the headers.
7030 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007031 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007032 ElaboratedTypeKeyword Keyword
7033 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007034 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007035 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007036 if (T.isNull())
7037 return 0;
7038
7039 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7040 if (isa<DependentNameType>(T)) {
7041 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7042 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007043 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007044 TL.setNameLoc(NameLoc);
7045 } else {
7046 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7047 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007048 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007049 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7050 }
7051
7052 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7053 TSI, FriendLoc);
7054 Friend->setAccess(AS_public);
7055 CurContext->addDecl(Friend);
7056 return Friend;
7057 }
7058
7059 // Handle the case of a templated-scope friend class. e.g.
7060 // template <class T> class A<T>::B;
7061 // FIXME: we don't support these right now.
7062 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7063 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7064 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7065 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7066 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007067 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007068 TL.setNameLoc(NameLoc);
7069
7070 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7071 TSI, FriendLoc);
7072 Friend->setAccess(AS_public);
7073 Friend->setUnsupportedFriend(true);
7074 CurContext->addDecl(Friend);
7075 return Friend;
7076}
7077
7078
John McCalldd4a3b02009-09-16 22:47:08 +00007079/// Handle a friend type declaration. This works in tandem with
7080/// ActOnTag.
7081///
7082/// Notes on friend class templates:
7083///
7084/// We generally treat friend class declarations as if they were
7085/// declaring a class. So, for example, the elaborated type specifier
7086/// in a friend declaration is required to obey the restrictions of a
7087/// class-head (i.e. no typedefs in the scope chain), template
7088/// parameters are required to match up with simple template-ids, &c.
7089/// However, unlike when declaring a template specialization, it's
7090/// okay to refer to a template specialization without an empty
7091/// template parameter declaration, e.g.
7092/// friend class A<T>::B<unsigned>;
7093/// We permit this as a special case; if there are any template
7094/// parameters present at all, require proper matching, i.e.
7095/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007096Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007097 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007098 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007099
7100 assert(DS.isFriendSpecified());
7101 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7102
John McCalldd4a3b02009-09-16 22:47:08 +00007103 // Try to convert the decl specifier to a type. This works for
7104 // friend templates because ActOnTag never produces a ClassTemplateDecl
7105 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007106 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007107 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7108 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007109 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007110 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007111
Douglas Gregor6ccab972010-12-16 01:14:37 +00007112 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7113 return 0;
7114
John McCalldd4a3b02009-09-16 22:47:08 +00007115 // This is definitely an error in C++98. It's probably meant to
7116 // be forbidden in C++0x, too, but the specification is just
7117 // poorly written.
7118 //
7119 // The problem is with declarations like the following:
7120 // template <T> friend A<T>::foo;
7121 // where deciding whether a class C is a friend or not now hinges
7122 // on whether there exists an instantiation of A that causes
7123 // 'foo' to equal C. There are restrictions on class-heads
7124 // (which we declare (by fiat) elaborated friend declarations to
7125 // be) that makes this tractable.
7126 //
7127 // FIXME: handle "template <> friend class A<T>;", which
7128 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007129 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007130 Diag(Loc, diag::err_tagless_friend_type_template)
7131 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007132 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007133 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007134
John McCall02cace72009-08-28 07:59:38 +00007135 // C++98 [class.friend]p1: A friend of a class is a function
7136 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007137 // This is fixed in DR77, which just barely didn't make the C++03
7138 // deadline. It's also a very silly restriction that seriously
7139 // affects inner classes and which nobody else seems to implement;
7140 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007141 //
7142 // But note that we could warn about it: it's always useless to
7143 // friend one of your own members (it's not, however, worthless to
7144 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007145
John McCalldd4a3b02009-09-16 22:47:08 +00007146 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007147 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007148 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007149 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007150 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007151 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007152 DS.getFriendSpecLoc());
7153 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007154 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7155
7156 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007157 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007158
John McCalldd4a3b02009-09-16 22:47:08 +00007159 D->setAccess(AS_public);
7160 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007161
John McCalld226f652010-08-21 09:40:31 +00007162 return D;
John McCall02cace72009-08-28 07:59:38 +00007163}
7164
John McCall337ec3d2010-10-12 23:13:28 +00007165Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7166 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007167 const DeclSpec &DS = D.getDeclSpec();
7168
7169 assert(DS.isFriendSpecified());
7170 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7171
7172 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007173 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7174 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007175
7176 // C++ [class.friend]p1
7177 // A friend of a class is a function or class....
7178 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007179 // It *doesn't* see through dependent types, which is correct
7180 // according to [temp.arg.type]p3:
7181 // If a declaration acquires a function type through a
7182 // type dependent on a template-parameter and this causes
7183 // a declaration that does not use the syntactic form of a
7184 // function declarator to have a function type, the program
7185 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007186 if (!T->isFunctionType()) {
7187 Diag(Loc, diag::err_unexpected_friend);
7188
7189 // It might be worthwhile to try to recover by creating an
7190 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007191 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007192 }
7193
7194 // C++ [namespace.memdef]p3
7195 // - If a friend declaration in a non-local class first declares a
7196 // class or function, the friend class or function is a member
7197 // of the innermost enclosing namespace.
7198 // - The name of the friend is not found by simple name lookup
7199 // until a matching declaration is provided in that namespace
7200 // scope (either before or after the class declaration granting
7201 // friendship).
7202 // - If a friend function is called, its name may be found by the
7203 // name lookup that considers functions from namespaces and
7204 // classes associated with the types of the function arguments.
7205 // - When looking for a prior declaration of a class or a function
7206 // declared as a friend, scopes outside the innermost enclosing
7207 // namespace scope are not considered.
7208
John McCall337ec3d2010-10-12 23:13:28 +00007209 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007210 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7211 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007212 assert(Name);
7213
Douglas Gregor6ccab972010-12-16 01:14:37 +00007214 // Check for unexpanded parameter packs.
7215 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7216 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7217 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7218 return 0;
7219
John McCall67d1a672009-08-06 02:15:43 +00007220 // The context we found the declaration in, or in which we should
7221 // create the declaration.
7222 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007223 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007224 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007225 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007226
John McCall337ec3d2010-10-12 23:13:28 +00007227 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007228
John McCall337ec3d2010-10-12 23:13:28 +00007229 // There are four cases here.
7230 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007231 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007232 // there as appropriate.
7233 // Recover from invalid scope qualifiers as if they just weren't there.
7234 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007235 // C++0x [namespace.memdef]p3:
7236 // If the name in a friend declaration is neither qualified nor
7237 // a template-id and the declaration is a function or an
7238 // elaborated-type-specifier, the lookup to determine whether
7239 // the entity has been previously declared shall not consider
7240 // any scopes outside the innermost enclosing namespace.
7241 // C++0x [class.friend]p11:
7242 // If a friend declaration appears in a local class and the name
7243 // specified is an unqualified name, a prior declaration is
7244 // looked up without considering scopes that are outside the
7245 // innermost enclosing non-class scope. For a friend function
7246 // declaration, if there is no prior declaration, the program is
7247 // ill-formed.
7248 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007249 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007250
John McCall29ae6e52010-10-13 05:45:15 +00007251 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007252 DC = CurContext;
7253 while (true) {
7254 // Skip class contexts. If someone can cite chapter and verse
7255 // for this behavior, that would be nice --- it's what GCC and
7256 // EDG do, and it seems like a reasonable intent, but the spec
7257 // really only says that checks for unqualified existing
7258 // declarations should stop at the nearest enclosing namespace,
7259 // not that they should only consider the nearest enclosing
7260 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007261 while (DC->isRecord())
7262 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007263
John McCall68263142009-11-18 22:49:29 +00007264 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007265
7266 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007267 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007268 break;
John McCall29ae6e52010-10-13 05:45:15 +00007269
John McCall8a407372010-10-14 22:22:28 +00007270 if (isTemplateId) {
7271 if (isa<TranslationUnitDecl>(DC)) break;
7272 } else {
7273 if (DC->isFileContext()) break;
7274 }
John McCall67d1a672009-08-06 02:15:43 +00007275 DC = DC->getParent();
7276 }
7277
7278 // C++ [class.friend]p1: A friend of a class is a function or
7279 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007280 // C++0x changes this for both friend types and functions.
7281 // Most C++ 98 compilers do seem to give an error here, so
7282 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007283 if (!Previous.empty() && DC->Equals(CurContext)
7284 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007285 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007286
John McCall380aaa42010-10-13 06:22:15 +00007287 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007288
John McCall337ec3d2010-10-12 23:13:28 +00007289 // - There's a non-dependent scope specifier, in which case we
7290 // compute it and do a previous lookup there for a function
7291 // or function template.
7292 } else if (!SS.getScopeRep()->isDependent()) {
7293 DC = computeDeclContext(SS);
7294 if (!DC) return 0;
7295
7296 if (RequireCompleteDeclContext(SS, DC)) return 0;
7297
7298 LookupQualifiedName(Previous, DC);
7299
7300 // Ignore things found implicitly in the wrong scope.
7301 // TODO: better diagnostics for this case. Suggesting the right
7302 // qualified scope would be nice...
7303 LookupResult::Filter F = Previous.makeFilter();
7304 while (F.hasNext()) {
7305 NamedDecl *D = F.next();
7306 if (!DC->InEnclosingNamespaceSetOf(
7307 D->getDeclContext()->getRedeclContext()))
7308 F.erase();
7309 }
7310 F.done();
7311
7312 if (Previous.empty()) {
7313 D.setInvalidType();
7314 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7315 return 0;
7316 }
7317
7318 // C++ [class.friend]p1: A friend of a class is a function or
7319 // class that is not a member of the class . . .
7320 if (DC->Equals(CurContext))
7321 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7322
7323 // - There's a scope specifier that does not match any template
7324 // parameter lists, in which case we use some arbitrary context,
7325 // create a method or method template, and wait for instantiation.
7326 // - There's a scope specifier that does match some template
7327 // parameter lists, which we don't handle right now.
7328 } else {
7329 DC = CurContext;
7330 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007331 }
7332
John McCall29ae6e52010-10-13 05:45:15 +00007333 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007334 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007335 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7336 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7337 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007338 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007339 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7340 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007341 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007342 }
John McCall67d1a672009-08-06 02:15:43 +00007343 }
7344
Douglas Gregor182ddf02009-09-28 00:08:27 +00007345 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007346 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007347 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007348 IsDefinition,
7349 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007350 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007351
Douglas Gregor182ddf02009-09-28 00:08:27 +00007352 assert(ND->getDeclContext() == DC);
7353 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007354
John McCallab88d972009-08-31 22:39:49 +00007355 // Add the function declaration to the appropriate lookup tables,
7356 // adjusting the redeclarations list as necessary. We don't
7357 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007358 //
John McCallab88d972009-08-31 22:39:49 +00007359 // Also update the scope-based lookup if the target context's
7360 // lookup context is in lexical scope.
7361 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007362 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007363 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007364 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007365 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007366 }
John McCall02cace72009-08-28 07:59:38 +00007367
7368 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007369 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007370 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007371 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007372 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007373
John McCall337ec3d2010-10-12 23:13:28 +00007374 if (ND->isInvalidDecl())
7375 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007376 else {
7377 FunctionDecl *FD;
7378 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7379 FD = FTD->getTemplatedDecl();
7380 else
7381 FD = cast<FunctionDecl>(ND);
7382
7383 // Mark templated-scope function declarations as unsupported.
7384 if (FD->getNumTemplateParameterLists())
7385 FrD->setUnsupportedFriend(true);
7386 }
John McCall337ec3d2010-10-12 23:13:28 +00007387
John McCalld226f652010-08-21 09:40:31 +00007388 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007389}
7390
John McCalld226f652010-08-21 09:40:31 +00007391void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7392 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007393
Sebastian Redl50de12f2009-03-24 22:27:57 +00007394 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7395 if (!Fn) {
7396 Diag(DelLoc, diag::err_deleted_non_function);
7397 return;
7398 }
7399 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7400 Diag(DelLoc, diag::err_deleted_decl_not_first);
7401 Diag(Prev->getLocation(), diag::note_previous_declaration);
7402 // If the declaration wasn't the first, we delete the function anyway for
7403 // recovery.
7404 }
7405 Fn->setDeleted();
7406}
Sebastian Redl13e88542009-04-27 21:33:24 +00007407
7408static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007409 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007410 Stmt *SubStmt = *CI;
7411 if (!SubStmt)
7412 continue;
7413 if (isa<ReturnStmt>(SubStmt))
7414 Self.Diag(SubStmt->getSourceRange().getBegin(),
7415 diag::err_return_in_constructor_handler);
7416 if (!isa<Expr>(SubStmt))
7417 SearchForReturnInStmt(Self, SubStmt);
7418 }
7419}
7420
7421void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7422 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7423 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7424 SearchForReturnInStmt(*this, Handler);
7425 }
7426}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007427
Mike Stump1eb44332009-09-09 15:08:12 +00007428bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007429 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007430 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7431 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007432
Chandler Carruth73857792010-02-15 11:53:20 +00007433 if (Context.hasSameType(NewTy, OldTy) ||
7434 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007435 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007436
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007437 // Check if the return types are covariant
7438 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007439
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007440 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007441 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7442 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007443 NewClassTy = NewPT->getPointeeType();
7444 OldClassTy = OldPT->getPointeeType();
7445 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007446 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7447 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7448 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7449 NewClassTy = NewRT->getPointeeType();
7450 OldClassTy = OldRT->getPointeeType();
7451 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007452 }
7453 }
Mike Stump1eb44332009-09-09 15:08:12 +00007454
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007455 // The return types aren't either both pointers or references to a class type.
7456 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007457 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007458 diag::err_different_return_type_for_overriding_virtual_function)
7459 << New->getDeclName() << NewTy << OldTy;
7460 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007461
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007462 return true;
7463 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007464
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007465 // C++ [class.virtual]p6:
7466 // If the return type of D::f differs from the return type of B::f, the
7467 // class type in the return type of D::f shall be complete at the point of
7468 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007469 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7470 if (!RT->isBeingDefined() &&
7471 RequireCompleteType(New->getLocation(), NewClassTy,
7472 PDiag(diag::err_covariant_return_incomplete)
7473 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007474 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007475 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007476
Douglas Gregora4923eb2009-11-16 21:35:15 +00007477 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007478 // Check if the new class derives from the old class.
7479 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7480 Diag(New->getLocation(),
7481 diag::err_covariant_return_not_derived)
7482 << New->getDeclName() << NewTy << OldTy;
7483 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7484 return true;
7485 }
Mike Stump1eb44332009-09-09 15:08:12 +00007486
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007487 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007488 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007489 diag::err_covariant_return_inaccessible_base,
7490 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7491 // FIXME: Should this point to the return type?
7492 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007493 // FIXME: this note won't trigger for delayed access control
7494 // diagnostics, and it's impossible to get an undelayed error
7495 // here from access control during the original parse because
7496 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007497 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7498 return true;
7499 }
7500 }
Mike Stump1eb44332009-09-09 15:08:12 +00007501
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007502 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007503 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007504 Diag(New->getLocation(),
7505 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007506 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007507 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7508 return true;
7509 };
Mike Stump1eb44332009-09-09 15:08:12 +00007510
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007511
7512 // The new class type must have the same or less qualifiers as the old type.
7513 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7514 Diag(New->getLocation(),
7515 diag::err_covariant_return_type_class_type_more_qualified)
7516 << New->getDeclName() << NewTy << OldTy;
7517 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7518 return true;
7519 };
Mike Stump1eb44332009-09-09 15:08:12 +00007520
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007521 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007522}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007523
Douglas Gregor4ba31362009-12-01 17:24:26 +00007524/// \brief Mark the given method pure.
7525///
7526/// \param Method the method to be marked pure.
7527///
7528/// \param InitRange the source range that covers the "0" initializer.
7529bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00007530 SourceLocation EndLoc = InitRange.getEnd();
7531 if (EndLoc.isValid())
7532 Method->setRangeEnd(EndLoc);
7533
Douglas Gregor4ba31362009-12-01 17:24:26 +00007534 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7535 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007536 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00007537 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00007538
7539 if (!Method->isInvalidDecl())
7540 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7541 << Method->getDeclName() << InitRange;
7542 return true;
7543}
7544
John McCall731ad842009-12-19 09:28:58 +00007545/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7546/// an initializer for the out-of-line declaration 'Dcl'. The scope
7547/// is a fresh scope pushed for just this purpose.
7548///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007549/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7550/// static data member of class X, names should be looked up in the scope of
7551/// class X.
John McCalld226f652010-08-21 09:40:31 +00007552void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007553 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007554 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007555
John McCall731ad842009-12-19 09:28:58 +00007556 // We should only get called for declarations with scope specifiers, like:
7557 // int foo::bar;
7558 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007559 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007560}
7561
7562/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007563/// initializer for the out-of-line declaration 'D'.
7564void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007565 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007566 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007567
John McCall731ad842009-12-19 09:28:58 +00007568 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007569 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007570}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007571
7572/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7573/// C++ if/switch/while/for statement.
7574/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007575DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007576 // C++ 6.4p2:
7577 // The declarator shall not specify a function or an array.
7578 // The type-specifier-seq shall not contain typedef and shall not declare a
7579 // new class or enumeration.
7580 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7581 "Parser allowed 'typedef' as storage class of condition decl.");
7582
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007583 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007584 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7585 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007586
7587 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7588 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7589 // would be created and CXXConditionDeclExpr wants a VarDecl.
7590 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7591 << D.getSourceRange();
7592 return DeclResult();
7593 } else if (OwnedTag && OwnedTag->isDefinition()) {
7594 // The type-specifier-seq shall not declare a new class or enumeration.
7595 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7596 }
7597
John McCalld226f652010-08-21 09:40:31 +00007598 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007599 if (!Dcl)
7600 return DeclResult();
7601
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007602 return Dcl;
7603}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007604
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007605void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7606 bool DefinitionRequired) {
7607 // Ignore any vtable uses in unevaluated operands or for classes that do
7608 // not have a vtable.
7609 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7610 CurContext->isDependentContext() ||
7611 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007612 return;
7613
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007614 // Try to insert this class into the map.
7615 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7616 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7617 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7618 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007619 // If we already had an entry, check to see if we are promoting this vtable
7620 // to required a definition. If so, we need to reappend to the VTableUses
7621 // list, since we may have already processed the first entry.
7622 if (DefinitionRequired && !Pos.first->second) {
7623 Pos.first->second = true;
7624 } else {
7625 // Otherwise, we can early exit.
7626 return;
7627 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007628 }
7629
7630 // Local classes need to have their virtual members marked
7631 // immediately. For all other classes, we mark their virtual members
7632 // at the end of the translation unit.
7633 if (Class->isLocalClass())
7634 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007635 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007636 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007637}
7638
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007639bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007640 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007641 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007642
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007643 // Note: The VTableUses vector could grow as a result of marking
7644 // the members of a class as "used", so we check the size each
7645 // time through the loop and prefer indices (with are stable) to
7646 // iterators (which are not).
7647 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007648 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007649 if (!Class)
7650 continue;
7651
7652 SourceLocation Loc = VTableUses[I].second;
7653
7654 // If this class has a key function, but that key function is
7655 // defined in another translation unit, we don't need to emit the
7656 // vtable even though we're using it.
7657 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007658 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007659 switch (KeyFunction->getTemplateSpecializationKind()) {
7660 case TSK_Undeclared:
7661 case TSK_ExplicitSpecialization:
7662 case TSK_ExplicitInstantiationDeclaration:
7663 // The key function is in another translation unit.
7664 continue;
7665
7666 case TSK_ExplicitInstantiationDefinition:
7667 case TSK_ImplicitInstantiation:
7668 // We will be instantiating the key function.
7669 break;
7670 }
7671 } else if (!KeyFunction) {
7672 // If we have a class with no key function that is the subject
7673 // of an explicit instantiation declaration, suppress the
7674 // vtable; it will live with the explicit instantiation
7675 // definition.
7676 bool IsExplicitInstantiationDeclaration
7677 = Class->getTemplateSpecializationKind()
7678 == TSK_ExplicitInstantiationDeclaration;
7679 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7680 REnd = Class->redecls_end();
7681 R != REnd; ++R) {
7682 TemplateSpecializationKind TSK
7683 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7684 if (TSK == TSK_ExplicitInstantiationDeclaration)
7685 IsExplicitInstantiationDeclaration = true;
7686 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7687 IsExplicitInstantiationDeclaration = false;
7688 break;
7689 }
7690 }
7691
7692 if (IsExplicitInstantiationDeclaration)
7693 continue;
7694 }
7695
7696 // Mark all of the virtual members of this class as referenced, so
7697 // that we can build a vtable. Then, tell the AST consumer that a
7698 // vtable for this class is required.
7699 MarkVirtualMembersReferenced(Loc, Class);
7700 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7701 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7702
7703 // Optionally warn if we're emitting a weak vtable.
7704 if (Class->getLinkage() == ExternalLinkage &&
7705 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007706 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007707 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7708 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007709 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007710 VTableUses.clear();
7711
Anders Carlssond6a637f2009-12-07 08:24:59 +00007712 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007713}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007714
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007715void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7716 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007717 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7718 e = RD->method_end(); i != e; ++i) {
7719 CXXMethodDecl *MD = *i;
7720
7721 // C++ [basic.def.odr]p2:
7722 // [...] A virtual member function is used if it is not pure. [...]
7723 if (MD->isVirtual() && !MD->isPure())
7724 MarkDeclarationReferenced(Loc, MD);
7725 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007726
7727 // Only classes that have virtual bases need a VTT.
7728 if (RD->getNumVBases() == 0)
7729 return;
7730
7731 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7732 e = RD->bases_end(); i != e; ++i) {
7733 const CXXRecordDecl *Base =
7734 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007735 if (Base->getNumVBases() == 0)
7736 continue;
7737 MarkVirtualMembersReferenced(Loc, Base);
7738 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007739}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007740
7741/// SetIvarInitializers - This routine builds initialization ASTs for the
7742/// Objective-C implementation whose ivars need be initialized.
7743void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7744 if (!getLangOptions().CPlusPlus)
7745 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007746 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007747 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7748 CollectIvarsToConstructOrDestruct(OID, ivars);
7749 if (ivars.empty())
7750 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007751 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007752 for (unsigned i = 0; i < ivars.size(); i++) {
7753 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007754 if (Field->isInvalidDecl())
7755 continue;
7756
Sean Huntcbb67482011-01-08 20:30:50 +00007757 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007758 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7759 InitializationKind InitKind =
7760 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7761
7762 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007763 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007764 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007765 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007766 // Note, MemberInit could actually come back empty if no initialization
7767 // is required (e.g., because it would call a trivial default constructor)
7768 if (!MemberInit.get() || MemberInit.isInvalid())
7769 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007770
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007771 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007772 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7773 SourceLocation(),
7774 MemberInit.takeAs<Expr>(),
7775 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007776 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007777
7778 // Be sure that the destructor is accessible and is marked as referenced.
7779 if (const RecordType *RecordTy
7780 = Context.getBaseElementType(Field->getType())
7781 ->getAs<RecordType>()) {
7782 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007783 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007784 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7785 CheckDestructorAccess(Field->getLocation(), Destructor,
7786 PDiag(diag::err_access_dtor_ivar)
7787 << Context.getBaseElementType(Field->getType()));
7788 }
7789 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007790 }
7791 ObjCImplementation->setIvarInitializers(Context,
7792 AllToInit.data(), AllToInit.size());
7793 }
7794}