blob: 7ae104a5423cb86acebbf198cc6a04766fa450e2 [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 Carlsson1d209272011-03-25 14:55:14 +0000566 // C++ [class]p3:
567 // If a class is marked final and it appears as a base-type-specifier in
568 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000569 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000570 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
571 << CXXBaseDecl->getDeclName();
572 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
573 << CXXBaseDecl->getDeclName();
574 return 0;
575 }
576
John McCall572fc622010-08-17 07:23:57 +0000577 if (BaseDecl->isInvalidDecl())
578 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000579
580 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000581 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000582 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000583 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000584}
585
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000586/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
587/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000588/// example:
589/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000590/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000591BaseResult
John McCalld226f652010-08-21 09:40:31 +0000592Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000593 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000594 ParsedType basetype, SourceLocation BaseLoc,
595 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000596 if (!classdecl)
597 return true;
598
Douglas Gregor40808ce2009-03-09 23:48:35 +0000599 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000600 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000601 if (!Class)
602 return true;
603
Nick Lewycky56062202010-07-26 16:56:01 +0000604 TypeSourceInfo *TInfo = 0;
605 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000606
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000607 if (EllipsisLoc.isInvalid() &&
608 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000609 UPPC_BaseType))
610 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000611
Douglas Gregor2943aed2009-03-03 04:44:36 +0000612 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000613 Virtual, Access, TInfo,
614 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000615 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000618}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000619
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620/// \brief Performs the actual work of attaching the given base class
621/// specifiers to a C++ class.
622bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
623 unsigned NumBases) {
624 if (NumBases == 0)
625 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000626
627 // Used to keep track of which base types we have already seen, so
628 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000629 // that the key is always the unqualified canonical type of the base
630 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000631 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
632
633 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000634 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000636 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000637 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000639 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000640 if (!Class->hasObjectMember()) {
641 if (const RecordType *FDTTy =
642 NewBaseType.getTypePtr()->getAs<RecordType>())
643 if (FDTTy->getDecl()->hasObjectMember())
644 Class->setHasObjectMember(true);
645 }
646
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000647 if (KnownBaseTypes[NewBaseType]) {
648 // C++ [class.mi]p3:
649 // A class shall not be specified as a direct base class of a
650 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000651 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000652 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000653 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000654 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000655
656 // Delete the duplicate base class specifier; we're going to
657 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000658 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000661 } else {
662 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000663 KnownBaseTypes[NewBaseType] = Bases[idx];
664 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000665 }
666 }
667
668 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000669 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000670
671 // Delete the remaining (good) base class specifiers, since their
672 // data has been copied into the CXXRecordDecl.
673 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000674 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000675
676 return Invalid;
677}
678
679/// ActOnBaseSpecifiers - Attach the given base specifiers to the
680/// class, after checking whether there are any duplicate base
681/// classes.
John McCalld226f652010-08-21 09:40:31 +0000682void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000683 unsigned NumBases) {
684 if (!ClassDecl || !Bases || !NumBases)
685 return;
686
687 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000688 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000689 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000690}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000691
John McCall3cb0ebd2010-03-10 03:28:59 +0000692static CXXRecordDecl *GetClassForType(QualType T) {
693 if (const RecordType *RT = T->getAs<RecordType>())
694 return cast<CXXRecordDecl>(RT->getDecl());
695 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
696 return ICT->getDecl();
697 else
698 return 0;
699}
700
Douglas Gregora8f32e02009-10-06 17:59:45 +0000701/// \brief Determine whether the type \p Derived is a C++ class that is
702/// derived from the type \p Base.
703bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
704 if (!getLangOptions().CPlusPlus)
705 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000706
707 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
708 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000709 return false;
710
John McCall3cb0ebd2010-03-10 03:28:59 +0000711 CXXRecordDecl *BaseRD = GetClassForType(Base);
712 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000713 return false;
714
John McCall86ff3082010-02-04 22:26:26 +0000715 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
716 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000717}
718
719/// \brief Determine whether the type \p Derived is a C++ class that is
720/// derived from the type \p Base.
721bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
722 if (!getLangOptions().CPlusPlus)
723 return false;
724
John McCall3cb0ebd2010-03-10 03:28:59 +0000725 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
726 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000727 return false;
728
John McCall3cb0ebd2010-03-10 03:28:59 +0000729 CXXRecordDecl *BaseRD = GetClassForType(Base);
730 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000731 return false;
732
Douglas Gregora8f32e02009-10-06 17:59:45 +0000733 return DerivedRD->isDerivedFrom(BaseRD, Paths);
734}
735
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000736void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000737 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000738 assert(BasePathArray.empty() && "Base path array must be empty!");
739 assert(Paths.isRecordingPaths() && "Must record paths!");
740
741 const CXXBasePath &Path = Paths.front();
742
743 // We first go backward and check if we have a virtual base.
744 // FIXME: It would be better if CXXBasePath had the base specifier for
745 // the nearest virtual base.
746 unsigned Start = 0;
747 for (unsigned I = Path.size(); I != 0; --I) {
748 if (Path[I - 1].Base->isVirtual()) {
749 Start = I - 1;
750 break;
751 }
752 }
753
754 // Now add all bases.
755 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000756 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000757}
758
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000759/// \brief Determine whether the given base path includes a virtual
760/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000761bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
762 for (CXXCastPath::const_iterator B = BasePath.begin(),
763 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000764 B != BEnd; ++B)
765 if ((*B)->isVirtual())
766 return true;
767
768 return false;
769}
770
Douglas Gregora8f32e02009-10-06 17:59:45 +0000771/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
772/// conversion (where Derived and Base are class types) is
773/// well-formed, meaning that the conversion is unambiguous (and
774/// that all of the base classes are accessible). Returns true
775/// and emits a diagnostic if the code is ill-formed, returns false
776/// otherwise. Loc is the location where this routine should point to
777/// if there is an error, and Range is the source range to highlight
778/// if there is an error.
779bool
780Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000781 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000782 unsigned AmbigiousBaseConvID,
783 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000784 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000785 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000786 // First, determine whether the path from Derived to Base is
787 // ambiguous. This is slightly more expensive than checking whether
788 // the Derived to Base conversion exists, because here we need to
789 // explore multiple paths to determine if there is an ambiguity.
790 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
791 /*DetectVirtual=*/false);
792 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
793 assert(DerivationOkay &&
794 "Can only be used with a derived-to-base conversion");
795 (void)DerivationOkay;
796
797 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000798 if (InaccessibleBaseID) {
799 // Check that the base class can be accessed.
800 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
801 InaccessibleBaseID)) {
802 case AR_inaccessible:
803 return true;
804 case AR_accessible:
805 case AR_dependent:
806 case AR_delayed:
807 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000808 }
John McCall6b2accb2010-02-10 09:31:12 +0000809 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000810
811 // Build a base path if necessary.
812 if (BasePath)
813 BuildBasePathArray(Paths, *BasePath);
814 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000815 }
816
817 // We know that the derived-to-base conversion is ambiguous, and
818 // we're going to produce a diagnostic. Perform the derived-to-base
819 // search just one more time to compute all of the possible paths so
820 // that we can print them out. This is more expensive than any of
821 // the previous derived-to-base checks we've done, but at this point
822 // performance isn't as much of an issue.
823 Paths.clear();
824 Paths.setRecordingPaths(true);
825 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
826 assert(StillOkay && "Can only be used with a derived-to-base conversion");
827 (void)StillOkay;
828
829 // Build up a textual representation of the ambiguous paths, e.g.,
830 // D -> B -> A, that will be used to illustrate the ambiguous
831 // conversions in the diagnostic. We only print one of the paths
832 // to each base class subobject.
833 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
834
835 Diag(Loc, AmbigiousBaseConvID)
836 << Derived << Base << PathDisplayStr << Range << Name;
837 return true;
838}
839
840bool
841Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000842 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000843 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000844 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000846 IgnoreAccess ? 0
847 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000848 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000849 Loc, Range, DeclarationName(),
850 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851}
852
853
854/// @brief Builds a string representing ambiguous paths from a
855/// specific derived class to different subobjects of the same base
856/// class.
857///
858/// This function builds a string that can be used in error messages
859/// to show the different paths that one can take through the
860/// inheritance hierarchy to go from the derived class to different
861/// subobjects of a base class. The result looks something like this:
862/// @code
863/// struct D -> struct B -> struct A
864/// struct D -> struct C -> struct A
865/// @endcode
866std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
867 std::string PathDisplayStr;
868 std::set<unsigned> DisplayedPaths;
869 for (CXXBasePaths::paths_iterator Path = Paths.begin();
870 Path != Paths.end(); ++Path) {
871 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
872 // We haven't displayed a path to this particular base
873 // class subobject yet.
874 PathDisplayStr += "\n ";
875 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
876 for (CXXBasePath::const_iterator Element = Path->begin();
877 Element != Path->end(); ++Element)
878 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
879 }
880 }
881
882 return PathDisplayStr;
883}
884
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000885//===----------------------------------------------------------------------===//
886// C++ class member Handling
887//===----------------------------------------------------------------------===//
888
Abramo Bagnara6206d532010-06-05 05:09:32 +0000889/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000890Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
891 SourceLocation ASLoc,
892 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000893 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000894 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000895 ASLoc, ColonLoc);
896 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000897 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000898}
899
Anders Carlsson9e682d92011-01-20 05:57:14 +0000900/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000901void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +0000902 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
903 if (!MD || !MD->isVirtual())
904 return;
905
Anders Carlsson3ffe1832011-01-20 06:33:26 +0000906 if (MD->isDependentContext())
907 return;
908
Anders Carlsson9e682d92011-01-20 05:57:14 +0000909 // C++0x [class.virtual]p3:
910 // If a virtual function is marked with the virt-specifier override and does
911 // not override a member function of a base class,
912 // the program is ill-formed.
913 bool HasOverriddenMethods =
914 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000915 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +0000916 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +0000917 diag::err_function_marked_override_not_overriding)
918 << MD->getDeclName();
919 return;
920 }
921}
922
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000923/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
924/// function overrides a virtual member function marked 'final', according to
925/// C++0x [class.virtual]p3.
926bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
927 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000928 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +0000929 return false;
930
931 Diag(New->getLocation(), diag::err_final_function_overridden)
932 << New->getDeclName();
933 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
934 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +0000935}
936
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000937/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
938/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
939/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000940/// any.
John McCalld226f652010-08-21 09:40:31 +0000941Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000942Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000943 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +0000944 ExprTy *BW, const VirtSpecifiers &VS,
945 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld1a78462009-11-24 23:38:44 +0000946 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000948 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
949 DeclarationName Name = NameInfo.getName();
950 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000951
952 // For anonymous bitfields, the location should point to the type.
953 if (Loc.isInvalid())
954 Loc = D.getSourceRange().getBegin();
955
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000956 Expr *BitWidth = static_cast<Expr*>(BW);
957 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000958
John McCall4bde1e12010-06-04 08:34:12 +0000959 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000960 assert(!DS.isFriendSpecified());
961
John McCall4bde1e12010-06-04 08:34:12 +0000962 bool isFunc = false;
963 if (D.isFunctionDeclarator())
964 isFunc = true;
965 else if (D.getNumTypeObjects() == 0 &&
966 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000967 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000968 isFunc = TDType->isFunctionType();
969 }
970
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000971 // C++ 9.2p6: A member shall not be declared to have automatic storage
972 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000973 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
974 // data members and cannot be applied to names declared const or static,
975 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000976 switch (DS.getStorageClassSpec()) {
977 case DeclSpec::SCS_unspecified:
978 case DeclSpec::SCS_typedef:
979 case DeclSpec::SCS_static:
980 // FALL THROUGH.
981 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000982 case DeclSpec::SCS_mutable:
983 if (isFunc) {
984 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000985 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000986 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000987 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Sebastian Redla11f42f2008-11-17 23:24:37 +0000989 // FIXME: It would be nicer if the keyword was ignored only for this
990 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000991 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000992 }
993 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000994 default:
995 if (DS.getStorageClassSpecLoc().isValid())
996 Diag(DS.getStorageClassSpecLoc(),
997 diag::err_storageclass_invalid_for_member);
998 else
999 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1000 D.getMutableDeclSpec().ClearStorageClassSpecs();
1001 }
1002
Sebastian Redl669d5d72008-11-14 23:42:31 +00001003 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1004 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001005 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001006
1007 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001008 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001009 CXXScopeSpec &SS = D.getCXXScopeSpec();
1010
1011
1012 if (SS.isSet() && !SS.isInvalid()) {
1013 // The user provided a superfluous scope specifier inside a class
1014 // definition:
1015 //
1016 // class X {
1017 // int X::member;
1018 // };
1019 DeclContext *DC = 0;
1020 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1021 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1022 << Name << FixItHint::CreateRemoval(SS.getRange());
1023 else
1024 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1025 << Name << SS.getRange();
1026
1027 SS.clear();
1028 }
1029
Douglas Gregor37b372b2009-08-20 22:52:58 +00001030 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001031 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001032 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1033 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001034 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001035 } else {
John McCalld226f652010-08-21 09:40:31 +00001036 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001037 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001038 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001039 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001040
1041 // Non-instance-fields can't have a bitfield.
1042 if (BitWidth) {
1043 if (Member->isInvalidDecl()) {
1044 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001045 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001046 // C++ 9.6p3: A bit-field shall not be a static member.
1047 // "static member 'A' cannot be a bit-field"
1048 Diag(Loc, diag::err_static_not_bitfield)
1049 << Name << BitWidth->getSourceRange();
1050 } else if (isa<TypedefDecl>(Member)) {
1051 // "typedef member 'x' cannot be a bit-field"
1052 Diag(Loc, diag::err_typedef_not_bitfield)
1053 << Name << BitWidth->getSourceRange();
1054 } else {
1055 // A function typedef ("typedef int f(); f a;").
1056 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1057 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001058 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001059 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner8b963ef2009-03-05 23:01:03 +00001062 BitWidth = 0;
1063 Member->setInvalidDecl();
1064 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001065
1066 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregor37b372b2009-08-20 22:52:58 +00001068 // If we have declared a member function template, set the access of the
1069 // templated declaration as well.
1070 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1071 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001072 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001073
Anders Carlssonaae5af22011-01-20 04:34:22 +00001074 if (VS.isOverrideSpecified()) {
1075 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1076 if (!MD || !MD->isVirtual()) {
1077 Diag(Member->getLocStart(),
1078 diag::override_keyword_only_allowed_on_virtual_member_functions)
1079 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001080 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001081 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001082 }
1083 if (VS.isFinalSpecified()) {
1084 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1085 if (!MD || !MD->isVirtual()) {
1086 Diag(Member->getLocStart(),
1087 diag::override_keyword_only_allowed_on_virtual_member_functions)
1088 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001089 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001090 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001091 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001092
Douglas Gregorf5251602011-03-08 17:10:18 +00001093 if (VS.getLastLocation().isValid()) {
1094 // Update the end location of a method that has a virt-specifiers.
1095 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1096 MD->setRangeEnd(VS.getLastLocation());
1097 }
1098
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001099 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001100
Douglas Gregor10bd3682008-11-17 22:58:34 +00001101 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001102
Douglas Gregor021c3b32009-03-11 23:00:04 +00001103 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001104 AddInitializerToDecl(Member, Init, false,
1105 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redle2b68332009-04-12 17:16:29 +00001106 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001107 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001108
Richard Smith483b9f32011-02-21 20:05:19 +00001109 FinalizeDeclaration(Member);
1110
John McCallb25b2952011-02-15 07:12:36 +00001111 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001112 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001113 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001114}
1115
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001116/// \brief Find the direct and/or virtual base specifiers that
1117/// correspond to the given base type, for use in base initialization
1118/// within a constructor.
1119static bool FindBaseInitializer(Sema &SemaRef,
1120 CXXRecordDecl *ClassDecl,
1121 QualType BaseType,
1122 const CXXBaseSpecifier *&DirectBaseSpec,
1123 const CXXBaseSpecifier *&VirtualBaseSpec) {
1124 // First, check for a direct base class.
1125 DirectBaseSpec = 0;
1126 for (CXXRecordDecl::base_class_const_iterator Base
1127 = ClassDecl->bases_begin();
1128 Base != ClassDecl->bases_end(); ++Base) {
1129 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1130 // We found a direct base of this type. That's what we're
1131 // initializing.
1132 DirectBaseSpec = &*Base;
1133 break;
1134 }
1135 }
1136
1137 // Check for a virtual base class.
1138 // FIXME: We might be able to short-circuit this if we know in advance that
1139 // there are no virtual bases.
1140 VirtualBaseSpec = 0;
1141 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1142 // We haven't found a base yet; search the class hierarchy for a
1143 // virtual base class.
1144 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1145 /*DetectVirtual=*/false);
1146 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1147 BaseType, Paths)) {
1148 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1149 Path != Paths.end(); ++Path) {
1150 if (Path->back().Base->isVirtual()) {
1151 VirtualBaseSpec = Path->back().Base;
1152 break;
1153 }
1154 }
1155 }
1156 }
1157
1158 return DirectBaseSpec || VirtualBaseSpec;
1159}
1160
Douglas Gregor7ad83902008-11-05 04:29:56 +00001161/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001162MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001163Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001164 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001165 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001166 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001167 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001168 SourceLocation IdLoc,
1169 SourceLocation LParenLoc,
1170 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001171 SourceLocation RParenLoc,
1172 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001173 if (!ConstructorD)
1174 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001176 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001177
1178 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001179 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001180 if (!Constructor) {
1181 // The user wrote a constructor initializer on a function that is
1182 // not a C++ constructor. Ignore the error for now, because we may
1183 // have more member initializers coming; we'll diagnose it just
1184 // once in ActOnMemInitializers.
1185 return true;
1186 }
1187
1188 CXXRecordDecl *ClassDecl = Constructor->getParent();
1189
1190 // C++ [class.base.init]p2:
1191 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001192 // constructor's class and, if not found in that scope, are looked
1193 // up in the scope containing the constructor's definition.
1194 // [Note: if the constructor's class contains a member with the
1195 // same name as a direct or virtual base class of the class, a
1196 // mem-initializer-id naming the member or base class and composed
1197 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001198 // mem-initializer-id for the hidden base class may be specified
1199 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001200 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001201 // Look for a member, first.
1202 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001203 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001204 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001205 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001206 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001207
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001208 if (Member) {
1209 if (EllipsisLoc.isValid())
1210 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1211 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1212
Francois Pichet00eb3f92010-12-04 09:14:42 +00001213 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001214 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001215 }
1216
Francois Pichet00eb3f92010-12-04 09:14:42 +00001217 // Handle anonymous union case.
1218 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001219 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1220 if (EllipsisLoc.isValid())
1221 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1222 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1223
Francois Pichet00eb3f92010-12-04 09:14:42 +00001224 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1225 NumArgs, IdLoc,
1226 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001227 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001228 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001229 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001230 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001231 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001232 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001233
1234 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001235 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001236 } else {
1237 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1238 LookupParsedName(R, S, &SS);
1239
1240 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1241 if (!TyD) {
1242 if (R.isAmbiguous()) return true;
1243
John McCallfd225442010-04-09 19:01:14 +00001244 // We don't want access-control diagnostics here.
1245 R.suppressDiagnostics();
1246
Douglas Gregor7a886e12010-01-19 06:46:48 +00001247 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1248 bool NotUnknownSpecialization = false;
1249 DeclContext *DC = computeDeclContext(SS, false);
1250 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1251 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1252
1253 if (!NotUnknownSpecialization) {
1254 // When the scope specifier can refer to a member of an unknown
1255 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001256 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1257 SS.getWithLocInContext(Context),
1258 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001259 if (BaseType.isNull())
1260 return true;
1261
Douglas Gregor7a886e12010-01-19 06:46:48 +00001262 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001263 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001264 }
1265 }
1266
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001267 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001268 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001269 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1270 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001271 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001272 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001273 // We have found a non-static data member with a similar
1274 // name to what was typed; complain and initialize that
1275 // member.
1276 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1277 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001278 << FixItHint::CreateReplacement(R.getNameLoc(),
1279 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001280 Diag(Member->getLocation(), diag::note_previous_decl)
1281 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001282
1283 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1284 LParenLoc, RParenLoc);
1285 }
1286 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1287 const CXXBaseSpecifier *DirectBaseSpec;
1288 const CXXBaseSpecifier *VirtualBaseSpec;
1289 if (FindBaseInitializer(*this, ClassDecl,
1290 Context.getTypeDeclType(Type),
1291 DirectBaseSpec, VirtualBaseSpec)) {
1292 // We have found a direct or virtual base class with a
1293 // similar name to what was typed; complain and initialize
1294 // that base class.
1295 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1296 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001297 << FixItHint::CreateReplacement(R.getNameLoc(),
1298 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001299
1300 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1301 : VirtualBaseSpec;
1302 Diag(BaseSpec->getSourceRange().getBegin(),
1303 diag::note_base_class_specified_here)
1304 << BaseSpec->getType()
1305 << BaseSpec->getSourceRange();
1306
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001307 TyD = Type;
1308 }
1309 }
1310 }
1311
Douglas Gregor7a886e12010-01-19 06:46:48 +00001312 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001313 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1314 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1315 return true;
1316 }
John McCall2b194412009-12-21 10:41:20 +00001317 }
1318
Douglas Gregor7a886e12010-01-19 06:46:48 +00001319 if (BaseType.isNull()) {
1320 BaseType = Context.getTypeDeclType(TyD);
1321 if (SS.isSet()) {
1322 NestedNameSpecifier *Qualifier =
1323 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001324
Douglas Gregor7a886e12010-01-19 06:46:48 +00001325 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001326 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001327 }
John McCall2b194412009-12-21 10:41:20 +00001328 }
1329 }
Mike Stump1eb44332009-09-09 15:08:12 +00001330
John McCalla93c9342009-12-07 02:54:59 +00001331 if (!TInfo)
1332 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001333
John McCalla93c9342009-12-07 02:54:59 +00001334 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001335 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001336}
1337
John McCallb4190042009-11-04 23:02:40 +00001338/// Checks an initializer expression for use of uninitialized fields, such as
1339/// containing the field that is being initialized. Returns true if there is an
1340/// uninitialized field was used an updates the SourceLocation parameter; false
1341/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001342static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001343 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001344 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001345 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1346
Nick Lewycky43ad1822010-06-15 07:32:55 +00001347 if (isa<CallExpr>(S)) {
1348 // Do not descend into function calls or constructors, as the use
1349 // of an uninitialized field may be valid. One would have to inspect
1350 // the contents of the function/ctor to determine if it is safe or not.
1351 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1352 // may be safe, depending on what the function/ctor does.
1353 return false;
1354 }
1355 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1356 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001357
1358 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1359 // The member expression points to a static data member.
1360 assert(VD->isStaticDataMember() &&
1361 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001362 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001363 return false;
1364 }
1365
1366 if (isa<EnumConstantDecl>(RhsField)) {
1367 // The member expression points to an enum.
1368 return false;
1369 }
1370
John McCallb4190042009-11-04 23:02:40 +00001371 if (RhsField == LhsField) {
1372 // Initializing a field with itself. Throw a warning.
1373 // But wait; there are exceptions!
1374 // Exception #1: The field may not belong to this record.
1375 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001376 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001377 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1378 // Even though the field matches, it does not belong to this record.
1379 return false;
1380 }
1381 // None of the exceptions triggered; return true to indicate an
1382 // uninitialized field was used.
1383 *L = ME->getMemberLoc();
1384 return true;
1385 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001386 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001387 // sizeof/alignof doesn't reference contents, do not warn.
1388 return false;
1389 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1390 // address-of doesn't reference contents (the pointer may be dereferenced
1391 // in the same expression but it would be rare; and weird).
1392 if (UOE->getOpcode() == UO_AddrOf)
1393 return false;
John McCallb4190042009-11-04 23:02:40 +00001394 }
John McCall7502c1d2011-02-13 04:07:26 +00001395 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001396 if (!*it) {
1397 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001398 continue;
1399 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001400 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1401 return true;
John McCallb4190042009-11-04 23:02:40 +00001402 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001403 return false;
John McCallb4190042009-11-04 23:02:40 +00001404}
1405
John McCallf312b1e2010-08-26 23:41:50 +00001406MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001407Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001408 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001409 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001410 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001411 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1412 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1413 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001414 "Member must be a FieldDecl or IndirectFieldDecl");
1415
Douglas Gregor464b2f02010-11-05 22:21:31 +00001416 if (Member->isInvalidDecl())
1417 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001418
John McCallb4190042009-11-04 23:02:40 +00001419 // Diagnose value-uses of fields to initialize themselves, e.g.
1420 // foo(foo)
1421 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001422 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001423 for (unsigned i = 0; i < NumArgs; ++i) {
1424 SourceLocation L;
1425 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1426 // FIXME: Return true in the case when other fields are used before being
1427 // uninitialized. For example, let this field be the i'th field. When
1428 // initializing the i'th field, throw a warning if any of the >= i'th
1429 // fields are used, as they are not yet initialized.
1430 // Right now we are only handling the case where the i'th field uses
1431 // itself in its initializer.
1432 Diag(L, diag::warn_field_is_uninit);
1433 }
1434 }
1435
Eli Friedman59c04372009-07-29 19:44:27 +00001436 bool HasDependentArg = false;
1437 for (unsigned i = 0; i < NumArgs; i++)
1438 HasDependentArg |= Args[i]->isTypeDependent();
1439
Chandler Carruth894aed92010-12-06 09:23:57 +00001440 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001441 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001442 // Can't check initialization for a member of dependent type or when
1443 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001444 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1445 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001446
1447 // Erase any temporaries within this evaluation context; we're not
1448 // going to track them in the AST, since we'll be rebuilding the
1449 // ASTs during template instantiation.
1450 ExprTemporaries.erase(
1451 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1452 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001453 } else {
1454 // Initialize the member.
1455 InitializedEntity MemberEntity =
1456 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1457 : InitializedEntity::InitializeMember(IndirectMember, 0);
1458 InitializationKind Kind =
1459 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001460
Chandler Carruth894aed92010-12-06 09:23:57 +00001461 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1462
1463 ExprResult MemberInit =
1464 InitSeq.Perform(*this, MemberEntity, Kind,
1465 MultiExprArg(*this, Args, NumArgs), 0);
1466 if (MemberInit.isInvalid())
1467 return true;
1468
1469 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1470
1471 // C++0x [class.base.init]p7:
1472 // The initialization of each base and member constitutes a
1473 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001474 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001475 if (MemberInit.isInvalid())
1476 return true;
1477
1478 // If we are in a dependent context, template instantiation will
1479 // perform this type-checking again. Just save the arguments that we
1480 // received in a ParenListExpr.
1481 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1482 // of the information that we have about the member
1483 // initializer. However, deconstructing the ASTs is a dicey process,
1484 // and this approach is far more likely to get the corner cases right.
1485 if (CurContext->isDependentContext())
1486 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1487 RParenLoc);
1488 else
1489 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001490 }
1491
Chandler Carruth894aed92010-12-06 09:23:57 +00001492 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001493 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001494 IdLoc, LParenLoc, Init,
1495 RParenLoc);
1496 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001497 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001498 IdLoc, LParenLoc, Init,
1499 RParenLoc);
1500 }
Eli Friedman59c04372009-07-29 19:44:27 +00001501}
1502
John McCallf312b1e2010-08-26 23:41:50 +00001503MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001504Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1505 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001506 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001507 SourceLocation LParenLoc,
1508 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001509 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001510 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1511 if (!LangOpts.CPlusPlus0x)
1512 return Diag(Loc, diag::err_delegation_0x_only)
1513 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001514
Sean Hunt41717662011-02-26 19:13:13 +00001515 // Initialize the object.
1516 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1517 QualType(ClassDecl->getTypeForDecl(), 0));
1518 InitializationKind Kind =
1519 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1520
1521 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1522
1523 ExprResult DelegationInit =
1524 InitSeq.Perform(*this, DelegationEntity, Kind,
1525 MultiExprArg(*this, Args, NumArgs), 0);
1526 if (DelegationInit.isInvalid())
1527 return true;
1528
1529 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1530 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1531 assert(Constructor && "Delegating constructor with no target?");
1532
1533 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1534
1535 // C++0x [class.base.init]p7:
1536 // The initialization of each base and member constitutes a
1537 // full-expression.
1538 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1539 if (DelegationInit.isInvalid())
1540 return true;
1541
1542 // If we are in a dependent context, template instantiation will
1543 // perform this type-checking again. Just save the arguments that we
1544 // received in a ParenListExpr.
1545 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1546 // of the information that we have about the base
1547 // initializer. However, deconstructing the ASTs is a dicey process,
1548 // and this approach is far more likely to get the corner cases right.
1549 if (CurContext->isDependentContext()) {
1550 ExprResult Init
1551 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1552 NumArgs, RParenLoc));
1553 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1554 Constructor, Init.takeAs<Expr>(),
1555 RParenLoc);
1556 }
1557
1558 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1559 DelegationInit.takeAs<Expr>(),
1560 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001561}
1562
1563MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001564Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001565 Expr **Args, unsigned NumArgs,
1566 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001567 CXXRecordDecl *ClassDecl,
1568 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001569 bool HasDependentArg = false;
1570 for (unsigned i = 0; i < NumArgs; i++)
1571 HasDependentArg |= Args[i]->isTypeDependent();
1572
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001573 SourceLocation BaseLoc
1574 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1575
1576 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1577 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1578 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1579
1580 // C++ [class.base.init]p2:
1581 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001582 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001583 // of that class, the mem-initializer is ill-formed. A
1584 // mem-initializer-list can initialize a base class using any
1585 // name that denotes that base class type.
1586 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1587
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001588 if (EllipsisLoc.isValid()) {
1589 // This is a pack expansion.
1590 if (!BaseType->containsUnexpandedParameterPack()) {
1591 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1592 << SourceRange(BaseLoc, RParenLoc);
1593
1594 EllipsisLoc = SourceLocation();
1595 }
1596 } else {
1597 // Check for any unexpanded parameter packs.
1598 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1599 return true;
1600
1601 for (unsigned I = 0; I != NumArgs; ++I)
1602 if (DiagnoseUnexpandedParameterPack(Args[I]))
1603 return true;
1604 }
1605
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001606 // Check for direct and virtual base classes.
1607 const CXXBaseSpecifier *DirectBaseSpec = 0;
1608 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1609 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001610 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1611 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001612 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1613 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001614
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001615 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1616 VirtualBaseSpec);
1617
1618 // C++ [base.class.init]p2:
1619 // Unless the mem-initializer-id names a nonstatic data member of the
1620 // constructor's class or a direct or virtual base of that class, the
1621 // mem-initializer is ill-formed.
1622 if (!DirectBaseSpec && !VirtualBaseSpec) {
1623 // If the class has any dependent bases, then it's possible that
1624 // one of those types will resolve to the same type as
1625 // BaseType. Therefore, just treat this as a dependent base
1626 // class initialization. FIXME: Should we try to check the
1627 // initialization anyway? It seems odd.
1628 if (ClassDecl->hasAnyDependentBases())
1629 Dependent = true;
1630 else
1631 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1632 << BaseType << Context.getTypeDeclType(ClassDecl)
1633 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1634 }
1635 }
1636
1637 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001638 // Can't check initialization for a base of dependent type or when
1639 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001640 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001641 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1642 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001643
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001644 // Erase any temporaries within this evaluation context; we're not
1645 // going to track them in the AST, since we'll be rebuilding the
1646 // ASTs during template instantiation.
1647 ExprTemporaries.erase(
1648 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1649 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Sean Huntcbb67482011-01-08 20:30:50 +00001651 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001652 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001653 LParenLoc,
1654 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001655 RParenLoc,
1656 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001657 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001658
1659 // C++ [base.class.init]p2:
1660 // If a mem-initializer-id is ambiguous because it designates both
1661 // a direct non-virtual base class and an inherited virtual base
1662 // class, the mem-initializer is ill-formed.
1663 if (DirectBaseSpec && VirtualBaseSpec)
1664 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001665 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001666
1667 CXXBaseSpecifier *BaseSpec
1668 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1669 if (!BaseSpec)
1670 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1671
1672 // Initialize the base.
1673 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001674 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001675 InitializationKind Kind =
1676 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1677
1678 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1679
John McCall60d7b3a2010-08-24 06:29:42 +00001680 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001681 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001682 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001683 if (BaseInit.isInvalid())
1684 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001685
1686 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001687
1688 // C++0x [class.base.init]p7:
1689 // The initialization of each base and member constitutes a
1690 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001691 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001692 if (BaseInit.isInvalid())
1693 return true;
1694
1695 // If we are in a dependent context, template instantiation will
1696 // perform this type-checking again. Just save the arguments that we
1697 // received in a ParenListExpr.
1698 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1699 // of the information that we have about the base
1700 // initializer. However, deconstructing the ASTs is a dicey process,
1701 // and this approach is far more likely to get the corner cases right.
1702 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001703 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001704 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1705 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001706 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001707 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001708 LParenLoc,
1709 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001710 RParenLoc,
1711 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001712 }
1713
Sean Huntcbb67482011-01-08 20:30:50 +00001714 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001715 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001716 LParenLoc,
1717 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001718 RParenLoc,
1719 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001720}
1721
Anders Carlssone5ef7402010-04-23 03:10:23 +00001722/// ImplicitInitializerKind - How an implicit base or member initializer should
1723/// initialize its base or member.
1724enum ImplicitInitializerKind {
1725 IIK_Default,
1726 IIK_Copy,
1727 IIK_Move
1728};
1729
Anders Carlssondefefd22010-04-23 02:00:02 +00001730static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001731BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001732 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001733 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001734 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001735 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001736 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001737 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1738 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001739
John McCall60d7b3a2010-08-24 06:29:42 +00001740 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001741
1742 switch (ImplicitInitKind) {
1743 case IIK_Default: {
1744 InitializationKind InitKind
1745 = InitializationKind::CreateDefault(Constructor->getLocation());
1746 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1747 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001748 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001749 break;
1750 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001751
Anders Carlssone5ef7402010-04-23 03:10:23 +00001752 case IIK_Copy: {
1753 ParmVarDecl *Param = Constructor->getParamDecl(0);
1754 QualType ParamType = Param->getType().getNonReferenceType();
1755
1756 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001757 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001758 Constructor->getLocation(), ParamType,
1759 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001760
Anders Carlssonc7957502010-04-24 22:02:54 +00001761 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001762 QualType ArgTy =
1763 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1764 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001765
1766 CXXCastPath BasePath;
1767 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001768 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001769 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001770 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001771
Anders Carlssone5ef7402010-04-23 03:10:23 +00001772 InitializationKind InitKind
1773 = InitializationKind::CreateDirect(Constructor->getLocation(),
1774 SourceLocation(), SourceLocation());
1775 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1776 &CopyCtorArg, 1);
1777 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001778 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001779 break;
1780 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001781
Anders Carlssone5ef7402010-04-23 03:10:23 +00001782 case IIK_Move:
1783 assert(false && "Unhandled initializer kind!");
1784 }
John McCall9ae2f072010-08-23 23:25:46 +00001785
Douglas Gregor53c374f2010-12-07 00:41:46 +00001786 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001787 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001788 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001789
Anders Carlssondefefd22010-04-23 02:00:02 +00001790 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001791 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001792 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1793 SourceLocation()),
1794 BaseSpec->isVirtual(),
1795 SourceLocation(),
1796 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001797 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001798 SourceLocation());
1799
Anders Carlssondefefd22010-04-23 02:00:02 +00001800 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001801}
1802
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001803static bool
1804BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001805 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001806 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001807 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001808 if (Field->isInvalidDecl())
1809 return true;
1810
Chandler Carruthf186b542010-06-29 23:50:44 +00001811 SourceLocation Loc = Constructor->getLocation();
1812
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001813 if (ImplicitInitKind == IIK_Copy) {
1814 ParmVarDecl *Param = Constructor->getParamDecl(0);
1815 QualType ParamType = Param->getType().getNonReferenceType();
1816
1817 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001818 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001819 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001820
1821 // Build a reference to this field within the parameter.
1822 CXXScopeSpec SS;
1823 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1824 Sema::LookupMemberName);
1825 MemberLookup.addDecl(Field, AS_public);
1826 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001827 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001828 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001829 ParamType, Loc,
1830 /*IsArrow=*/false,
1831 SS,
1832 /*FirstQualifierInScope=*/0,
1833 MemberLookup,
1834 /*TemplateArgs=*/0);
1835 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001836 return true;
1837
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001838 // When the field we are copying is an array, create index variables for
1839 // each dimension of the array. We use these index variables to subscript
1840 // the source array, and other clients (e.g., CodeGen) will perform the
1841 // necessary iteration with these index variables.
1842 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1843 QualType BaseType = Field->getType();
1844 QualType SizeType = SemaRef.Context.getSizeType();
1845 while (const ConstantArrayType *Array
1846 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1847 // Create the iteration variable for this array index.
1848 IdentifierInfo *IterationVarName = 0;
1849 {
1850 llvm::SmallString<8> Str;
1851 llvm::raw_svector_ostream OS(Str);
1852 OS << "__i" << IndexVariables.size();
1853 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1854 }
1855 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001856 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001857 IterationVarName, SizeType,
1858 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001859 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001860 IndexVariables.push_back(IterationVar);
1861
1862 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001863 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001864 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001865 assert(!IterationVarRef.isInvalid() &&
1866 "Reference to invented variable cannot fail!");
1867
1868 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001869 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001870 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001871 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001872 Loc);
1873 if (CopyCtorArg.isInvalid())
1874 return true;
1875
1876 BaseType = Array->getElementType();
1877 }
1878
1879 // Construct the entity that we will be initializing. For an array, this
1880 // will be first element in the array, which may require several levels
1881 // of array-subscript entities.
1882 llvm::SmallVector<InitializedEntity, 4> Entities;
1883 Entities.reserve(1 + IndexVariables.size());
1884 Entities.push_back(InitializedEntity::InitializeMember(Field));
1885 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1886 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1887 0,
1888 Entities.back()));
1889
1890 // Direct-initialize to use the copy constructor.
1891 InitializationKind InitKind =
1892 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1893
1894 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1895 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1896 &CopyCtorArgE, 1);
1897
John McCall60d7b3a2010-08-24 06:29:42 +00001898 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001899 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001900 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001901 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001902 if (MemberInit.isInvalid())
1903 return true;
1904
1905 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00001906 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001907 MemberInit.takeAs<Expr>(), Loc,
1908 IndexVariables.data(),
1909 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001910 return false;
1911 }
1912
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001913 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1914
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001915 QualType FieldBaseElementType =
1916 SemaRef.Context.getBaseElementType(Field->getType());
1917
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001918 if (FieldBaseElementType->isRecordType()) {
1919 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001920 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001921 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001922
1923 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001924 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001925 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001926
Douglas Gregor53c374f2010-12-07 00:41:46 +00001927 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001928 if (MemberInit.isInvalid())
1929 return true;
1930
1931 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001932 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001933 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001934 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001935 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001936 return false;
1937 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001938
1939 if (FieldBaseElementType->isReferenceType()) {
1940 SemaRef.Diag(Constructor->getLocation(),
1941 diag::err_uninitialized_member_in_ctor)
1942 << (int)Constructor->isImplicit()
1943 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1944 << 0 << Field->getDeclName();
1945 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1946 return true;
1947 }
1948
1949 if (FieldBaseElementType.isConstQualified()) {
1950 SemaRef.Diag(Constructor->getLocation(),
1951 diag::err_uninitialized_member_in_ctor)
1952 << (int)Constructor->isImplicit()
1953 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1954 << 1 << Field->getDeclName();
1955 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1956 return true;
1957 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001958
1959 // Nothing to initialize.
1960 CXXMemberInit = 0;
1961 return false;
1962}
John McCallf1860e52010-05-20 23:23:51 +00001963
1964namespace {
1965struct BaseAndFieldInfo {
1966 Sema &S;
1967 CXXConstructorDecl *Ctor;
1968 bool AnyErrorsInInits;
1969 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00001970 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1971 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00001972
1973 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1974 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1975 // FIXME: Handle implicit move constructors.
1976 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1977 IIK = IIK_Copy;
1978 else
1979 IIK = IIK_Default;
1980 }
1981};
1982}
1983
1984static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1985 FieldDecl *Top, FieldDecl *Field) {
1986
Chandler Carruthe861c602010-06-30 02:59:29 +00001987 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00001988 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001989 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001990 return false;
1991 }
1992
1993 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1994 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1995 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001996 CXXRecordDecl *FieldClassDecl
1997 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001998
1999 // Even though union members never have non-trivial default
2000 // constructions in C++03, we still build member initializers for aggregate
2001 // record types which can be union members, and C++0x allows non-trivial
2002 // default constructors for union members, so we ensure that only one
2003 // member is initialized for these.
2004 if (FieldClassDecl->isUnion()) {
2005 // First check for an explicit initializer for one field.
2006 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2007 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002008 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002009 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002010
2011 // Once we've initialized a field of an anonymous union, the union
2012 // field in the class is also initialized, so exit immediately.
2013 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002014 } else if ((*FA)->isAnonymousStructOrUnion()) {
2015 if (CollectFieldInitializer(Info, Top, *FA))
2016 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002017 }
2018 }
2019
2020 // Fallthrough and construct a default initializer for the union as
2021 // a whole, which can call its default constructor if such a thing exists
2022 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2023 // behavior going forward with C++0x, when anonymous unions there are
2024 // finalized, we should revisit this.
2025 } else {
2026 // For structs, we simply descend through to initialize all members where
2027 // necessary.
2028 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2029 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2030 if (CollectFieldInitializer(Info, Top, *FA))
2031 return true;
2032 }
2033 }
John McCallf1860e52010-05-20 23:23:51 +00002034 }
2035
2036 // Don't try to build an implicit initializer if there were semantic
2037 // errors in any of the initializers (and therefore we might be
2038 // missing some that the user actually wrote).
2039 if (Info.AnyErrorsInInits)
2040 return false;
2041
Sean Huntcbb67482011-01-08 20:30:50 +00002042 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002043 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2044 return true;
John McCallf1860e52010-05-20 23:23:51 +00002045
Francois Pichet00eb3f92010-12-04 09:14:42 +00002046 if (Init)
2047 Info.AllToInit.push_back(Init);
2048
John McCallf1860e52010-05-20 23:23:51 +00002049 return false;
2050}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002051
Eli Friedman80c30da2009-11-09 19:20:36 +00002052bool
Sean Huntcbb67482011-01-08 20:30:50 +00002053Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2054 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002055 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002056 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002057 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002058 // Just store the initializers as written, they will be checked during
2059 // instantiation.
2060 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002061 Constructor->setNumCtorInitializers(NumInitializers);
2062 CXXCtorInitializer **baseOrMemberInitializers =
2063 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002064 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002065 NumInitializers * sizeof(CXXCtorInitializer*));
2066 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002067 }
2068
2069 return false;
2070 }
2071
John McCallf1860e52010-05-20 23:23:51 +00002072 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002073
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002074 // We need to build the initializer AST according to order of construction
2075 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002076 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002077 if (!ClassDecl)
2078 return true;
2079
Eli Friedman80c30da2009-11-09 19:20:36 +00002080 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002082 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002083 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002084
2085 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002086 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002087 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002088 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002089 }
2090
Anders Carlsson711f34a2010-04-21 19:52:01 +00002091 // Keep track of the direct virtual bases.
2092 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2093 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2094 E = ClassDecl->bases_end(); I != E; ++I) {
2095 if (I->isVirtual())
2096 DirectVBases.insert(I);
2097 }
2098
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002099 // Push virtual bases before others.
2100 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2101 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2102
Sean Huntcbb67482011-01-08 20:30:50 +00002103 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002104 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2105 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002106 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002107 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002108 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002109 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002110 VBase, IsInheritedVirtualBase,
2111 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002112 HadError = true;
2113 continue;
2114 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002115
John McCallf1860e52010-05-20 23:23:51 +00002116 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002117 }
2118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
John McCallf1860e52010-05-20 23:23:51 +00002120 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002121 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2122 E = ClassDecl->bases_end(); Base != E; ++Base) {
2123 // Virtuals are in the virtual base list and already constructed.
2124 if (Base->isVirtual())
2125 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Sean Huntcbb67482011-01-08 20:30:50 +00002127 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002128 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2129 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002130 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002131 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002132 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002133 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002134 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002135 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002136 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002137 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002138
John McCallf1860e52010-05-20 23:23:51 +00002139 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002140 }
2141 }
Mike Stump1eb44332009-09-09 15:08:12 +00002142
John McCallf1860e52010-05-20 23:23:51 +00002143 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002144 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002145 E = ClassDecl->field_end(); Field != E; ++Field) {
2146 if ((*Field)->getType()->isIncompleteArrayType()) {
2147 assert(ClassDecl->hasFlexibleArrayMember() &&
2148 "Incomplete array type is not valid");
2149 continue;
2150 }
John McCallf1860e52010-05-20 23:23:51 +00002151 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002152 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002153 }
Mike Stump1eb44332009-09-09 15:08:12 +00002154
John McCallf1860e52010-05-20 23:23:51 +00002155 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002156 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002157 Constructor->setNumCtorInitializers(NumInitializers);
2158 CXXCtorInitializer **baseOrMemberInitializers =
2159 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002160 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002161 NumInitializers * sizeof(CXXCtorInitializer*));
2162 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002163
John McCallef027fe2010-03-16 21:39:52 +00002164 // Constructors implicitly reference the base and member
2165 // destructors.
2166 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2167 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002168 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002169
2170 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002171}
2172
Eli Friedman6347f422009-07-21 19:28:10 +00002173static void *GetKeyForTopLevelField(FieldDecl *Field) {
2174 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002175 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002176 if (RT->getDecl()->isAnonymousStructOrUnion())
2177 return static_cast<void *>(RT->getDecl());
2178 }
2179 return static_cast<void *>(Field);
2180}
2181
Anders Carlssonea356fb2010-04-02 05:42:15 +00002182static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002183 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002184}
2185
Anders Carlssonea356fb2010-04-02 05:42:15 +00002186static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002187 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002188 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002189 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002190
Eli Friedman6347f422009-07-21 19:28:10 +00002191 // For fields injected into the class via declaration of an anonymous union,
2192 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002193 FieldDecl *Field = Member->getAnyMember();
2194
John McCall3c3ccdb2010-04-10 09:28:51 +00002195 // If the field is a member of an anonymous struct or union, our key
2196 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002197 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002198 if (RD->isAnonymousStructOrUnion()) {
2199 while (true) {
2200 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2201 if (Parent->isAnonymousStructOrUnion())
2202 RD = Parent;
2203 else
2204 break;
2205 }
2206
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002207 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002208 }
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002210 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002211}
2212
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002213static void
2214DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002215 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002216 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002217 unsigned NumInits) {
2218 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002219 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002221 // Don't check initializers order unless the warning is enabled at the
2222 // location of at least one initializer.
2223 bool ShouldCheckOrder = false;
2224 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002225 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002226 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2227 Init->getSourceLocation())
2228 != Diagnostic::Ignored) {
2229 ShouldCheckOrder = true;
2230 break;
2231 }
2232 }
2233 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002234 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002235
John McCalld6ca8da2010-04-10 07:37:23 +00002236 // Build the list of bases and members in the order that they'll
2237 // actually be initialized. The explicit initializers should be in
2238 // this same order but may be missing things.
2239 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Anders Carlsson071d6102010-04-02 03:38:04 +00002241 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2242
John McCalld6ca8da2010-04-10 07:37:23 +00002243 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002244 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002245 ClassDecl->vbases_begin(),
2246 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002247 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002248
John McCalld6ca8da2010-04-10 07:37:23 +00002249 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002250 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002251 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002252 if (Base->isVirtual())
2253 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002254 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002255 }
Mike Stump1eb44332009-09-09 15:08:12 +00002256
John McCalld6ca8da2010-04-10 07:37:23 +00002257 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002258 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2259 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002260 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002261
John McCalld6ca8da2010-04-10 07:37:23 +00002262 unsigned NumIdealInits = IdealInitKeys.size();
2263 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002264
Sean Huntcbb67482011-01-08 20:30:50 +00002265 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002266 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002267 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002268 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002269
2270 // Scan forward to try to find this initializer in the idealized
2271 // initializers list.
2272 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2273 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002274 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002275
2276 // If we didn't find this initializer, it must be because we
2277 // scanned past it on a previous iteration. That can only
2278 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002279 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002280 Sema::SemaDiagnosticBuilder D =
2281 SemaRef.Diag(PrevInit->getSourceLocation(),
2282 diag::warn_initializer_out_of_order);
2283
Francois Pichet00eb3f92010-12-04 09:14:42 +00002284 if (PrevInit->isAnyMemberInitializer())
2285 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002286 else
2287 D << 1 << PrevInit->getBaseClassInfo()->getType();
2288
Francois Pichet00eb3f92010-12-04 09:14:42 +00002289 if (Init->isAnyMemberInitializer())
2290 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002291 else
2292 D << 1 << Init->getBaseClassInfo()->getType();
2293
2294 // Move back to the initializer's location in the ideal list.
2295 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2296 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002297 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002298
2299 assert(IdealIndex != NumIdealInits &&
2300 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002301 }
John McCalld6ca8da2010-04-10 07:37:23 +00002302
2303 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002304 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002305}
2306
John McCall3c3ccdb2010-04-10 09:28:51 +00002307namespace {
2308bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002309 CXXCtorInitializer *Init,
2310 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002311 if (!PrevInit) {
2312 PrevInit = Init;
2313 return false;
2314 }
2315
2316 if (FieldDecl *Field = Init->getMember())
2317 S.Diag(Init->getSourceLocation(),
2318 diag::err_multiple_mem_initialization)
2319 << Field->getDeclName()
2320 << Init->getSourceRange();
2321 else {
John McCallf4c73712011-01-19 06:33:43 +00002322 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002323 assert(BaseClass && "neither field nor base");
2324 S.Diag(Init->getSourceLocation(),
2325 diag::err_multiple_base_initialization)
2326 << QualType(BaseClass, 0)
2327 << Init->getSourceRange();
2328 }
2329 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2330 << 0 << PrevInit->getSourceRange();
2331
2332 return true;
2333}
2334
Sean Huntcbb67482011-01-08 20:30:50 +00002335typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002336typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2337
2338bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002339 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002340 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002341 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002342 RecordDecl *Parent = Field->getParent();
2343 if (!Parent->isAnonymousStructOrUnion())
2344 return false;
2345
2346 NamedDecl *Child = Field;
2347 do {
2348 if (Parent->isUnion()) {
2349 UnionEntry &En = Unions[Parent];
2350 if (En.first && En.first != Child) {
2351 S.Diag(Init->getSourceLocation(),
2352 diag::err_multiple_mem_union_initialization)
2353 << Field->getDeclName()
2354 << Init->getSourceRange();
2355 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2356 << 0 << En.second->getSourceRange();
2357 return true;
2358 } else if (!En.first) {
2359 En.first = Child;
2360 En.second = Init;
2361 }
2362 }
2363
2364 Child = Parent;
2365 Parent = cast<RecordDecl>(Parent->getDeclContext());
2366 } while (Parent->isAnonymousStructOrUnion());
2367
2368 return false;
2369}
2370}
2371
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002372/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002373void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002374 SourceLocation ColonLoc,
2375 MemInitTy **meminits, unsigned NumMemInits,
2376 bool AnyErrors) {
2377 if (!ConstructorDecl)
2378 return;
2379
2380 AdjustDeclIfTemplate(ConstructorDecl);
2381
2382 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002383 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002384
2385 if (!Constructor) {
2386 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2387 return;
2388 }
2389
Sean Huntcbb67482011-01-08 20:30:50 +00002390 CXXCtorInitializer **MemInits =
2391 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002392
2393 // Mapping for the duplicate initializers check.
2394 // For member initializers, this is keyed with a FieldDecl*.
2395 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002396 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002397
2398 // Mapping for the inconsistent anonymous-union initializers check.
2399 RedundantUnionMap MemberUnions;
2400
Anders Carlssonea356fb2010-04-02 05:42:15 +00002401 bool HadError = false;
2402 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002403 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002404
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002405 // Set the source order index.
2406 Init->setSourceOrder(i);
2407
Francois Pichet00eb3f92010-12-04 09:14:42 +00002408 if (Init->isAnyMemberInitializer()) {
2409 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002410 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2411 CheckRedundantUnionInit(*this, Init, MemberUnions))
2412 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002413 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002414 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2415 if (CheckRedundantInit(*this, Init, Members[Key]))
2416 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002417 } else {
2418 assert(Init->isDelegatingInitializer());
2419 // This must be the only initializer
2420 if (i != 0 || NumMemInits > 1) {
2421 Diag(MemInits[0]->getSourceLocation(),
2422 diag::err_delegating_initializer_alone)
2423 << MemInits[0]->getSourceRange();
2424 HadError = true;
2425 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002426 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002427 }
2428
Anders Carlssonea356fb2010-04-02 05:42:15 +00002429 if (HadError)
2430 return;
2431
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002432 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002433
Sean Huntcbb67482011-01-08 20:30:50 +00002434 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002435}
2436
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002437void
John McCallef027fe2010-03-16 21:39:52 +00002438Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2439 CXXRecordDecl *ClassDecl) {
2440 // Ignore dependent contexts.
2441 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002442 return;
John McCall58e6f342010-03-16 05:22:47 +00002443
2444 // FIXME: all the access-control diagnostics are positioned on the
2445 // field/base declaration. That's probably good; that said, the
2446 // user might reasonably want to know why the destructor is being
2447 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002448
Anders Carlsson9f853df2009-11-17 04:44:12 +00002449 // Non-static data members.
2450 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2451 E = ClassDecl->field_end(); I != E; ++I) {
2452 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002453 if (Field->isInvalidDecl())
2454 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002455 QualType FieldType = Context.getBaseElementType(Field->getType());
2456
2457 const RecordType* RT = FieldType->getAs<RecordType>();
2458 if (!RT)
2459 continue;
2460
2461 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002462 if (FieldClassDecl->isInvalidDecl())
2463 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002464 if (FieldClassDecl->hasTrivialDestructor())
2465 continue;
2466
Douglas Gregordb89f282010-07-01 22:47:18 +00002467 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002468 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002469 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002470 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002471 << Field->getDeclName()
2472 << FieldType);
2473
John McCallef027fe2010-03-16 21:39:52 +00002474 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002475 }
2476
John McCall58e6f342010-03-16 05:22:47 +00002477 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2478
Anders Carlsson9f853df2009-11-17 04:44:12 +00002479 // Bases.
2480 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2481 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002482 // Bases are always records in a well-formed non-dependent class.
2483 const RecordType *RT = Base->getType()->getAs<RecordType>();
2484
2485 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002486 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002487 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002488
John McCall58e6f342010-03-16 05:22:47 +00002489 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002490 // If our base class is invalid, we probably can't get its dtor anyway.
2491 if (BaseClassDecl->isInvalidDecl())
2492 continue;
2493 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002494 if (BaseClassDecl->hasTrivialDestructor())
2495 continue;
John McCall58e6f342010-03-16 05:22:47 +00002496
Douglas Gregordb89f282010-07-01 22:47:18 +00002497 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002498 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002499
2500 // FIXME: caret should be on the start of the class name
2501 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002502 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002503 << Base->getType()
2504 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002505
John McCallef027fe2010-03-16 21:39:52 +00002506 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002507 }
2508
2509 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002510 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2511 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002512
2513 // Bases are always records in a well-formed non-dependent class.
2514 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2515
2516 // Ignore direct virtual bases.
2517 if (DirectVirtualBases.count(RT))
2518 continue;
2519
John McCall58e6f342010-03-16 05:22:47 +00002520 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002521 // If our base class is invalid, we probably can't get its dtor anyway.
2522 if (BaseClassDecl->isInvalidDecl())
2523 continue;
2524 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002525 if (BaseClassDecl->hasTrivialDestructor())
2526 continue;
John McCall58e6f342010-03-16 05:22:47 +00002527
Douglas Gregordb89f282010-07-01 22:47:18 +00002528 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002529 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002530 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002531 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002532 << VBase->getType());
2533
John McCallef027fe2010-03-16 21:39:52 +00002534 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002535 }
2536}
2537
John McCalld226f652010-08-21 09:40:31 +00002538void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002539 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002540 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Mike Stump1eb44332009-09-09 15:08:12 +00002542 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002543 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002544 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002545}
2546
Mike Stump1eb44332009-09-09 15:08:12 +00002547bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002548 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002549 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002550 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002551 else
John McCall94c3b562010-08-18 09:41:07 +00002552 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002553}
2554
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002555bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002556 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002557 if (!getLangOptions().CPlusPlus)
2558 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Anders Carlsson11f21a02009-03-23 19:10:31 +00002560 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002561 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Ted Kremenek6217b802009-07-29 21:53:49 +00002563 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002564 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002565 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002566 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002568 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002569 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002570 }
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Ted Kremenek6217b802009-07-29 21:53:49 +00002572 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002573 if (!RT)
2574 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002575
John McCall86ff3082010-02-04 22:26:26 +00002576 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002577
John McCall94c3b562010-08-18 09:41:07 +00002578 // We can't answer whether something is abstract until it has a
2579 // definition. If it's currently being defined, we'll walk back
2580 // over all the declarations when we have a full definition.
2581 const CXXRecordDecl *Def = RD->getDefinition();
2582 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002583 return false;
2584
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002585 if (!RD->isAbstract())
2586 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002588 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002589 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002590
John McCall94c3b562010-08-18 09:41:07 +00002591 return true;
2592}
2593
2594void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2595 // Check if we've already emitted the list of pure virtual functions
2596 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002597 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002598 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002600 CXXFinalOverriderMap FinalOverriders;
2601 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002603 // Keep a set of seen pure methods so we won't diagnose the same method
2604 // more than once.
2605 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2606
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002607 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2608 MEnd = FinalOverriders.end();
2609 M != MEnd;
2610 ++M) {
2611 for (OverridingMethods::iterator SO = M->second.begin(),
2612 SOEnd = M->second.end();
2613 SO != SOEnd; ++SO) {
2614 // C++ [class.abstract]p4:
2615 // A class is abstract if it contains or inherits at least one
2616 // pure virtual function for which the final overrider is pure
2617 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002619 //
2620 if (SO->second.size() != 1)
2621 continue;
2622
2623 if (!SO->second.front().Method->isPure())
2624 continue;
2625
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002626 if (!SeenPureMethods.insert(SO->second.front().Method))
2627 continue;
2628
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002629 Diag(SO->second.front().Method->getLocation(),
2630 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002631 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002632 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002633 }
2634
2635 if (!PureVirtualClassDiagSet)
2636 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2637 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002638}
2639
Anders Carlsson8211eff2009-03-24 01:19:16 +00002640namespace {
John McCall94c3b562010-08-18 09:41:07 +00002641struct AbstractUsageInfo {
2642 Sema &S;
2643 CXXRecordDecl *Record;
2644 CanQualType AbstractType;
2645 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002646
John McCall94c3b562010-08-18 09:41:07 +00002647 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2648 : S(S), Record(Record),
2649 AbstractType(S.Context.getCanonicalType(
2650 S.Context.getTypeDeclType(Record))),
2651 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002652
John McCall94c3b562010-08-18 09:41:07 +00002653 void DiagnoseAbstractType() {
2654 if (Invalid) return;
2655 S.DiagnoseAbstractType(Record);
2656 Invalid = true;
2657 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002658
John McCall94c3b562010-08-18 09:41:07 +00002659 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2660};
2661
2662struct CheckAbstractUsage {
2663 AbstractUsageInfo &Info;
2664 const NamedDecl *Ctx;
2665
2666 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2667 : Info(Info), Ctx(Ctx) {}
2668
2669 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2670 switch (TL.getTypeLocClass()) {
2671#define ABSTRACT_TYPELOC(CLASS, PARENT)
2672#define TYPELOC(CLASS, PARENT) \
2673 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2674#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002675 }
John McCall94c3b562010-08-18 09:41:07 +00002676 }
Mike Stump1eb44332009-09-09 15:08:12 +00002677
John McCall94c3b562010-08-18 09:41:07 +00002678 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2679 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2680 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002681 if (!TL.getArg(I))
2682 continue;
2683
John McCall94c3b562010-08-18 09:41:07 +00002684 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2685 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002686 }
John McCall94c3b562010-08-18 09:41:07 +00002687 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002688
John McCall94c3b562010-08-18 09:41:07 +00002689 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2690 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2691 }
Mike Stump1eb44332009-09-09 15:08:12 +00002692
John McCall94c3b562010-08-18 09:41:07 +00002693 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2694 // Visit the type parameters from a permissive context.
2695 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2696 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2697 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2698 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2699 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2700 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002701 }
John McCall94c3b562010-08-18 09:41:07 +00002702 }
Mike Stump1eb44332009-09-09 15:08:12 +00002703
John McCall94c3b562010-08-18 09:41:07 +00002704 // Visit pointee types from a permissive context.
2705#define CheckPolymorphic(Type) \
2706 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2707 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2708 }
2709 CheckPolymorphic(PointerTypeLoc)
2710 CheckPolymorphic(ReferenceTypeLoc)
2711 CheckPolymorphic(MemberPointerTypeLoc)
2712 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002713
John McCall94c3b562010-08-18 09:41:07 +00002714 /// Handle all the types we haven't given a more specific
2715 /// implementation for above.
2716 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2717 // Every other kind of type that we haven't called out already
2718 // that has an inner type is either (1) sugar or (2) contains that
2719 // inner type in some way as a subobject.
2720 if (TypeLoc Next = TL.getNextTypeLoc())
2721 return Visit(Next, Sel);
2722
2723 // If there's no inner type and we're in a permissive context,
2724 // don't diagnose.
2725 if (Sel == Sema::AbstractNone) return;
2726
2727 // Check whether the type matches the abstract type.
2728 QualType T = TL.getType();
2729 if (T->isArrayType()) {
2730 Sel = Sema::AbstractArrayType;
2731 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002732 }
John McCall94c3b562010-08-18 09:41:07 +00002733 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2734 if (CT != Info.AbstractType) return;
2735
2736 // It matched; do some magic.
2737 if (Sel == Sema::AbstractArrayType) {
2738 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2739 << T << TL.getSourceRange();
2740 } else {
2741 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2742 << Sel << T << TL.getSourceRange();
2743 }
2744 Info.DiagnoseAbstractType();
2745 }
2746};
2747
2748void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2749 Sema::AbstractDiagSelID Sel) {
2750 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2751}
2752
2753}
2754
2755/// Check for invalid uses of an abstract type in a method declaration.
2756static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2757 CXXMethodDecl *MD) {
2758 // No need to do the check on definitions, which require that
2759 // the return/param types be complete.
2760 if (MD->isThisDeclarationADefinition())
2761 return;
2762
2763 // For safety's sake, just ignore it if we don't have type source
2764 // information. This should never happen for non-implicit methods,
2765 // but...
2766 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2767 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2768}
2769
2770/// Check for invalid uses of an abstract type within a class definition.
2771static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2772 CXXRecordDecl *RD) {
2773 for (CXXRecordDecl::decl_iterator
2774 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2775 Decl *D = *I;
2776 if (D->isImplicit()) continue;
2777
2778 // Methods and method templates.
2779 if (isa<CXXMethodDecl>(D)) {
2780 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2781 } else if (isa<FunctionTemplateDecl>(D)) {
2782 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2783 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2784
2785 // Fields and static variables.
2786 } else if (isa<FieldDecl>(D)) {
2787 FieldDecl *FD = cast<FieldDecl>(D);
2788 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2789 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2790 } else if (isa<VarDecl>(D)) {
2791 VarDecl *VD = cast<VarDecl>(D);
2792 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2793 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2794
2795 // Nested classes and class templates.
2796 } else if (isa<CXXRecordDecl>(D)) {
2797 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2798 } else if (isa<ClassTemplateDecl>(D)) {
2799 CheckAbstractClassUsage(Info,
2800 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2801 }
2802 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002803}
2804
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002805/// \brief Perform semantic checks on a class definition that has been
2806/// completing, introducing implicitly-declared members, checking for
2807/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002808void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002809 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002810 return;
2811
John McCall94c3b562010-08-18 09:41:07 +00002812 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2813 AbstractUsageInfo Info(*this, Record);
2814 CheckAbstractClassUsage(Info, Record);
2815 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002816
2817 // If this is not an aggregate type and has no user-declared constructor,
2818 // complain about any non-static data members of reference or const scalar
2819 // type, since they will never get initializers.
2820 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2821 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2822 bool Complained = false;
2823 for (RecordDecl::field_iterator F = Record->field_begin(),
2824 FEnd = Record->field_end();
2825 F != FEnd; ++F) {
2826 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002827 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002828 if (!Complained) {
2829 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2830 << Record->getTagKind() << Record;
2831 Complained = true;
2832 }
2833
2834 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2835 << F->getType()->isReferenceType()
2836 << F->getDeclName();
2837 }
2838 }
2839 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002840
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00002841 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002842 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002843
2844 if (Record->getIdentifier()) {
2845 // C++ [class.mem]p13:
2846 // If T is the name of a class, then each of the following shall have a
2847 // name different from T:
2848 // - every member of every anonymous union that is a member of class T.
2849 //
2850 // C++ [class.mem]p14:
2851 // In addition, if class T has a user-declared constructor (12.1), every
2852 // non-static data member of class T shall have a name different from T.
2853 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002854 R.first != R.second; ++R.first) {
2855 NamedDecl *D = *R.first;
2856 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2857 isa<IndirectFieldDecl>(D)) {
2858 Diag(D->getLocation(), diag::err_member_name_of_class)
2859 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002860 break;
2861 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002862 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002863 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002864
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002865 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00002866 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002867 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00002868 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00002869 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2870 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2871 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002872
2873 // See if a method overloads virtual methods in a base
2874 /// class without overriding any.
2875 if (!Record->isDependentType()) {
2876 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2877 MEnd = Record->method_end();
2878 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00002879 if (!(*M)->isStatic())
2880 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002881 }
2882 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00002883
2884 // Declare inherited constructors. We do this eagerly here because:
2885 // - The standard requires an eager diagnostic for conflicting inherited
2886 // constructors from different classes.
2887 // - The lazy declaration of the other implicit constructors is so as to not
2888 // waste space and performance on classes that are not meant to be
2889 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2890 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00002891 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002892}
2893
2894/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00002895namespace {
2896 struct FindHiddenVirtualMethodData {
2897 Sema *S;
2898 CXXMethodDecl *Method;
2899 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2900 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2901 };
2902}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002903
2904/// \brief Member lookup function that determines whether a given C++
2905/// method overloads virtual methods in a base class without overriding any,
2906/// to be used with CXXRecordDecl::lookupInBases().
2907static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2908 CXXBasePath &Path,
2909 void *UserData) {
2910 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2911
2912 FindHiddenVirtualMethodData &Data
2913 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2914
2915 DeclarationName Name = Data.Method->getDeclName();
2916 assert(Name.getNameKind() == DeclarationName::Identifier);
2917
2918 bool foundSameNameMethod = false;
2919 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2920 for (Path.Decls = BaseRecord->lookup(Name);
2921 Path.Decls.first != Path.Decls.second;
2922 ++Path.Decls.first) {
2923 NamedDecl *D = *Path.Decls.first;
2924 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002925 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002926 foundSameNameMethod = true;
2927 // Interested only in hidden virtual methods.
2928 if (!MD->isVirtual())
2929 continue;
2930 // If the method we are checking overrides a method from its base
2931 // don't warn about the other overloaded methods.
2932 if (!Data.S->IsOverload(Data.Method, MD, false))
2933 return true;
2934 // Collect the overload only if its hidden.
2935 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2936 overloadedMethods.push_back(MD);
2937 }
2938 }
2939
2940 if (foundSameNameMethod)
2941 Data.OverloadedMethods.append(overloadedMethods.begin(),
2942 overloadedMethods.end());
2943 return foundSameNameMethod;
2944}
2945
2946/// \brief See if a method overloads virtual methods in a base class without
2947/// overriding any.
2948void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2949 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2950 MD->getLocation()) == Diagnostic::Ignored)
2951 return;
2952 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2953 return;
2954
2955 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2956 /*bool RecordPaths=*/false,
2957 /*bool DetectVirtual=*/false);
2958 FindHiddenVirtualMethodData Data;
2959 Data.Method = MD;
2960 Data.S = this;
2961
2962 // Keep the base methods that were overriden or introduced in the subclass
2963 // by 'using' in a set. A base method not in this set is hidden.
2964 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2965 res.first != res.second; ++res.first) {
2966 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2967 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2968 E = MD->end_overridden_methods();
2969 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002970 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002971 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2972 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00002973 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00002974 }
2975
2976 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2977 !Data.OverloadedMethods.empty()) {
2978 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2979 << MD << (Data.OverloadedMethods.size() > 1);
2980
2981 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2982 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2983 Diag(overloadedMD->getLocation(),
2984 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2985 }
2986 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002987}
2988
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002989void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002990 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002991 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002992 SourceLocation RBrac,
2993 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002994 if (!TagDecl)
2995 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Douglas Gregor42af25f2009-05-11 19:58:34 +00002997 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002998
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002999 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00003000 // strict aliasing violation!
3001 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00003002 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00003003
Douglas Gregor23c94db2010-07-02 17:43:08 +00003004 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00003005 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003006}
3007
Douglas Gregord92ec472010-07-01 05:10:53 +00003008namespace {
3009 /// \brief Helper class that collects exception specifications for
3010 /// implicitly-declared special member functions.
3011 class ImplicitExceptionSpecification {
3012 ASTContext &Context;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003013 // We order exception specifications thus:
3014 // noexcept is the most restrictive, but is only used in C++0x.
3015 // throw() comes next.
3016 // Then a throw(collected exceptions)
3017 // Finally no specification.
3018 // throw(...) is used instead if any called function uses it.
3019 ExceptionSpecificationType ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003020 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3021 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003022
3023 void ClearExceptions() {
3024 ExceptionsSeen.clear();
3025 Exceptions.clear();
3026 }
3027
Douglas Gregord92ec472010-07-01 05:10:53 +00003028 public:
3029 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redl60618fa2011-03-12 11:50:43 +00003030 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3031 if (!Context.getLangOptions().CPlusPlus0x)
3032 ComputedEST = EST_DynamicNone;
Douglas Gregord92ec472010-07-01 05:10:53 +00003033 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003034
3035 /// \brief Get the computed exception specification type.
3036 ExceptionSpecificationType getExceptionSpecType() const {
3037 assert(ComputedEST != EST_ComputedNoexcept &&
3038 "noexcept(expr) should not be a possible result");
3039 return ComputedEST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003040 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003041
Douglas Gregord92ec472010-07-01 05:10:53 +00003042 /// \brief The number of exceptions in the exception specification.
3043 unsigned size() const { return Exceptions.size(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003044
Douglas Gregord92ec472010-07-01 05:10:53 +00003045 /// \brief The set of exceptions in the exception specification.
3046 const QualType *data() const { return Exceptions.data(); }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003047
3048 /// \brief Integrate another called method into the collected data.
Douglas Gregord92ec472010-07-01 05:10:53 +00003049 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00003050 // If we have an MSAny spec already, don't bother.
3051 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregord92ec472010-07-01 05:10:53 +00003052 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003053
Douglas Gregord92ec472010-07-01 05:10:53 +00003054 const FunctionProtoType *Proto
3055 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003056
3057 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3058
Douglas Gregord92ec472010-07-01 05:10:53 +00003059 // If this function can throw any exceptions, make a note of that.
Sebastian Redl60618fa2011-03-12 11:50:43 +00003060 if (EST == EST_MSAny || EST == EST_None) {
3061 ClearExceptions();
3062 ComputedEST = EST;
Douglas Gregord92ec472010-07-01 05:10:53 +00003063 return;
3064 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00003065
3066 // If this function has a basic noexcept, it doesn't affect the outcome.
3067 if (EST == EST_BasicNoexcept)
3068 return;
3069
3070 // If we have a throw-all spec at this point, ignore the function.
3071 if (ComputedEST == EST_None)
3072 return;
3073
3074 // If we're still at noexcept(true) and there's a nothrow() callee,
3075 // change to that specification.
3076 if (EST == EST_DynamicNone) {
3077 if (ComputedEST == EST_BasicNoexcept)
3078 ComputedEST = EST_DynamicNone;
3079 return;
3080 }
3081
3082 // Check out noexcept specs.
3083 if (EST == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003084 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +00003085 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3086 "Must have noexcept result for EST_ComputedNoexcept.");
3087 assert(NR != FunctionProtoType::NR_Dependent &&
3088 "Should not generate implicit declarations for dependent cases, "
3089 "and don't know how to handle them anyway.");
3090
3091 // noexcept(false) -> no spec on the new function
3092 if (NR == FunctionProtoType::NR_Throw) {
3093 ClearExceptions();
3094 ComputedEST = EST_None;
3095 }
3096 // noexcept(true) won't change anything either.
3097 return;
3098 }
3099
3100 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3101 assert(ComputedEST != EST_None &&
3102 "Shouldn't collect exceptions when throw-all is guaranteed.");
3103 ComputedEST = EST_Dynamic;
Douglas Gregord92ec472010-07-01 05:10:53 +00003104 // Record the exceptions in this function's exception specification.
3105 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3106 EEnd = Proto->exception_end();
Sebastian Redl60618fa2011-03-12 11:50:43 +00003107 E != EEnd; ++E)
Douglas Gregord92ec472010-07-01 05:10:53 +00003108 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3109 Exceptions.push_back(*E);
3110 }
3111 };
3112}
3113
3114
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003115/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3116/// special functions, such as the default constructor, copy
3117/// constructor, or destructor, to the given C++ class (C++
3118/// [special]p1). This routine can only be executed just before the
3119/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003120void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00003121 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00003122 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003123
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00003124 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00003125 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003126
Douglas Gregora376d102010-07-02 21:50:04 +00003127 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3128 ++ASTContext::NumImplicitCopyAssignmentOperators;
3129
3130 // If we have a dynamic class, then the copy assignment operator may be
3131 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3132 // it shows up in the right place in the vtable and that we diagnose
3133 // problems with the implicit exception specification.
3134 if (ClassDecl->isDynamicClass())
3135 DeclareImplicitCopyAssignment(ClassDecl);
3136 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003137
Douglas Gregor4923aa22010-07-02 20:37:36 +00003138 if (!ClassDecl->hasUserDeclaredDestructor()) {
3139 ++ASTContext::NumImplicitDestructors;
3140
3141 // If we have a dynamic class, then the destructor may be virtual, so we
3142 // have to declare the destructor immediately. This ensures that, e.g., it
3143 // shows up in the right place in the vtable and that we diagnose problems
3144 // with the implicit exception specification.
3145 if (ClassDecl->isDynamicClass())
3146 DeclareImplicitDestructor(ClassDecl);
3147 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00003148}
3149
John McCalld226f652010-08-21 09:40:31 +00003150void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00003151 if (!D)
3152 return;
3153
3154 TemplateParameterList *Params = 0;
3155 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3156 Params = Template->getTemplateParameters();
3157 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3158 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3159 Params = PartialSpec->getTemplateParameters();
3160 else
Douglas Gregor6569d682009-05-27 23:11:45 +00003161 return;
3162
Douglas Gregor6569d682009-05-27 23:11:45 +00003163 for (TemplateParameterList::iterator Param = Params->begin(),
3164 ParamEnd = Params->end();
3165 Param != ParamEnd; ++Param) {
3166 NamedDecl *Named = cast<NamedDecl>(*Param);
3167 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00003168 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00003169 IdResolver.AddDecl(Named);
3170 }
3171 }
3172}
3173
John McCalld226f652010-08-21 09:40:31 +00003174void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003175 if (!RecordD) return;
3176 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00003177 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00003178 PushDeclContext(S, Record);
3179}
3180
John McCalld226f652010-08-21 09:40:31 +00003181void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00003182 if (!RecordD) return;
3183 PopDeclContext();
3184}
3185
Douglas Gregor72b505b2008-12-16 21:30:33 +00003186/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3187/// parsing a top-level (non-nested) C++ class, and we are now
3188/// parsing those parts of the given Method declaration that could
3189/// not be parsed earlier (C++ [class.mem]p2), such as default
3190/// arguments. This action should enter the scope of the given
3191/// Method declaration as if we had just parsed the qualified method
3192/// name. However, it should not bring the parameters into scope;
3193/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00003194void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003195}
3196
3197/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3198/// C++ method declaration. We're (re-)introducing the given
3199/// function parameter into scope for use in parsing later parts of
3200/// the method declaration. For example, we could see an
3201/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00003202void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003203 if (!ParamD)
3204 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003205
John McCalld226f652010-08-21 09:40:31 +00003206 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00003207
3208 // If this parameter has an unparsed default argument, clear it out
3209 // to make way for the parsed default argument.
3210 if (Param->hasUnparsedDefaultArg())
3211 Param->setDefaultArg(0);
3212
John McCalld226f652010-08-21 09:40:31 +00003213 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003214 if (Param->getDeclName())
3215 IdResolver.AddDecl(Param);
3216}
3217
3218/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3219/// processing the delayed method declaration for Method. The method
3220/// declaration is now considered finished. There may be a separate
3221/// ActOnStartOfFunctionDef action later (not necessarily
3222/// immediately!) for this method, if it was also defined inside the
3223/// class body.
John McCalld226f652010-08-21 09:40:31 +00003224void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00003225 if (!MethodD)
3226 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003228 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00003229
John McCalld226f652010-08-21 09:40:31 +00003230 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003231
3232 // Now that we have our default arguments, check the constructor
3233 // again. It could produce additional diagnostics or affect whether
3234 // the class has implicitly-declared destructors, among other
3235 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00003236 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3237 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003238
3239 // Check the default arguments, which we may have added.
3240 if (!Method->isInvalidDecl())
3241 CheckCXXDefaultArguments(Method);
3242}
3243
Douglas Gregor42a552f2008-11-05 20:51:48 +00003244/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00003245/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00003246/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003247/// emit diagnostics and set the invalid bit to true. In any case, the type
3248/// will be updated to reflect a well-formed type for the constructor and
3249/// returned.
3250QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003251 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003252 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003253
3254 // C++ [class.ctor]p3:
3255 // A constructor shall not be virtual (10.3) or static (9.4). A
3256 // constructor can be invoked for a const, volatile or const
3257 // volatile object. A constructor shall not be declared const,
3258 // volatile, or const volatile (9.3.2).
3259 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00003260 if (!D.isInvalidType())
3261 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3262 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3263 << SourceRange(D.getIdentifierLoc());
3264 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003265 }
John McCalld931b082010-08-26 03:08:43 +00003266 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003267 if (!D.isInvalidType())
3268 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3269 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3270 << SourceRange(D.getIdentifierLoc());
3271 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003272 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003273 }
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003275 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003276 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00003277 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003278 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3279 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003280 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003281 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3282 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003283 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003284 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3285 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00003286 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003287 }
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Douglas Gregorc938c162011-01-26 05:01:58 +00003289 // C++0x [class.ctor]p4:
3290 // A constructor shall not be declared with a ref-qualifier.
3291 if (FTI.hasRefQualifier()) {
3292 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3293 << FTI.RefQualifierIsLValueRef
3294 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3295 D.setInvalidType();
3296 }
3297
Douglas Gregor42a552f2008-11-05 20:51:48 +00003298 // Rebuild the function type "R" without any type qualifiers (in
3299 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00003300 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00003301 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003302 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3303 return R;
3304
3305 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3306 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003307 EPI.RefQualifier = RQ_None;
3308
Chris Lattner65401802009-04-25 08:28:21 +00003309 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00003310 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003311}
3312
Douglas Gregor72b505b2008-12-16 21:30:33 +00003313/// CheckConstructor - Checks a fully-formed constructor for
3314/// well-formedness, issuing any diagnostics required. Returns true if
3315/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00003316void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00003317 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00003318 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3319 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00003320 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003321
3322 // C++ [class.copy]p3:
3323 // A declaration of a constructor for a class X is ill-formed if
3324 // its first parameter is of type (optionally cv-qualified) X and
3325 // either there are no other parameters or else all other
3326 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00003327 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003328 ((Constructor->getNumParams() == 1) ||
3329 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00003330 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3331 Constructor->getTemplateSpecializationKind()
3332 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003333 QualType ParamType = Constructor->getParamDecl(0)->getType();
3334 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3335 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00003336 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003337 const char *ConstRef
3338 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3339 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00003340 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00003341 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00003342
3343 // FIXME: Rather that making the constructor invalid, we should endeavor
3344 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00003345 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00003346 }
3347 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003348}
3349
John McCall15442822010-08-04 01:04:25 +00003350/// CheckDestructor - Checks a fully-formed destructor definition for
3351/// well-formedness, issuing any diagnostics required. Returns true
3352/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003353bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00003354 CXXRecordDecl *RD = Destructor->getParent();
3355
3356 if (Destructor->isVirtual()) {
3357 SourceLocation Loc;
3358
3359 if (!Destructor->isImplicit())
3360 Loc = Destructor->getLocation();
3361 else
3362 Loc = RD->getLocation();
3363
3364 // If we have a virtual destructor, look up the deallocation function
3365 FunctionDecl *OperatorDelete = 0;
3366 DeclarationName Name =
3367 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003368 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003369 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003370
3371 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003372
3373 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003374 }
Anders Carlsson37909802009-11-30 21:24:50 +00003375
3376 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003377}
3378
Mike Stump1eb44332009-09-09 15:08:12 +00003379static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003380FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3381 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3382 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003383 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003384}
3385
Douglas Gregor42a552f2008-11-05 20:51:48 +00003386/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3387/// the well-formednes of the destructor declarator @p D with type @p
3388/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003389/// emit diagnostics and set the declarator to invalid. Even if this happens,
3390/// will be updated to reflect a well-formed type for the destructor and
3391/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003392QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003393 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003394 // C++ [class.dtor]p1:
3395 // [...] A typedef-name that names a class is a class-name
3396 // (7.1.3); however, a typedef-name that names a class shall not
3397 // be used as the identifier in the declarator for a destructor
3398 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003399 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003400 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003401 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003402 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003403
3404 // C++ [class.dtor]p2:
3405 // A destructor is used to destroy objects of its class type. A
3406 // destructor takes no parameters, and no return type can be
3407 // specified for it (not even void). The address of a destructor
3408 // shall not be taken. A destructor shall not be static. A
3409 // destructor can be invoked for a const, volatile or const
3410 // volatile object. A destructor shall not be declared const,
3411 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003412 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003413 if (!D.isInvalidType())
3414 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3415 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003416 << SourceRange(D.getIdentifierLoc())
3417 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3418
John McCalld931b082010-08-26 03:08:43 +00003419 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003420 }
Chris Lattner65401802009-04-25 08:28:21 +00003421 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003422 // Destructors don't have return types, but the parser will
3423 // happily parse something like:
3424 //
3425 // class X {
3426 // float ~X();
3427 // };
3428 //
3429 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003430 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3431 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3432 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003433 }
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003435 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003436 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003437 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003438 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3439 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003440 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003441 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3442 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003443 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003444 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3445 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003446 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003447 }
3448
Douglas Gregorc938c162011-01-26 05:01:58 +00003449 // C++0x [class.dtor]p2:
3450 // A destructor shall not be declared with a ref-qualifier.
3451 if (FTI.hasRefQualifier()) {
3452 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3453 << FTI.RefQualifierIsLValueRef
3454 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3455 D.setInvalidType();
3456 }
3457
Douglas Gregor42a552f2008-11-05 20:51:48 +00003458 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003459 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003460 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3461
3462 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003463 FTI.freeArgs();
3464 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003465 }
3466
Mike Stump1eb44332009-09-09 15:08:12 +00003467 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003468 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003469 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003470 D.setInvalidType();
3471 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003472
3473 // Rebuild the function type "R" without any type qualifiers or
3474 // parameters (in case any of the errors above fired) and with
3475 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003476 // types.
John McCalle23cf432010-12-14 08:05:40 +00003477 if (!D.isInvalidType())
3478 return R;
3479
Douglas Gregord92ec472010-07-01 05:10:53 +00003480 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003481 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3482 EPI.Variadic = false;
3483 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00003484 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00003485 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003486}
3487
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003488/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3489/// well-formednes of the conversion function declarator @p D with
3490/// type @p R. If there are any errors in the declarator, this routine
3491/// will emit diagnostics and return true. Otherwise, it will return
3492/// false. Either way, the type @p R will be updated to reflect a
3493/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003494void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003495 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003496 // C++ [class.conv.fct]p1:
3497 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003498 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003499 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003500 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003501 if (!D.isInvalidType())
3502 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3503 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3504 << SourceRange(D.getIdentifierLoc());
3505 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003506 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003507 }
John McCalla3f81372010-04-13 00:04:31 +00003508
3509 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3510
Chris Lattner6e475012009-04-25 08:35:12 +00003511 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003512 // Conversion functions don't have return types, but the parser will
3513 // happily parse something like:
3514 //
3515 // class X {
3516 // float operator bool();
3517 // };
3518 //
3519 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003520 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3521 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3522 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003523 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003524 }
3525
John McCalla3f81372010-04-13 00:04:31 +00003526 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3527
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003528 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003529 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003530 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3531
3532 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003533 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003534 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003535 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003536 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003537 D.setInvalidType();
3538 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003539
John McCalla3f81372010-04-13 00:04:31 +00003540 // Diagnose "&operator bool()" and other such nonsense. This
3541 // is actually a gcc extension which we don't support.
3542 if (Proto->getResultType() != ConvType) {
3543 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3544 << Proto->getResultType();
3545 D.setInvalidType();
3546 ConvType = Proto->getResultType();
3547 }
3548
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003549 // C++ [class.conv.fct]p4:
3550 // The conversion-type-id shall not represent a function type nor
3551 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003552 if (ConvType->isArrayType()) {
3553 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3554 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003555 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003556 } else if (ConvType->isFunctionType()) {
3557 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3558 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003559 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003560 }
3561
3562 // Rebuild the function type "R" without any parameters (in case any
3563 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003564 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003565 if (D.isInvalidType())
3566 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003567
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003568 // C++0x explicit conversion operators.
3569 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003570 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003571 diag::warn_explicit_conversion_functions)
3572 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003573}
3574
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003575/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3576/// the declaration of the given C++ conversion function. This routine
3577/// is responsible for recording the conversion function in the C++
3578/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003579Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003580 assert(Conversion && "Expected to receive a conversion function declaration");
3581
Douglas Gregor9d350972008-12-12 08:25:50 +00003582 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003583
3584 // Make sure we aren't redeclaring the conversion function.
3585 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003586
3587 // C++ [class.conv.fct]p1:
3588 // [...] A conversion function is never used to convert a
3589 // (possibly cv-qualified) object to the (possibly cv-qualified)
3590 // same object type (or a reference to it), to a (possibly
3591 // cv-qualified) base class of that type (or a reference to it),
3592 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003593 // FIXME: Suppress this warning if the conversion function ends up being a
3594 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003595 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003596 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003597 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003598 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003599 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3600 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003601 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003602 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003603 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3604 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003605 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003606 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003607 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003608 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003609 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003610 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003611 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003612 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003613 }
3614
Douglas Gregore80622f2010-09-29 04:25:11 +00003615 if (FunctionTemplateDecl *ConversionTemplate
3616 = Conversion->getDescribedFunctionTemplate())
3617 return ConversionTemplate;
3618
John McCalld226f652010-08-21 09:40:31 +00003619 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003620}
3621
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003622//===----------------------------------------------------------------------===//
3623// Namespace Handling
3624//===----------------------------------------------------------------------===//
3625
John McCallea318642010-08-26 09:15:37 +00003626
3627
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003628/// ActOnStartNamespaceDef - This is called at the start of a namespace
3629/// definition.
John McCalld226f652010-08-21 09:40:31 +00003630Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003631 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003632 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00003633 SourceLocation IdentLoc,
3634 IdentifierInfo *II,
3635 SourceLocation LBrace,
3636 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003637 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3638 // For anonymous namespace, take the location of the left brace.
3639 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00003640 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003641 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003642 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003643
3644 Scope *DeclRegionScope = NamespcScope->getParent();
3645
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003646 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3647
John McCall90f14502010-12-10 02:59:44 +00003648 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3649 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003650
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003651 if (II) {
3652 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003653 // The identifier in an original-namespace-definition shall not
3654 // have been previously defined in the declarative region in
3655 // which the original-namespace-definition appears. The
3656 // identifier in an original-namespace-definition is the name of
3657 // the namespace. Subsequently in that declarative region, it is
3658 // treated as an original-namespace-name.
3659 //
3660 // Since namespace names are unique in their scope, and we don't
3661 // look through using directives, just
3662 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3663 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Douglas Gregor44b43212008-12-11 16:49:14 +00003665 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3666 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003667 if (Namespc->isInline() != OrigNS->isInline()) {
3668 // inline-ness must match
3669 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3670 << Namespc->isInline();
3671 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3672 Namespc->setInvalidDecl();
3673 // Recover by ignoring the new namespace's inline status.
3674 Namespc->setInline(OrigNS->isInline());
3675 }
3676
Douglas Gregor44b43212008-12-11 16:49:14 +00003677 // Attach this namespace decl to the chain of extended namespace
3678 // definitions.
3679 OrigNS->setNextNamespace(Namespc);
3680 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003681
Mike Stump1eb44332009-09-09 15:08:12 +00003682 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003683 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003684 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003685 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003686 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003687 } else if (PrevDecl) {
3688 // This is an invalid name redefinition.
3689 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3690 << Namespc->getDeclName();
3691 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3692 Namespc->setInvalidDecl();
3693 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003694 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003695 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003696 // This is the first "real" definition of the namespace "std", so update
3697 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003698 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003699 // We had already defined a dummy namespace "std". Link this new
3700 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003701 StdNS->setNextNamespace(Namespc);
3702 StdNS->setLocation(IdentLoc);
3703 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003704 }
3705
3706 // Make our StdNamespace cache point at the first real definition of the
3707 // "std" namespace.
3708 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003709 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003710
3711 PushOnScopeChains(Namespc, DeclRegionScope);
3712 } else {
John McCall9aeed322009-10-01 00:25:31 +00003713 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003714 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003715
3716 // Link the anonymous namespace into its parent.
3717 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003718 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003719 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3720 PrevDecl = TU->getAnonymousNamespace();
3721 TU->setAnonymousNamespace(Namespc);
3722 } else {
3723 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3724 PrevDecl = ND->getAnonymousNamespace();
3725 ND->setAnonymousNamespace(Namespc);
3726 }
3727
3728 // Link the anonymous namespace with its previous declaration.
3729 if (PrevDecl) {
3730 assert(PrevDecl->isAnonymousNamespace());
3731 assert(!PrevDecl->getNextNamespace());
3732 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3733 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003734
3735 if (Namespc->isInline() != PrevDecl->isInline()) {
3736 // inline-ness must match
3737 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3738 << Namespc->isInline();
3739 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3740 Namespc->setInvalidDecl();
3741 // Recover by ignoring the new namespace's inline status.
3742 Namespc->setInline(PrevDecl->isInline());
3743 }
John McCall5fdd7642009-12-16 02:06:49 +00003744 }
John McCall9aeed322009-10-01 00:25:31 +00003745
Douglas Gregora4181472010-03-24 00:46:35 +00003746 CurContext->addDecl(Namespc);
3747
John McCall9aeed322009-10-01 00:25:31 +00003748 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3749 // behaves as if it were replaced by
3750 // namespace unique { /* empty body */ }
3751 // using namespace unique;
3752 // namespace unique { namespace-body }
3753 // where all occurrences of 'unique' in a translation unit are
3754 // replaced by the same identifier and this identifier differs
3755 // from all other identifiers in the entire program.
3756
3757 // We just create the namespace with an empty name and then add an
3758 // implicit using declaration, just like the standard suggests.
3759 //
3760 // CodeGen enforces the "universally unique" aspect by giving all
3761 // declarations semantically contained within an anonymous
3762 // namespace internal linkage.
3763
John McCall5fdd7642009-12-16 02:06:49 +00003764 if (!PrevDecl) {
3765 UsingDirectiveDecl* UD
3766 = UsingDirectiveDecl::Create(Context, CurContext,
3767 /* 'using' */ LBrace,
3768 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00003769 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00003770 /* identifier */ SourceLocation(),
3771 Namespc,
3772 /* Ancestor */ CurContext);
3773 UD->setImplicit();
3774 CurContext->addDecl(UD);
3775 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003776 }
3777
3778 // Although we could have an invalid decl (i.e. the namespace name is a
3779 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003780 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3781 // for the namespace has the declarations that showed up in that particular
3782 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003783 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003784 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003785}
3786
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003787/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3788/// is a namespace alias, returns the namespace it points to.
3789static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3790 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3791 return AD->getNamespace();
3792 return dyn_cast_or_null<NamespaceDecl>(D);
3793}
3794
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003795/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3796/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003797void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003798 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3799 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003800 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003801 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003802 if (Namespc->hasAttr<VisibilityAttr>())
3803 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003804}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003805
John McCall384aff82010-08-25 07:42:41 +00003806CXXRecordDecl *Sema::getStdBadAlloc() const {
3807 return cast_or_null<CXXRecordDecl>(
3808 StdBadAlloc.get(Context.getExternalSource()));
3809}
3810
3811NamespaceDecl *Sema::getStdNamespace() const {
3812 return cast_or_null<NamespaceDecl>(
3813 StdNamespace.get(Context.getExternalSource()));
3814}
3815
Douglas Gregor66992202010-06-29 17:53:46 +00003816/// \brief Retrieve the special "std" namespace, which may require us to
3817/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003818NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003819 if (!StdNamespace) {
3820 // The "std" namespace has not yet been defined, so build one implicitly.
3821 StdNamespace = NamespaceDecl::Create(Context,
3822 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00003823 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00003824 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003825 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003826 }
3827
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003828 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003829}
3830
Douglas Gregor9172aa62011-03-26 22:25:30 +00003831/// \brief Determine whether a using statement is in a context where it will be
3832/// apply in all contexts.
3833static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3834 switch (CurContext->getDeclKind()) {
3835 case Decl::TranslationUnit:
3836 return true;
3837 case Decl::LinkageSpec:
3838 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3839 default:
3840 return false;
3841 }
3842}
3843
John McCalld226f652010-08-21 09:40:31 +00003844Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003845 SourceLocation UsingLoc,
3846 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003847 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003848 SourceLocation IdentLoc,
3849 IdentifierInfo *NamespcName,
3850 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003851 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3852 assert(NamespcName && "Invalid NamespcName.");
3853 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003854
3855 // This can only happen along a recovery path.
3856 while (S->getFlags() & Scope::TemplateParamScope)
3857 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003858 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003859
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003860 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003861 NestedNameSpecifier *Qualifier = 0;
3862 if (SS.isSet())
3863 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3864
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003865 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003866 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3867 LookupParsedName(R, S, &SS);
3868 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003869 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003870
Douglas Gregor66992202010-06-29 17:53:46 +00003871 if (R.empty()) {
3872 // Allow "using namespace std;" or "using namespace ::std;" even if
3873 // "std" hasn't been defined yet, for GCC compatibility.
3874 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3875 NamespcName->isStr("std")) {
3876 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003877 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003878 R.resolveKind();
3879 }
3880 // Otherwise, attempt typo correction.
3881 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3882 CTC_NoKeywords, 0)) {
3883 if (R.getAsSingle<NamespaceDecl>() ||
3884 R.getAsSingle<NamespaceAliasDecl>()) {
3885 if (DeclContext *DC = computeDeclContext(SS, false))
3886 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3887 << NamespcName << DC << Corrected << SS.getRange()
3888 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3889 else
3890 Diag(IdentLoc, diag::err_using_directive_suggest)
3891 << NamespcName << Corrected
3892 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3893 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3894 << Corrected;
3895
3896 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003897 } else {
3898 R.clear();
3899 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003900 }
3901 }
3902 }
3903
John McCallf36e02d2009-10-09 21:13:30 +00003904 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003905 NamedDecl *Named = R.getFoundDecl();
3906 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3907 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003908 // C++ [namespace.udir]p1:
3909 // A using-directive specifies that the names in the nominated
3910 // namespace can be used in the scope in which the
3911 // using-directive appears after the using-directive. During
3912 // unqualified name lookup (3.4.1), the names appear as if they
3913 // were declared in the nearest enclosing namespace which
3914 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003915 // namespace. [Note: in this context, "contains" means "contains
3916 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003917
3918 // Find enclosing context containing both using-directive and
3919 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003920 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003921 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3922 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3923 CommonAncestor = CommonAncestor->getParent();
3924
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003925 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00003926 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003927 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003928
Douglas Gregor9172aa62011-03-26 22:25:30 +00003929 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Douglas Gregord6a49bb2011-03-18 16:10:52 +00003930 !SourceMgr.isFromMainFile(IdentLoc)) {
3931 Diag(IdentLoc, diag::warn_using_directive_in_header);
3932 }
3933
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003934 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003935 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003936 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003937 }
3938
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003939 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003940 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003941}
3942
3943void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3944 // If scope has associated entity, then using directive is at namespace
3945 // or translation unit scope. We add UsingDirectiveDecls, into
3946 // it's lookup structure.
3947 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003948 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003949 else
3950 // Otherwise it is block-sope. using-directives will affect lookup
3951 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003952 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003953}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003954
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003955
John McCalld226f652010-08-21 09:40:31 +00003956Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003957 AccessSpecifier AS,
3958 bool HasUsingKeyword,
3959 SourceLocation UsingLoc,
3960 CXXScopeSpec &SS,
3961 UnqualifiedId &Name,
3962 AttributeList *AttrList,
3963 bool IsTypeName,
3964 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003965 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Douglas Gregor12c118a2009-11-04 16:30:06 +00003967 switch (Name.getKind()) {
3968 case UnqualifiedId::IK_Identifier:
3969 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003970 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003971 case UnqualifiedId::IK_ConversionFunctionId:
3972 break;
3973
3974 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003975 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003976 // C++0x inherited constructors.
3977 if (getLangOptions().CPlusPlus0x) break;
3978
Douglas Gregor12c118a2009-11-04 16:30:06 +00003979 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3980 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003981 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003982
3983 case UnqualifiedId::IK_DestructorName:
3984 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3985 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003986 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003987
3988 case UnqualifiedId::IK_TemplateId:
3989 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3990 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003991 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003992 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003993
3994 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3995 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003996 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003997 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003998
John McCall60fa3cf2009-12-11 02:10:03 +00003999 // Warn about using declarations.
4000 // TODO: store that the declaration was written without 'using' and
4001 // talk about access decls instead of using decls in the
4002 // diagnostics.
4003 if (!HasUsingKeyword) {
4004 UsingLoc = Name.getSourceRange().getBegin();
4005
4006 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00004007 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00004008 }
4009
Douglas Gregor56c04582010-12-16 00:46:58 +00004010 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4011 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4012 return 0;
4013
John McCall9488ea12009-11-17 05:59:44 +00004014 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004015 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004016 /* IsInstantiation */ false,
4017 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00004018 if (UD)
4019 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00004020
John McCalld226f652010-08-21 09:40:31 +00004021 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00004022}
4023
Douglas Gregor09acc982010-07-07 23:08:52 +00004024/// \brief Determine whether a using declaration considers the given
4025/// declarations as "equivalent", e.g., if they are redeclarations of
4026/// the same entity or are both typedefs of the same type.
4027static bool
4028IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4029 bool &SuppressRedeclaration) {
4030 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4031 SuppressRedeclaration = false;
4032 return true;
4033 }
4034
4035 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
4036 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
4037 SuppressRedeclaration = true;
4038 return Context.hasSameType(TD1->getUnderlyingType(),
4039 TD2->getUnderlyingType());
4040 }
4041
4042 return false;
4043}
4044
4045
John McCall9f54ad42009-12-10 09:41:52 +00004046/// Determines whether to create a using shadow decl for a particular
4047/// decl, given the set of decls existing prior to this using lookup.
4048bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4049 const LookupResult &Previous) {
4050 // Diagnose finding a decl which is not from a base class of the
4051 // current class. We do this now because there are cases where this
4052 // function will silently decide not to build a shadow decl, which
4053 // will pre-empt further diagnostics.
4054 //
4055 // We don't need to do this in C++0x because we do the check once on
4056 // the qualifier.
4057 //
4058 // FIXME: diagnose the following if we care enough:
4059 // struct A { int foo; };
4060 // struct B : A { using A::foo; };
4061 // template <class T> struct C : A {};
4062 // template <class T> struct D : C<T> { using B::foo; } // <---
4063 // This is invalid (during instantiation) in C++03 because B::foo
4064 // resolves to the using decl in B, which is not a base class of D<T>.
4065 // We can't diagnose it immediately because C<T> is an unknown
4066 // specialization. The UsingShadowDecl in D<T> then points directly
4067 // to A::foo, which will look well-formed when we instantiate.
4068 // The right solution is to not collapse the shadow-decl chain.
4069 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4070 DeclContext *OrigDC = Orig->getDeclContext();
4071
4072 // Handle enums and anonymous structs.
4073 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4074 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4075 while (OrigRec->isAnonymousStructOrUnion())
4076 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4077
4078 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4079 if (OrigDC == CurContext) {
4080 Diag(Using->getLocation(),
4081 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004082 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004083 Diag(Orig->getLocation(), diag::note_using_decl_target);
4084 return true;
4085 }
4086
Douglas Gregordc355712011-02-25 00:36:19 +00004087 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00004088 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00004089 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00004090 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00004091 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00004092 Diag(Orig->getLocation(), diag::note_using_decl_target);
4093 return true;
4094 }
4095 }
4096
4097 if (Previous.empty()) return false;
4098
4099 NamedDecl *Target = Orig;
4100 if (isa<UsingShadowDecl>(Target))
4101 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4102
John McCalld7533ec2009-12-11 02:33:26 +00004103 // If the target happens to be one of the previous declarations, we
4104 // don't have a conflict.
4105 //
4106 // FIXME: but we might be increasing its access, in which case we
4107 // should redeclare it.
4108 NamedDecl *NonTag = 0, *Tag = 0;
4109 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4110 I != E; ++I) {
4111 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00004112 bool Result;
4113 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4114 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00004115
4116 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4117 }
4118
John McCall9f54ad42009-12-10 09:41:52 +00004119 if (Target->isFunctionOrFunctionTemplate()) {
4120 FunctionDecl *FD;
4121 if (isa<FunctionTemplateDecl>(Target))
4122 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4123 else
4124 FD = cast<FunctionDecl>(Target);
4125
4126 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00004127 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00004128 case Ovl_Overload:
4129 return false;
4130
4131 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00004132 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004133 break;
4134
4135 // We found a decl with the exact signature.
4136 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004137 // If we're in a record, we want to hide the target, so we
4138 // return true (without a diagnostic) to tell the caller not to
4139 // build a shadow decl.
4140 if (CurContext->isRecord())
4141 return true;
4142
4143 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00004144 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004145 break;
4146 }
4147
4148 Diag(Target->getLocation(), diag::note_using_decl_target);
4149 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4150 return true;
4151 }
4152
4153 // Target is not a function.
4154
John McCall9f54ad42009-12-10 09:41:52 +00004155 if (isa<TagDecl>(Target)) {
4156 // No conflict between a tag and a non-tag.
4157 if (!Tag) return false;
4158
John McCall41ce66f2009-12-10 19:51:03 +00004159 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004160 Diag(Target->getLocation(), diag::note_using_decl_target);
4161 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4162 return true;
4163 }
4164
4165 // No conflict between a tag and a non-tag.
4166 if (!NonTag) return false;
4167
John McCall41ce66f2009-12-10 19:51:03 +00004168 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00004169 Diag(Target->getLocation(), diag::note_using_decl_target);
4170 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4171 return true;
4172}
4173
John McCall9488ea12009-11-17 05:59:44 +00004174/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00004175UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00004176 UsingDecl *UD,
4177 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00004178
4179 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00004180 NamedDecl *Target = Orig;
4181 if (isa<UsingShadowDecl>(Target)) {
4182 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4183 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00004184 }
4185
4186 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00004187 = UsingShadowDecl::Create(Context, CurContext,
4188 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00004189 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00004190
4191 Shadow->setAccess(UD->getAccess());
4192 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4193 Shadow->setInvalidDecl();
4194
John McCall9488ea12009-11-17 05:59:44 +00004195 if (S)
John McCall604e7f12009-12-08 07:46:18 +00004196 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00004197 else
John McCall604e7f12009-12-08 07:46:18 +00004198 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00004199
John McCall604e7f12009-12-08 07:46:18 +00004200
John McCall9f54ad42009-12-10 09:41:52 +00004201 return Shadow;
4202}
John McCall604e7f12009-12-08 07:46:18 +00004203
John McCall9f54ad42009-12-10 09:41:52 +00004204/// Hides a using shadow declaration. This is required by the current
4205/// using-decl implementation when a resolvable using declaration in a
4206/// class is followed by a declaration which would hide or override
4207/// one or more of the using decl's targets; for example:
4208///
4209/// struct Base { void foo(int); };
4210/// struct Derived : Base {
4211/// using Base::foo;
4212/// void foo(int);
4213/// };
4214///
4215/// The governing language is C++03 [namespace.udecl]p12:
4216///
4217/// When a using-declaration brings names from a base class into a
4218/// derived class scope, member functions in the derived class
4219/// override and/or hide member functions with the same name and
4220/// parameter types in a base class (rather than conflicting).
4221///
4222/// There are two ways to implement this:
4223/// (1) optimistically create shadow decls when they're not hidden
4224/// by existing declarations, or
4225/// (2) don't create any shadow decls (or at least don't make them
4226/// visible) until we've fully parsed/instantiated the class.
4227/// The problem with (1) is that we might have to retroactively remove
4228/// a shadow decl, which requires several O(n) operations because the
4229/// decl structures are (very reasonably) not designed for removal.
4230/// (2) avoids this but is very fiddly and phase-dependent.
4231void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00004232 if (Shadow->getDeclName().getNameKind() ==
4233 DeclarationName::CXXConversionFunctionName)
4234 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4235
John McCall9f54ad42009-12-10 09:41:52 +00004236 // Remove it from the DeclContext...
4237 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004238
John McCall9f54ad42009-12-10 09:41:52 +00004239 // ...and the scope, if applicable...
4240 if (S) {
John McCalld226f652010-08-21 09:40:31 +00004241 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00004242 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00004243 }
4244
John McCall9f54ad42009-12-10 09:41:52 +00004245 // ...and the using decl.
4246 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4247
4248 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00004249 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00004250}
4251
John McCall7ba107a2009-11-18 02:36:19 +00004252/// Builds a using declaration.
4253///
4254/// \param IsInstantiation - Whether this call arises from an
4255/// instantiation of an unresolved using declaration. We treat
4256/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00004257NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4258 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004259 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004260 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00004261 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00004262 bool IsInstantiation,
4263 bool IsTypeName,
4264 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00004265 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004266 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00004267 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00004268
Anders Carlsson550b14b2009-08-28 05:49:21 +00004269 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004271 if (SS.isEmpty()) {
4272 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00004273 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004274 }
Mike Stump1eb44332009-09-09 15:08:12 +00004275
John McCall9f54ad42009-12-10 09:41:52 +00004276 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004277 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00004278 ForRedeclaration);
4279 Previous.setHideTags(false);
4280 if (S) {
4281 LookupName(Previous, S);
4282
4283 // It is really dumb that we have to do this.
4284 LookupResult::Filter F = Previous.makeFilter();
4285 while (F.hasNext()) {
4286 NamedDecl *D = F.next();
4287 if (!isDeclInScope(D, CurContext, S))
4288 F.erase();
4289 }
4290 F.done();
4291 } else {
4292 assert(IsInstantiation && "no scope in non-instantiation");
4293 assert(CurContext->isRecord() && "scope not record in instantiation");
4294 LookupQualifiedName(Previous, CurContext);
4295 }
4296
John McCall9f54ad42009-12-10 09:41:52 +00004297 // Check for invalid redeclarations.
4298 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4299 return 0;
4300
4301 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00004302 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4303 return 0;
4304
John McCallaf8e6ed2009-11-12 03:15:40 +00004305 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004306 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00004307 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00004308 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00004309 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00004310 // FIXME: not all declaration name kinds are legal here
4311 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4312 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00004313 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004314 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00004315 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004316 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4317 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00004318 }
John McCalled976492009-12-04 22:46:56 +00004319 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00004320 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4321 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00004322 }
John McCalled976492009-12-04 22:46:56 +00004323 D->setAccess(AS);
4324 CurContext->addDecl(D);
4325
4326 if (!LookupContext) return D;
4327 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004328
John McCall77bb1aa2010-05-01 00:40:08 +00004329 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00004330 UD->setInvalidDecl();
4331 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004332 }
4333
Sebastian Redlf677ea32011-02-05 19:23:19 +00004334 // Constructor inheriting using decls get special treatment.
4335 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004336 if (CheckInheritedConstructorUsingDecl(UD))
4337 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004338 return UD;
4339 }
4340
4341 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00004342
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004343 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00004344
John McCall604e7f12009-12-08 07:46:18 +00004345 // Unlike most lookups, we don't always want to hide tag
4346 // declarations: tag names are visible through the using declaration
4347 // even if hidden by ordinary names, *except* in a dependent context
4348 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00004349 if (!IsInstantiation)
4350 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00004351
John McCalla24dc2e2009-11-17 02:14:36 +00004352 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004353
John McCallf36e02d2009-10-09 21:13:30 +00004354 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00004355 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00004356 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004357 UD->setInvalidDecl();
4358 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004359 }
4360
John McCalled976492009-12-04 22:46:56 +00004361 if (R.isAmbiguous()) {
4362 UD->setInvalidDecl();
4363 return UD;
4364 }
Mike Stump1eb44332009-09-09 15:08:12 +00004365
John McCall7ba107a2009-11-18 02:36:19 +00004366 if (IsTypeName) {
4367 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00004368 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004369 Diag(IdentLoc, diag::err_using_typename_non_type);
4370 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4371 Diag((*I)->getUnderlyingDecl()->getLocation(),
4372 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004373 UD->setInvalidDecl();
4374 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004375 }
4376 } else {
4377 // If we asked for a non-typename and we got a type, error out,
4378 // but only if this is an instantiation of an unresolved using
4379 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004380 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004381 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4382 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004383 UD->setInvalidDecl();
4384 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004385 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004386 }
4387
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004388 // C++0x N2914 [namespace.udecl]p6:
4389 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004390 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004391 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4392 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004393 UD->setInvalidDecl();
4394 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004395 }
Mike Stump1eb44332009-09-09 15:08:12 +00004396
John McCall9f54ad42009-12-10 09:41:52 +00004397 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4398 if (!CheckUsingShadowDecl(UD, *I, Previous))
4399 BuildUsingShadowDecl(S, UD, *I);
4400 }
John McCall9488ea12009-11-17 05:59:44 +00004401
4402 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004403}
4404
Sebastian Redlf677ea32011-02-05 19:23:19 +00004405/// Additional checks for a using declaration referring to a constructor name.
4406bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4407 if (UD->isTypeName()) {
4408 // FIXME: Cannot specify typename when specifying constructor
4409 return true;
4410 }
4411
Douglas Gregordc355712011-02-25 00:36:19 +00004412 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00004413 assert(SourceType &&
4414 "Using decl naming constructor doesn't have type in scope spec.");
4415 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4416
4417 // Check whether the named type is a direct base class.
4418 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4419 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4420 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4421 BaseIt != BaseE; ++BaseIt) {
4422 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4423 if (CanonicalSourceType == BaseType)
4424 break;
4425 }
4426
4427 if (BaseIt == BaseE) {
4428 // Did not find SourceType in the bases.
4429 Diag(UD->getUsingLocation(),
4430 diag::err_using_decl_constructor_not_in_direct_base)
4431 << UD->getNameInfo().getSourceRange()
4432 << QualType(SourceType, 0) << TargetClass;
4433 return true;
4434 }
4435
4436 BaseIt->setInheritConstructors();
4437
4438 return false;
4439}
4440
John McCall9f54ad42009-12-10 09:41:52 +00004441/// Checks that the given using declaration is not an invalid
4442/// redeclaration. Note that this is checking only for the using decl
4443/// itself, not for any ill-formedness among the UsingShadowDecls.
4444bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4445 bool isTypeName,
4446 const CXXScopeSpec &SS,
4447 SourceLocation NameLoc,
4448 const LookupResult &Prev) {
4449 // C++03 [namespace.udecl]p8:
4450 // C++0x [namespace.udecl]p10:
4451 // A using-declaration is a declaration and can therefore be used
4452 // repeatedly where (and only where) multiple declarations are
4453 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004454 //
John McCall8a726212010-11-29 18:01:58 +00004455 // That's in non-member contexts.
4456 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004457 return false;
4458
4459 NestedNameSpecifier *Qual
4460 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4461
4462 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4463 NamedDecl *D = *I;
4464
4465 bool DTypename;
4466 NestedNameSpecifier *DQual;
4467 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4468 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00004469 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004470 } else if (UnresolvedUsingValueDecl *UD
4471 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4472 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00004473 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004474 } else if (UnresolvedUsingTypenameDecl *UD
4475 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4476 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00004477 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00004478 } else continue;
4479
4480 // using decls differ if one says 'typename' and the other doesn't.
4481 // FIXME: non-dependent using decls?
4482 if (isTypeName != DTypename) continue;
4483
4484 // using decls differ if they name different scopes (but note that
4485 // template instantiation can cause this check to trigger when it
4486 // didn't before instantiation).
4487 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4488 Context.getCanonicalNestedNameSpecifier(DQual))
4489 continue;
4490
4491 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004492 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004493 return true;
4494 }
4495
4496 return false;
4497}
4498
John McCall604e7f12009-12-08 07:46:18 +00004499
John McCalled976492009-12-04 22:46:56 +00004500/// Checks that the given nested-name qualifier used in a using decl
4501/// in the current context is appropriately related to the current
4502/// scope. If an error is found, diagnoses it and returns true.
4503bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4504 const CXXScopeSpec &SS,
4505 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004506 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004507
John McCall604e7f12009-12-08 07:46:18 +00004508 if (!CurContext->isRecord()) {
4509 // C++03 [namespace.udecl]p3:
4510 // C++0x [namespace.udecl]p8:
4511 // A using-declaration for a class member shall be a member-declaration.
4512
4513 // If we weren't able to compute a valid scope, it must be a
4514 // dependent class scope.
4515 if (!NamedContext || NamedContext->isRecord()) {
4516 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4517 << SS.getRange();
4518 return true;
4519 }
4520
4521 // Otherwise, everything is known to be fine.
4522 return false;
4523 }
4524
4525 // The current scope is a record.
4526
4527 // If the named context is dependent, we can't decide much.
4528 if (!NamedContext) {
4529 // FIXME: in C++0x, we can diagnose if we can prove that the
4530 // nested-name-specifier does not refer to a base class, which is
4531 // still possible in some cases.
4532
4533 // Otherwise we have to conservatively report that things might be
4534 // okay.
4535 return false;
4536 }
4537
4538 if (!NamedContext->isRecord()) {
4539 // Ideally this would point at the last name in the specifier,
4540 // but we don't have that level of source info.
4541 Diag(SS.getRange().getBegin(),
4542 diag::err_using_decl_nested_name_specifier_is_not_class)
4543 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4544 return true;
4545 }
4546
Douglas Gregor6fb07292010-12-21 07:41:49 +00004547 if (!NamedContext->isDependentContext() &&
4548 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4549 return true;
4550
John McCall604e7f12009-12-08 07:46:18 +00004551 if (getLangOptions().CPlusPlus0x) {
4552 // C++0x [namespace.udecl]p3:
4553 // In a using-declaration used as a member-declaration, the
4554 // nested-name-specifier shall name a base class of the class
4555 // being defined.
4556
4557 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4558 cast<CXXRecordDecl>(NamedContext))) {
4559 if (CurContext == NamedContext) {
4560 Diag(NameLoc,
4561 diag::err_using_decl_nested_name_specifier_is_current_class)
4562 << SS.getRange();
4563 return true;
4564 }
4565
4566 Diag(SS.getRange().getBegin(),
4567 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4568 << (NestedNameSpecifier*) SS.getScopeRep()
4569 << cast<CXXRecordDecl>(CurContext)
4570 << SS.getRange();
4571 return true;
4572 }
4573
4574 return false;
4575 }
4576
4577 // C++03 [namespace.udecl]p4:
4578 // A using-declaration used as a member-declaration shall refer
4579 // to a member of a base class of the class being defined [etc.].
4580
4581 // Salient point: SS doesn't have to name a base class as long as
4582 // lookup only finds members from base classes. Therefore we can
4583 // diagnose here only if we can prove that that can't happen,
4584 // i.e. if the class hierarchies provably don't intersect.
4585
4586 // TODO: it would be nice if "definitely valid" results were cached
4587 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4588 // need to be repeated.
4589
4590 struct UserData {
4591 llvm::DenseSet<const CXXRecordDecl*> Bases;
4592
4593 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4594 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4595 Data->Bases.insert(Base);
4596 return true;
4597 }
4598
4599 bool hasDependentBases(const CXXRecordDecl *Class) {
4600 return !Class->forallBases(collect, this);
4601 }
4602
4603 /// Returns true if the base is dependent or is one of the
4604 /// accumulated base classes.
4605 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4606 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4607 return !Data->Bases.count(Base);
4608 }
4609
4610 bool mightShareBases(const CXXRecordDecl *Class) {
4611 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4612 }
4613 };
4614
4615 UserData Data;
4616
4617 // Returns false if we find a dependent base.
4618 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4619 return false;
4620
4621 // Returns false if the class has a dependent base or if it or one
4622 // of its bases is present in the base set of the current context.
4623 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4624 return false;
4625
4626 Diag(SS.getRange().getBegin(),
4627 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4628 << (NestedNameSpecifier*) SS.getScopeRep()
4629 << cast<CXXRecordDecl>(CurContext)
4630 << SS.getRange();
4631
4632 return true;
John McCalled976492009-12-04 22:46:56 +00004633}
4634
John McCalld226f652010-08-21 09:40:31 +00004635Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004636 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004637 SourceLocation AliasLoc,
4638 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004639 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004640 SourceLocation IdentLoc,
4641 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Anders Carlsson81c85c42009-03-28 23:53:49 +00004643 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004644 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4645 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004646
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004647 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004648 NamedDecl *PrevDecl
4649 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4650 ForRedeclaration);
4651 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4652 PrevDecl = 0;
4653
4654 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004655 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004656 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004657 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004658 // FIXME: At some point, we'll want to create the (redundant)
4659 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004660 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004661 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004662 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004663 }
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004665 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4666 diag::err_redefinition_different_kind;
4667 Diag(AliasLoc, DiagID) << Alias;
4668 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004669 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004670 }
4671
John McCalla24dc2e2009-11-17 02:14:36 +00004672 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004673 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004674
John McCallf36e02d2009-10-09 21:13:30 +00004675 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004676 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4677 CTC_NoKeywords, 0)) {
4678 if (R.getAsSingle<NamespaceDecl>() ||
4679 R.getAsSingle<NamespaceAliasDecl>()) {
4680 if (DeclContext *DC = computeDeclContext(SS, false))
4681 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4682 << Ident << DC << Corrected << SS.getRange()
4683 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4684 else
4685 Diag(IdentLoc, diag::err_using_directive_suggest)
4686 << Ident << Corrected
4687 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4688
4689 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4690 << Corrected;
4691
4692 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004693 } else {
4694 R.clear();
4695 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004696 }
4697 }
4698
4699 if (R.empty()) {
4700 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004701 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004702 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004703 }
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004705 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004706 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00004707 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00004708 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004709
John McCall3dbd3d52010-02-16 06:53:13 +00004710 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004711 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004712}
4713
Douglas Gregor39957dc2010-05-01 15:04:51 +00004714namespace {
4715 /// \brief Scoped object used to handle the state changes required in Sema
4716 /// to implicitly define the body of a C++ member function;
4717 class ImplicitlyDefinedFunctionScope {
4718 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00004719 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00004720
4721 public:
4722 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00004723 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00004724 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00004725 S.PushFunctionScope();
4726 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4727 }
4728
4729 ~ImplicitlyDefinedFunctionScope() {
4730 S.PopExpressionEvaluationContext();
4731 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00004732 }
4733 };
4734}
4735
Sebastian Redl751025d2010-09-13 22:02:47 +00004736static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4737 CXXRecordDecl *D) {
4738 ASTContext &Context = Self.Context;
4739 QualType ClassType = Context.getTypeDeclType(D);
4740 DeclarationName ConstructorName
4741 = Context.DeclarationNames.getCXXConstructorName(
4742 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4743
4744 DeclContext::lookup_const_iterator Con, ConEnd;
4745 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4746 Con != ConEnd; ++Con) {
4747 // FIXME: In C++0x, a constructor template can be a default constructor.
4748 if (isa<FunctionTemplateDecl>(*Con))
4749 continue;
4750
4751 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4752 if (Constructor->isDefaultConstructor())
4753 return Constructor;
4754 }
4755 return 0;
4756}
4757
Douglas Gregor23c94db2010-07-02 17:43:08 +00004758CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4759 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004760 // C++ [class.ctor]p5:
4761 // A default constructor for a class X is a constructor of class X
4762 // that can be called without an argument. If there is no
4763 // user-declared constructor for class X, a default constructor is
4764 // implicitly declared. An implicitly-declared default constructor
4765 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004766 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4767 "Should not build implicit default constructor!");
4768
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004769 // C++ [except.spec]p14:
4770 // An implicitly declared special member function (Clause 12) shall have an
4771 // exception-specification. [...]
4772 ImplicitExceptionSpecification ExceptSpec(Context);
4773
Sebastian Redl60618fa2011-03-12 11:50:43 +00004774 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004775 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4776 BEnd = ClassDecl->bases_end();
4777 B != BEnd; ++B) {
4778 if (B->isVirtual()) // Handled below.
4779 continue;
4780
Douglas Gregor18274032010-07-03 00:47:00 +00004781 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4783 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4784 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004785 else if (CXXConstructorDecl *Constructor
4786 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004787 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004788 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004789 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004790
4791 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004792 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4793 BEnd = ClassDecl->vbases_end();
4794 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004795 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4796 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4797 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4798 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4799 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004800 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004801 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004802 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004803 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00004804
4805 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004806 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4807 FEnd = ClassDecl->field_end();
4808 F != FEnd; ++F) {
4809 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004810 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4811 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4812 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4813 ExceptSpec.CalledDecl(
4814 DeclareImplicitDefaultConstructor(FieldClassDecl));
4815 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004816 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004817 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004818 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004819 }
John McCalle23cf432010-12-14 08:05:40 +00004820
4821 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00004822 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00004823 EPI.NumExceptions = ExceptSpec.size();
4824 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00004825
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004826 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004827 CanQualType ClassType
4828 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004829 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00004830 DeclarationName Name
4831 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004832 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00004833 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004834 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004835 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004836 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004837 /*TInfo=*/0,
4838 /*isExplicit=*/false,
4839 /*isInline=*/true,
4840 /*isImplicitlyDeclared=*/true);
4841 DefaultCon->setAccess(AS_public);
4842 DefaultCon->setImplicit();
4843 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004844
4845 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004846 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4847
Douglas Gregor23c94db2010-07-02 17:43:08 +00004848 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004849 PushOnScopeChains(DefaultCon, S, false);
4850 ClassDecl->addDecl(DefaultCon);
4851
Douglas Gregor32df23e2010-07-01 22:02:46 +00004852 return DefaultCon;
4853}
4854
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004855void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4856 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004857 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004858 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004859 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004860
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004861 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004862 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004863
Douglas Gregor39957dc2010-05-01 15:04:51 +00004864 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004865 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00004866 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004867 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004868 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004869 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004870 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004871 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004872 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004873
4874 SourceLocation Loc = Constructor->getLocation();
4875 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4876
4877 Constructor->setUsed();
4878 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004879}
4880
Sebastian Redlf677ea32011-02-05 19:23:19 +00004881void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4882 // We start with an initial pass over the base classes to collect those that
4883 // inherit constructors from. If there are none, we can forgo all further
4884 // processing.
4885 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4886 BasesVector BasesToInheritFrom;
4887 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4888 BaseE = ClassDecl->bases_end();
4889 BaseIt != BaseE; ++BaseIt) {
4890 if (BaseIt->getInheritConstructors()) {
4891 QualType Base = BaseIt->getType();
4892 if (Base->isDependentType()) {
4893 // If we inherit constructors from anything that is dependent, just
4894 // abort processing altogether. We'll get another chance for the
4895 // instantiations.
4896 return;
4897 }
4898 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4899 }
4900 }
4901 if (BasesToInheritFrom.empty())
4902 return;
4903
4904 // Now collect the constructors that we already have in the current class.
4905 // Those take precedence over inherited constructors.
4906 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4907 // unless there is a user-declared constructor with the same signature in
4908 // the class where the using-declaration appears.
4909 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4910 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4911 CtorE = ClassDecl->ctor_end();
4912 CtorIt != CtorE; ++CtorIt) {
4913 ExistingConstructors.insert(
4914 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4915 }
4916
4917 Scope *S = getScopeForContext(ClassDecl);
4918 DeclarationName CreatedCtorName =
4919 Context.DeclarationNames.getCXXConstructorName(
4920 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4921
4922 // Now comes the true work.
4923 // First, we keep a map from constructor types to the base that introduced
4924 // them. Needed for finding conflicting constructors. We also keep the
4925 // actually inserted declarations in there, for pretty diagnostics.
4926 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4927 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4928 ConstructorToSourceMap InheritedConstructors;
4929 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4930 BaseE = BasesToInheritFrom.end();
4931 BaseIt != BaseE; ++BaseIt) {
4932 const RecordType *Base = *BaseIt;
4933 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4934 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4935 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4936 CtorE = BaseDecl->ctor_end();
4937 CtorIt != CtorE; ++CtorIt) {
4938 // Find the using declaration for inheriting this base's constructors.
4939 DeclarationName Name =
4940 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4941 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4942 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4943 SourceLocation UsingLoc = UD ? UD->getLocation() :
4944 ClassDecl->getLocation();
4945
4946 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4947 // from the class X named in the using-declaration consists of actual
4948 // constructors and notional constructors that result from the
4949 // transformation of defaulted parameters as follows:
4950 // - all non-template default constructors of X, and
4951 // - for each non-template constructor of X that has at least one
4952 // parameter with a default argument, the set of constructors that
4953 // results from omitting any ellipsis parameter specification and
4954 // successively omitting parameters with a default argument from the
4955 // end of the parameter-type-list.
4956 CXXConstructorDecl *BaseCtor = *CtorIt;
4957 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4958 const FunctionProtoType *BaseCtorType =
4959 BaseCtor->getType()->getAs<FunctionProtoType>();
4960
4961 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4962 maxParams = BaseCtor->getNumParams();
4963 params <= maxParams; ++params) {
4964 // Skip default constructors. They're never inherited.
4965 if (params == 0)
4966 continue;
4967 // Skip copy and move constructors for the same reason.
4968 if (CanBeCopyOrMove && params == 1)
4969 continue;
4970
4971 // Build up a function type for this particular constructor.
4972 // FIXME: The working paper does not consider that the exception spec
4973 // for the inheriting constructor might be larger than that of the
4974 // source. This code doesn't yet, either.
4975 const Type *NewCtorType;
4976 if (params == maxParams)
4977 NewCtorType = BaseCtorType;
4978 else {
4979 llvm::SmallVector<QualType, 16> Args;
4980 for (unsigned i = 0; i < params; ++i) {
4981 Args.push_back(BaseCtorType->getArgType(i));
4982 }
4983 FunctionProtoType::ExtProtoInfo ExtInfo =
4984 BaseCtorType->getExtProtoInfo();
4985 ExtInfo.Variadic = false;
4986 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4987 Args.data(), params, ExtInfo)
4988 .getTypePtr();
4989 }
4990 const Type *CanonicalNewCtorType =
4991 Context.getCanonicalType(NewCtorType);
4992
4993 // Now that we have the type, first check if the class already has a
4994 // constructor with this signature.
4995 if (ExistingConstructors.count(CanonicalNewCtorType))
4996 continue;
4997
4998 // Then we check if we have already declared an inherited constructor
4999 // with this signature.
5000 std::pair<ConstructorToSourceMap::iterator, bool> result =
5001 InheritedConstructors.insert(std::make_pair(
5002 CanonicalNewCtorType,
5003 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5004 if (!result.second) {
5005 // Already in the map. If it came from a different class, that's an
5006 // error. Not if it's from the same.
5007 CanQualType PreviousBase = result.first->second.first;
5008 if (CanonicalBase != PreviousBase) {
5009 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5010 const CXXConstructorDecl *PrevBaseCtor =
5011 PrevCtor->getInheritedConstructor();
5012 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5013
5014 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5015 Diag(BaseCtor->getLocation(),
5016 diag::note_using_decl_constructor_conflict_current_ctor);
5017 Diag(PrevBaseCtor->getLocation(),
5018 diag::note_using_decl_constructor_conflict_previous_ctor);
5019 Diag(PrevCtor->getLocation(),
5020 diag::note_using_decl_constructor_conflict_previous_using);
5021 }
5022 continue;
5023 }
5024
5025 // OK, we're there, now add the constructor.
5026 // C++0x [class.inhctor]p8: [...] that would be performed by a
5027 // user-writtern inline constructor [...]
5028 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5029 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005030 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5031 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005032 /*ImplicitlyDeclared=*/true);
5033 NewCtor->setAccess(BaseCtor->getAccess());
5034
5035 // Build up the parameter decls and add them.
5036 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5037 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005038 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5039 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00005040 /*IdentifierInfo=*/0,
5041 BaseCtorType->getArgType(i),
5042 /*TInfo=*/0, SC_None,
5043 SC_None, /*DefaultArg=*/0));
5044 }
5045 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5046 NewCtor->setInheritedConstructor(BaseCtor);
5047
5048 PushOnScopeChains(NewCtor, S, false);
5049 ClassDecl->addDecl(NewCtor);
5050 result.first->second.second = NewCtor;
5051 }
5052 }
5053 }
5054}
5055
Douglas Gregor23c94db2010-07-02 17:43:08 +00005056CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005057 // C++ [class.dtor]p2:
5058 // If a class has no user-declared destructor, a destructor is
5059 // declared implicitly. An implicitly-declared destructor is an
5060 // inline public member of its class.
5061
5062 // C++ [except.spec]p14:
5063 // An implicitly declared special member function (Clause 12) shall have
5064 // an exception-specification.
5065 ImplicitExceptionSpecification ExceptSpec(Context);
5066
5067 // Direct base-class destructors.
5068 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5069 BEnd = ClassDecl->bases_end();
5070 B != BEnd; ++B) {
5071 if (B->isVirtual()) // Handled below.
5072 continue;
5073
5074 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5075 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005076 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005077 }
5078
5079 // Virtual base-class destructors.
5080 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5081 BEnd = ClassDecl->vbases_end();
5082 B != BEnd; ++B) {
5083 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5084 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005085 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005086 }
5087
5088 // Field destructors.
5089 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5090 FEnd = ClassDecl->field_end();
5091 F != FEnd; ++F) {
5092 if (const RecordType *RecordTy
5093 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5094 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00005095 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005096 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005097
Douglas Gregor4923aa22010-07-02 20:37:36 +00005098 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00005099 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005100 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005101 EPI.NumExceptions = ExceptSpec.size();
5102 EPI.Exceptions = ExceptSpec.data();
5103 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00005104
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005105 CanQualType ClassType
5106 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005107 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005108 DeclarationName Name
5109 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005110 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005111 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00005112 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5113 /*isInline=*/true,
5114 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005115 Destructor->setAccess(AS_public);
5116 Destructor->setImplicit();
5117 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00005118
5119 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00005120 ++ASTContext::NumImplicitDestructorsDeclared;
5121
5122 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005123 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00005124 PushOnScopeChains(Destructor, S, false);
5125 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005126
5127 // This could be uniqued if it ever proves significant.
5128 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5129
5130 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00005131
Douglas Gregorfabd43a2010-07-01 19:09:28 +00005132 return Destructor;
5133}
5134
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005135void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00005136 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00005137 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005138 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00005139 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005140 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005141
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005142 if (Destructor->isInvalidDecl())
5143 return;
5144
Douglas Gregor39957dc2010-05-01 15:04:51 +00005145 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005146
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005147 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00005148 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5149 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00005150
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005151 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00005152 Diag(CurrentLocation, diag::note_member_synthesized_at)
5153 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5154
5155 Destructor->setInvalidDecl();
5156 return;
5157 }
5158
Douglas Gregor4ada9d32010-09-20 16:48:21 +00005159 SourceLocation Loc = Destructor->getLocation();
5160 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5161
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005162 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005163 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005164}
5165
Douglas Gregor06a9f362010-05-01 20:49:11 +00005166/// \brief Builds a statement that copies the given entity from \p From to
5167/// \c To.
5168///
5169/// This routine is used to copy the members of a class with an
5170/// implicitly-declared copy assignment operator. When the entities being
5171/// copied are arrays, this routine builds for loops to copy them.
5172///
5173/// \param S The Sema object used for type-checking.
5174///
5175/// \param Loc The location where the implicit copy is being generated.
5176///
5177/// \param T The type of the expressions being copied. Both expressions must
5178/// have this type.
5179///
5180/// \param To The expression we are copying to.
5181///
5182/// \param From The expression we are copying from.
5183///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005184/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5185/// Otherwise, it's a non-static member subobject.
5186///
Douglas Gregor06a9f362010-05-01 20:49:11 +00005187/// \param Depth Internal parameter recording the depth of the recursion.
5188///
5189/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005190static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00005191BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00005192 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005193 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005194 // C++0x [class.copy]p30:
5195 // Each subobject is assigned in the manner appropriate to its type:
5196 //
5197 // - if the subobject is of class type, the copy assignment operator
5198 // for the class is used (as if by explicit qualification; that is,
5199 // ignoring any possible virtual overriding functions in more derived
5200 // classes);
5201 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5202 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5203
5204 // Look for operator=.
5205 DeclarationName Name
5206 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5207 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5208 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5209
5210 // Filter out any result that isn't a copy-assignment operator.
5211 LookupResult::Filter F = OpLookup.makeFilter();
5212 while (F.hasNext()) {
5213 NamedDecl *D = F.next();
5214 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5215 if (Method->isCopyAssignmentOperator())
5216 continue;
5217
5218 F.erase();
John McCallb0207482010-03-16 06:11:48 +00005219 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005220 F.done();
5221
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005222 // Suppress the protected check (C++ [class.protected]) for each of the
5223 // assignment operators we found. This strange dance is required when
5224 // we're assigning via a base classes's copy-assignment operator. To
5225 // ensure that we're getting the right base class subobject (without
5226 // ambiguities), we need to cast "this" to that subobject type; to
5227 // ensure that we don't go through the virtual call mechanism, we need
5228 // to qualify the operator= name with the base class (see below). However,
5229 // this means that if the base class has a protected copy assignment
5230 // operator, the protected member access check will fail. So, we
5231 // rewrite "protected" access to "public" access in this case, since we
5232 // know by construction that we're calling from a derived class.
5233 if (CopyingBaseSubobject) {
5234 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5235 L != LEnd; ++L) {
5236 if (L.getAccess() == AS_protected)
5237 L.setAccess(AS_public);
5238 }
5239 }
5240
Douglas Gregor06a9f362010-05-01 20:49:11 +00005241 // Create the nested-name-specifier that will be used to qualify the
5242 // reference to operator=; this is required to suppress the virtual
5243 // call mechanism.
5244 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00005245 SS.MakeTrivial(S.Context,
5246 NestedNameSpecifier::Create(S.Context, 0, false,
5247 T.getTypePtr()),
5248 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005249
5250 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00005251 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00005252 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005253 /*FirstQualifierInScope=*/0, OpLookup,
5254 /*TemplateArgs=*/0,
5255 /*SuppressQualifierCheck=*/true);
5256 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005257 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005258
5259 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00005260
John McCall60d7b3a2010-08-24 06:29:42 +00005261 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00005262 OpEqualRef.takeAs<Expr>(),
5263 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005264 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005265 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005266
5267 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005268 }
John McCallb0207482010-03-16 06:11:48 +00005269
Douglas Gregor06a9f362010-05-01 20:49:11 +00005270 // - if the subobject is of scalar type, the built-in assignment
5271 // operator is used.
5272 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5273 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00005274 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005275 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005276 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005277
5278 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005279 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005280
5281 // - if the subobject is an array, each element is assigned, in the
5282 // manner appropriate to the element type;
5283
5284 // Construct a loop over the array bounds, e.g.,
5285 //
5286 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5287 //
5288 // that will copy each of the array elements.
5289 QualType SizeType = S.Context.getSizeType();
5290
5291 // Create the iteration variable.
5292 IdentifierInfo *IterationVarName = 0;
5293 {
5294 llvm::SmallString<8> Str;
5295 llvm::raw_svector_ostream OS(Str);
5296 OS << "__i" << Depth;
5297 IterationVarName = &S.Context.Idents.get(OS.str());
5298 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005299 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005300 IterationVarName, SizeType,
5301 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00005302 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005303
5304 // Initialize the iteration variable to zero.
5305 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005306 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005307
5308 // Create a reference to the iteration variable; we'll use this several
5309 // times throughout.
5310 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00005311 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005312 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5313
5314 // Create the DeclStmt that holds the iteration variable.
5315 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5316
5317 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005318 llvm::APInt Upper
5319 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00005320 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00005321 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00005322 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5323 BO_NE, S.Context.BoolTy,
5324 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005325
5326 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005327 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00005328 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5329 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005330
5331 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00005332 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5333 IterationVarRef, Loc));
5334 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5335 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005336
5337 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00005338 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5339 To, From, CopyingBaseSubobject,
5340 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00005341 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005342 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005343
5344 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00005345 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005346 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00005347 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00005348 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005349}
5350
Douglas Gregora376d102010-07-02 21:50:04 +00005351/// \brief Determine whether the given class has a copy assignment operator
5352/// that accepts a const-qualified argument.
5353static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5354 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5355
5356 if (!Class->hasDeclaredCopyAssignment())
5357 S.DeclareImplicitCopyAssignment(Class);
5358
5359 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5360 DeclarationName OpName
5361 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5362
5363 DeclContext::lookup_const_iterator Op, OpEnd;
5364 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5365 // C++ [class.copy]p9:
5366 // A user-declared copy assignment operator is a non-static non-template
5367 // member function of class X with exactly one parameter of type X, X&,
5368 // const X&, volatile X& or const volatile X&.
5369 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5370 if (!Method)
5371 continue;
5372
5373 if (Method->isStatic())
5374 continue;
5375 if (Method->getPrimaryTemplate())
5376 continue;
5377 const FunctionProtoType *FnType =
5378 Method->getType()->getAs<FunctionProtoType>();
5379 assert(FnType && "Overloaded operator has no prototype.");
5380 // Don't assert on this; an invalid decl might have been left in the AST.
5381 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5382 continue;
5383 bool AcceptsConst = true;
5384 QualType ArgType = FnType->getArgType(0);
5385 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5386 ArgType = Ref->getPointeeType();
5387 // Is it a non-const lvalue reference?
5388 if (!ArgType.isConstQualified())
5389 AcceptsConst = false;
5390 }
5391 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5392 continue;
5393
5394 // We have a single argument of type cv X or cv X&, i.e. we've found the
5395 // copy assignment operator. Return whether it accepts const arguments.
5396 return AcceptsConst;
5397 }
5398 assert(Class->isInvalidDecl() &&
5399 "No copy assignment operator declared in valid code.");
5400 return false;
5401}
5402
Douglas Gregor23c94db2010-07-02 17:43:08 +00005403CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00005404 // Note: The following rules are largely analoguous to the copy
5405 // constructor rules. Note that virtual bases are not taken into account
5406 // for determining the argument type of the operator. Note also that
5407 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00005408
5409
Douglas Gregord3c35902010-07-01 16:36:15 +00005410 // C++ [class.copy]p10:
5411 // If the class definition does not explicitly declare a copy
5412 // assignment operator, one is declared implicitly.
5413 // The implicitly-defined copy assignment operator for a class X
5414 // will have the form
5415 //
5416 // X& X::operator=(const X&)
5417 //
5418 // if
5419 bool HasConstCopyAssignment = true;
5420
5421 // -- each direct base class B of X has a copy assignment operator
5422 // whose parameter is of type const B&, const volatile B& or B,
5423 // and
5424 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5425 BaseEnd = ClassDecl->bases_end();
5426 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5427 assert(!Base->getType()->isDependentType() &&
5428 "Cannot generate implicit members for class with dependent bases.");
5429 const CXXRecordDecl *BaseClassDecl
5430 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005431 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005432 }
5433
5434 // -- for all the nonstatic data members of X that are of a class
5435 // type M (or array thereof), each such class type has a copy
5436 // assignment operator whose parameter is of type const M&,
5437 // const volatile M& or M.
5438 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5439 FieldEnd = ClassDecl->field_end();
5440 HasConstCopyAssignment && Field != FieldEnd;
5441 ++Field) {
5442 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5443 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5444 const CXXRecordDecl *FieldClassDecl
5445 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005446 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00005447 }
5448 }
5449
5450 // Otherwise, the implicitly declared copy assignment operator will
5451 // have the form
5452 //
5453 // X& X::operator=(X&)
5454 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5455 QualType RetType = Context.getLValueReferenceType(ArgType);
5456 if (HasConstCopyAssignment)
5457 ArgType = ArgType.withConst();
5458 ArgType = Context.getLValueReferenceType(ArgType);
5459
Douglas Gregorb87786f2010-07-01 17:48:08 +00005460 // C++ [except.spec]p14:
5461 // An implicitly declared special member function (Clause 12) shall have an
5462 // exception-specification. [...]
5463 ImplicitExceptionSpecification ExceptSpec(Context);
5464 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5465 BaseEnd = ClassDecl->bases_end();
5466 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00005467 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005468 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005469
5470 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5471 DeclareImplicitCopyAssignment(BaseClassDecl);
5472
Douglas Gregorb87786f2010-07-01 17:48:08 +00005473 if (CXXMethodDecl *CopyAssign
5474 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5475 ExceptSpec.CalledDecl(CopyAssign);
5476 }
5477 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5478 FieldEnd = ClassDecl->field_end();
5479 Field != FieldEnd;
5480 ++Field) {
5481 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5482 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00005483 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00005484 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00005485
5486 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5487 DeclareImplicitCopyAssignment(FieldClassDecl);
5488
Douglas Gregorb87786f2010-07-01 17:48:08 +00005489 if (CXXMethodDecl *CopyAssign
5490 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5491 ExceptSpec.CalledDecl(CopyAssign);
5492 }
5493 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005494
Douglas Gregord3c35902010-07-01 16:36:15 +00005495 // An implicitly-declared copy assignment operator is an inline public
5496 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005497 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005498 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005499 EPI.NumExceptions = ExceptSpec.size();
5500 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00005501 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005502 SourceLocation ClassLoc = ClassDecl->getLocation();
5503 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00005504 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005505 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00005506 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00005507 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00005508 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00005509 /*isInline=*/true,
5510 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00005511 CopyAssignment->setAccess(AS_public);
5512 CopyAssignment->setImplicit();
5513 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00005514
5515 // Add the parameter to the operator.
5516 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005517 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00005518 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005519 SC_None,
5520 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00005521 CopyAssignment->setParams(&FromParam, 1);
5522
Douglas Gregora376d102010-07-02 21:50:04 +00005523 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00005524 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5525
Douglas Gregor23c94db2010-07-02 17:43:08 +00005526 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00005527 PushOnScopeChains(CopyAssignment, S, false);
5528 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00005529
5530 AddOverriddenMethods(ClassDecl, CopyAssignment);
5531 return CopyAssignment;
5532}
5533
Douglas Gregor06a9f362010-05-01 20:49:11 +00005534void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5535 CXXMethodDecl *CopyAssignOperator) {
5536 assert((CopyAssignOperator->isImplicit() &&
5537 CopyAssignOperator->isOverloadedOperator() &&
5538 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005539 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00005540 "DefineImplicitCopyAssignment called for wrong function");
5541
5542 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5543
5544 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5545 CopyAssignOperator->setInvalidDecl();
5546 return;
5547 }
5548
5549 CopyAssignOperator->setUsed();
5550
5551 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005552 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005553
5554 // C++0x [class.copy]p30:
5555 // The implicitly-defined or explicitly-defaulted copy assignment operator
5556 // for a non-union class X performs memberwise copy assignment of its
5557 // subobjects. The direct base classes of X are assigned first, in the
5558 // order of their declaration in the base-specifier-list, and then the
5559 // immediate non-static data members of X are assigned, in the order in
5560 // which they were declared in the class definition.
5561
5562 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00005563 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005564
5565 // The parameter for the "other" object, which we are copying from.
5566 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5567 Qualifiers OtherQuals = Other->getType().getQualifiers();
5568 QualType OtherRefType = Other->getType();
5569 if (const LValueReferenceType *OtherRef
5570 = OtherRefType->getAs<LValueReferenceType>()) {
5571 OtherRefType = OtherRef->getPointeeType();
5572 OtherQuals = OtherRefType.getQualifiers();
5573 }
5574
5575 // Our location for everything implicitly-generated.
5576 SourceLocation Loc = CopyAssignOperator->getLocation();
5577
5578 // Construct a reference to the "other" object. We'll be using this
5579 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00005580 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005581 assert(OtherRef && "Reference to parameter cannot fail!");
5582
5583 // Construct the "this" pointer. We'll be using this throughout the generated
5584 // ASTs.
5585 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5586 assert(This && "Reference to this cannot fail!");
5587
5588 // Assign base classes.
5589 bool Invalid = false;
5590 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5591 E = ClassDecl->bases_end(); Base != E; ++Base) {
5592 // Form the assignment:
5593 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5594 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00005595 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005596 Invalid = true;
5597 continue;
5598 }
5599
John McCallf871d0c2010-08-07 06:22:56 +00005600 CXXCastPath BasePath;
5601 BasePath.push_back(Base);
5602
Douglas Gregor06a9f362010-05-01 20:49:11 +00005603 // Construct the "from" expression, which is an implicit cast to the
5604 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00005605 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005606 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005607 CK_UncheckedDerivedToBase,
5608 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005609
5610 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005611 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005612
5613 // Implicitly cast "this" to the appropriately-qualified base type.
5614 Expr *ToE = To.takeAs<Expr>();
5615 ImpCastExprToType(ToE,
5616 Context.getCVRQualifiedType(BaseType,
5617 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005618 CK_UncheckedDerivedToBase,
5619 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005620 To = Owned(ToE);
5621
5622 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005623 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005624 To.get(), From,
5625 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005626 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005627 Diag(CurrentLocation, diag::note_member_synthesized_at)
5628 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5629 CopyAssignOperator->setInvalidDecl();
5630 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005631 }
5632
5633 // Success! Record the copy.
5634 Statements.push_back(Copy.takeAs<Expr>());
5635 }
5636
5637 // \brief Reference to the __builtin_memcpy function.
5638 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005639 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005640 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005641
5642 // Assign non-static members.
5643 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5644 FieldEnd = ClassDecl->field_end();
5645 Field != FieldEnd; ++Field) {
5646 // Check for members of reference type; we can't copy those.
5647 if (Field->getType()->isReferenceType()) {
5648 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5649 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5650 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005651 Diag(CurrentLocation, diag::note_member_synthesized_at)
5652 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005653 Invalid = true;
5654 continue;
5655 }
5656
5657 // Check for members of const-qualified, non-class type.
5658 QualType BaseType = Context.getBaseElementType(Field->getType());
5659 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5660 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5661 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5662 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005663 Diag(CurrentLocation, diag::note_member_synthesized_at)
5664 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005665 Invalid = true;
5666 continue;
5667 }
5668
5669 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005670 if (FieldType->isIncompleteArrayType()) {
5671 assert(ClassDecl->hasFlexibleArrayMember() &&
5672 "Incomplete array type is not valid");
5673 continue;
5674 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005675
5676 // Build references to the field in the object we're copying from and to.
5677 CXXScopeSpec SS; // Intentionally empty
5678 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5679 LookupMemberName);
5680 MemberLookup.addDecl(*Field);
5681 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005682 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005683 Loc, /*IsArrow=*/false,
5684 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005685 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005686 Loc, /*IsArrow=*/true,
5687 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005688 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5689 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5690
5691 // If the field should be copied with __builtin_memcpy rather than via
5692 // explicit assignments, do so. This optimization only applies for arrays
5693 // of scalars and arrays of class type with trivial copy-assignment
5694 // operators.
5695 if (FieldType->isArrayType() &&
5696 (!BaseType->isRecordType() ||
5697 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5698 ->hasTrivialCopyAssignment())) {
5699 // Compute the size of the memory buffer to be copied.
5700 QualType SizeType = Context.getSizeType();
5701 llvm::APInt Size(Context.getTypeSize(SizeType),
5702 Context.getTypeSizeInChars(BaseType).getQuantity());
5703 for (const ConstantArrayType *Array
5704 = Context.getAsConstantArrayType(FieldType);
5705 Array;
5706 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005707 llvm::APInt ArraySize
5708 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005709 Size *= ArraySize;
5710 }
5711
5712 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005713 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5714 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005715
5716 bool NeedsCollectableMemCpy =
5717 (BaseType->isRecordType() &&
5718 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5719
5720 if (NeedsCollectableMemCpy) {
5721 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005722 // Create a reference to the __builtin_objc_memmove_collectable function.
5723 LookupResult R(*this,
5724 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005725 Loc, LookupOrdinaryName);
5726 LookupName(R, TUScope, true);
5727
5728 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5729 if (!CollectableMemCpy) {
5730 // Something went horribly wrong earlier, and we will have
5731 // complained about it.
5732 Invalid = true;
5733 continue;
5734 }
5735
5736 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5737 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005738 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005739 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5740 }
5741 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005742 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005743 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005744 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5745 LookupOrdinaryName);
5746 LookupName(R, TUScope, true);
5747
5748 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5749 if (!BuiltinMemCpy) {
5750 // Something went horribly wrong earlier, and we will have complained
5751 // about it.
5752 Invalid = true;
5753 continue;
5754 }
5755
5756 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5757 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005758 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005759 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5760 }
5761
John McCallca0408f2010-08-23 06:44:23 +00005762 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005763 CallArgs.push_back(To.takeAs<Expr>());
5764 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005765 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005766 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005767 if (NeedsCollectableMemCpy)
5768 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005769 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005770 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005771 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005772 else
5773 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005774 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005775 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005776 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005777
Douglas Gregor06a9f362010-05-01 20:49:11 +00005778 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5779 Statements.push_back(Call.takeAs<Expr>());
5780 continue;
5781 }
5782
5783 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005784 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005785 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005786 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005787 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005788 Diag(CurrentLocation, diag::note_member_synthesized_at)
5789 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5790 CopyAssignOperator->setInvalidDecl();
5791 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005792 }
5793
5794 // Success! Record the copy.
5795 Statements.push_back(Copy.takeAs<Stmt>());
5796 }
5797
5798 if (!Invalid) {
5799 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005800 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005801
John McCall60d7b3a2010-08-24 06:29:42 +00005802 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005803 if (Return.isInvalid())
5804 Invalid = true;
5805 else {
5806 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005807
5808 if (Trap.hasErrorOccurred()) {
5809 Diag(CurrentLocation, diag::note_member_synthesized_at)
5810 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5811 Invalid = true;
5812 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005813 }
5814 }
5815
5816 if (Invalid) {
5817 CopyAssignOperator->setInvalidDecl();
5818 return;
5819 }
5820
John McCall60d7b3a2010-08-24 06:29:42 +00005821 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005822 /*isStmtExpr=*/false);
5823 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5824 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005825}
5826
Douglas Gregor23c94db2010-07-02 17:43:08 +00005827CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5828 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005829 // C++ [class.copy]p4:
5830 // If the class definition does not explicitly declare a copy
5831 // constructor, one is declared implicitly.
5832
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005833 // C++ [class.copy]p5:
5834 // The implicitly-declared copy constructor for a class X will
5835 // have the form
5836 //
5837 // X::X(const X&)
5838 //
5839 // if
5840 bool HasConstCopyConstructor = true;
5841
5842 // -- each direct or virtual base class B of X has a copy
5843 // constructor whose first parameter is of type const B& or
5844 // const volatile B&, and
5845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5846 BaseEnd = ClassDecl->bases_end();
5847 HasConstCopyConstructor && Base != BaseEnd;
5848 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005849 // Virtual bases are handled below.
5850 if (Base->isVirtual())
5851 continue;
5852
Douglas Gregor22584312010-07-02 23:41:54 +00005853 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005854 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005855 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5856 DeclareImplicitCopyConstructor(BaseClassDecl);
5857
Douglas Gregor598a8542010-07-01 18:27:03 +00005858 HasConstCopyConstructor
5859 = BaseClassDecl->hasConstCopyConstructor(Context);
5860 }
5861
5862 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5863 BaseEnd = ClassDecl->vbases_end();
5864 HasConstCopyConstructor && Base != BaseEnd;
5865 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005866 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005867 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005868 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5869 DeclareImplicitCopyConstructor(BaseClassDecl);
5870
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005871 HasConstCopyConstructor
5872 = BaseClassDecl->hasConstCopyConstructor(Context);
5873 }
5874
5875 // -- for all the nonstatic data members of X that are of a
5876 // class type M (or array thereof), each such class type
5877 // has a copy constructor whose first parameter is of type
5878 // const M& or const volatile M&.
5879 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5880 FieldEnd = ClassDecl->field_end();
5881 HasConstCopyConstructor && Field != FieldEnd;
5882 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005883 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005884 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005885 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005886 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005887 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5888 DeclareImplicitCopyConstructor(FieldClassDecl);
5889
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005890 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005891 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005892 }
5893 }
5894
5895 // Otherwise, the implicitly declared copy constructor will have
5896 // the form
5897 //
5898 // X::X(X&)
5899 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5900 QualType ArgType = ClassType;
5901 if (HasConstCopyConstructor)
5902 ArgType = ArgType.withConst();
5903 ArgType = Context.getLValueReferenceType(ArgType);
5904
Douglas Gregor0d405db2010-07-01 20:59:04 +00005905 // C++ [except.spec]p14:
5906 // An implicitly declared special member function (Clause 12) shall have an
5907 // exception-specification. [...]
5908 ImplicitExceptionSpecification ExceptSpec(Context);
5909 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5911 BaseEnd = ClassDecl->bases_end();
5912 Base != BaseEnd;
5913 ++Base) {
5914 // Virtual bases are handled below.
5915 if (Base->isVirtual())
5916 continue;
5917
Douglas Gregor22584312010-07-02 23:41:54 +00005918 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005919 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005920 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5921 DeclareImplicitCopyConstructor(BaseClassDecl);
5922
Douglas Gregor0d405db2010-07-01 20:59:04 +00005923 if (CXXConstructorDecl *CopyConstructor
5924 = BaseClassDecl->getCopyConstructor(Context, Quals))
5925 ExceptSpec.CalledDecl(CopyConstructor);
5926 }
5927 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5928 BaseEnd = ClassDecl->vbases_end();
5929 Base != BaseEnd;
5930 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005931 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005932 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005933 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5934 DeclareImplicitCopyConstructor(BaseClassDecl);
5935
Douglas Gregor0d405db2010-07-01 20:59:04 +00005936 if (CXXConstructorDecl *CopyConstructor
5937 = BaseClassDecl->getCopyConstructor(Context, Quals))
5938 ExceptSpec.CalledDecl(CopyConstructor);
5939 }
5940 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5941 FieldEnd = ClassDecl->field_end();
5942 Field != FieldEnd;
5943 ++Field) {
5944 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5945 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005946 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005947 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005948 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5949 DeclareImplicitCopyConstructor(FieldClassDecl);
5950
Douglas Gregor0d405db2010-07-01 20:59:04 +00005951 if (CXXConstructorDecl *CopyConstructor
5952 = FieldClassDecl->getCopyConstructor(Context, Quals))
5953 ExceptSpec.CalledDecl(CopyConstructor);
5954 }
5955 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005956
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005957 // An implicitly-declared copy constructor is an inline public
5958 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005959 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl60618fa2011-03-12 11:50:43 +00005960 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00005961 EPI.NumExceptions = ExceptSpec.size();
5962 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005963 DeclarationName Name
5964 = Context.DeclarationNames.getCXXConstructorName(
5965 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005966 SourceLocation ClassLoc = ClassDecl->getLocation();
5967 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005968 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005969 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005970 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005971 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005972 /*TInfo=*/0,
5973 /*isExplicit=*/false,
5974 /*isInline=*/true,
5975 /*isImplicitlyDeclared=*/true);
5976 CopyConstructor->setAccess(AS_public);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005977 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5978
Douglas Gregor22584312010-07-02 23:41:54 +00005979 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005980 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5981
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005982 // Add the parameter to the constructor.
5983 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005984 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005985 /*IdentifierInfo=*/0,
5986 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005987 SC_None,
5988 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005989 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005990 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005991 PushOnScopeChains(CopyConstructor, S, false);
5992 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005993
5994 return CopyConstructor;
5995}
5996
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005997void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5998 CXXConstructorDecl *CopyConstructor,
5999 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00006000 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00006001 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00006002 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006003 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006004
Anders Carlsson63010a72010-04-23 16:24:12 +00006005 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006006 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006007
Douglas Gregor39957dc2010-05-01 15:04:51 +00006008 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006009 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006010
Sean Huntcbb67482011-01-08 20:30:50 +00006011 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006012 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00006013 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006014 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00006015 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006016 } else {
6017 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6018 CopyConstructor->getLocation(),
6019 MultiStmtArg(*this, 0, 0),
6020 /*isStmtExpr=*/false)
6021 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00006022 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00006023
6024 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006025}
6026
John McCall60d7b3a2010-08-24 06:29:42 +00006027ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006028Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00006029 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00006030 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006031 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006032 unsigned ConstructKind,
6033 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006034 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006035
Douglas Gregor2f599792010-04-02 18:24:57 +00006036 // C++0x [class.copy]p34:
6037 // When certain criteria are met, an implementation is allowed to
6038 // omit the copy/move construction of a class object, even if the
6039 // copy/move constructor and/or destructor for the object have
6040 // side effects. [...]
6041 // - when a temporary class object that has not been bound to a
6042 // reference (12.2) would be copied/moved to a class object
6043 // with the same cv-unqualified type, the copy/move operation
6044 // can be omitted by constructing the temporary object
6045 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00006046 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00006047 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00006048 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00006049 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006050 }
Mike Stump1eb44332009-09-09 15:08:12 +00006051
6052 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006053 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006054 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00006055}
6056
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006057/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6058/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006059ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00006060Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6061 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00006062 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006063 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006064 unsigned ConstructKind,
6065 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00006066 unsigned NumExprs = ExprArgs.size();
6067 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006068
Nick Lewycky909a70d2011-03-25 01:44:32 +00006069 for (specific_attr_iterator<NonNullAttr>
6070 i = Constructor->specific_attr_begin<NonNullAttr>(),
6071 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6072 const NonNullAttr *NonNull = *i;
6073 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6074 }
6075
Douglas Gregor7edfb692009-11-23 12:27:39 +00006076 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00006077 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00006078 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00006079 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006080 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6081 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006082}
6083
Mike Stump1eb44332009-09-09 15:08:12 +00006084bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00006085 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00006086 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00006087 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00006088 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00006089 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00006090 move(Exprs), false, CXXConstructExpr::CK_Complete,
6091 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00006092 if (TempResult.isInvalid())
6093 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006094
Anders Carlssonda3f4e22009-08-25 05:12:04 +00006095 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00006096 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006097 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00006098 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00006099 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00006100
Anders Carlssonfe2de492009-08-25 05:18:00 +00006101 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00006102}
6103
John McCall68c6c9a2010-02-02 09:10:11 +00006104void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006105 if (VD->isInvalidDecl()) return;
6106
John McCall68c6c9a2010-02-02 09:10:11 +00006107 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006108 if (ClassDecl->isInvalidDecl()) return;
6109 if (ClassDecl->hasTrivialDestructor()) return;
6110 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00006111
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006112 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6113 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6114 CheckDestructorAccess(VD->getLocation(), Destructor,
6115 PDiag(diag::err_access_dtor_var)
6116 << VD->getDeclName()
6117 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00006118
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00006119 if (!VD->hasGlobalStorage()) return;
6120
6121 // Emit warning for non-trivial dtor in global scope (a real global,
6122 // class-static, function-static).
6123 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6124
6125 // TODO: this should be re-enabled for static locals by !CXAAtExit
6126 if (!VD->isStaticLocal())
6127 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006128}
6129
Mike Stump1eb44332009-09-09 15:08:12 +00006130/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006131/// ActOnDeclarator, when a C++ direct initializer is present.
6132/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00006133void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006134 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006135 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00006136 SourceLocation RParenLoc,
6137 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00006138 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006139
6140 // If there is no declaration, there was an error parsing it. Just ignore
6141 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006142 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006143 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006144
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006145 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6146 if (!VDecl) {
6147 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6148 RealDecl->setInvalidDecl();
6149 return;
6150 }
6151
Richard Smith34b41d92011-02-20 03:19:35 +00006152 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6153 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00006154 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6155 if (Exprs.size() > 1) {
6156 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6157 diag::err_auto_var_init_multiple_expressions)
6158 << VDecl->getDeclName() << VDecl->getType()
6159 << VDecl->getSourceRange();
6160 RealDecl->setInvalidDecl();
6161 return;
6162 }
6163
6164 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00006165 TypeSourceInfo *DeducedType = 0;
6166 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00006167 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6168 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6169 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00006170 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00006171 RealDecl->setInvalidDecl();
6172 return;
6173 }
Richard Smitha085da82011-03-17 16:11:59 +00006174 VDecl->setTypeSourceInfo(DeducedType);
6175 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00006176
6177 // If this is a redeclaration, check that the type we just deduced matches
6178 // the previously declared type.
6179 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6180 MergeVarDeclTypes(VDecl, Old);
6181 }
6182
Douglas Gregor83ddad32009-08-26 21:14:46 +00006183 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006184 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006185 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6186 //
6187 // Clients that want to distinguish between the two forms, can check for
6188 // direct initializer using VarDecl::hasCXXDirectInitializer().
6189 // A major benefit is that clients that don't particularly care about which
6190 // exactly form was it (like the CodeGen) can handle both cases without
6191 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006192
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006193 // C++ 8.5p11:
6194 // The form of initialization (using parentheses or '=') is generally
6195 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006196 // class type.
6197
Douglas Gregor4dffad62010-02-11 22:55:30 +00006198 if (!VDecl->getType()->isDependentType() &&
6199 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00006200 diag::err_typecheck_decl_incomplete_type)) {
6201 VDecl->setInvalidDecl();
6202 return;
6203 }
6204
Douglas Gregor90f93822009-12-22 22:17:25 +00006205 // The variable can not have an abstract class type.
6206 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6207 diag::err_abstract_type_in_decl,
6208 AbstractVariableType))
6209 VDecl->setInvalidDecl();
6210
Sebastian Redl31310a22010-02-01 20:16:42 +00006211 const VarDecl *Def;
6212 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00006213 Diag(VDecl->getLocation(), diag::err_redefinition)
6214 << VDecl->getDeclName();
6215 Diag(Def->getLocation(), diag::note_previous_definition);
6216 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00006217 return;
6218 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00006219
Douglas Gregor3a91abf2010-08-24 05:27:49 +00006220 // C++ [class.static.data]p4
6221 // If a static data member is of const integral or const
6222 // enumeration type, its declaration in the class definition can
6223 // specify a constant-initializer which shall be an integral
6224 // constant expression (5.19). In that case, the member can appear
6225 // in integral constant expressions. The member shall still be
6226 // defined in a namespace scope if it is used in the program and the
6227 // namespace scope definition shall not contain an initializer.
6228 //
6229 // We already performed a redefinition check above, but for static
6230 // data members we also need to check whether there was an in-class
6231 // declaration with an initializer.
6232 const VarDecl* PrevInit = 0;
6233 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6234 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6235 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6236 return;
6237 }
6238
Douglas Gregora31040f2010-12-16 01:31:22 +00006239 bool IsDependent = false;
6240 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6241 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6242 VDecl->setInvalidDecl();
6243 return;
6244 }
6245
6246 if (Exprs.get()[I]->isTypeDependent())
6247 IsDependent = true;
6248 }
6249
Douglas Gregor4dffad62010-02-11 22:55:30 +00006250 // If either the declaration has a dependent type or if any of the
6251 // expressions is type-dependent, we represent the initialization
6252 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00006253 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00006254 // Let clients know that initialization was done with a direct initializer.
6255 VDecl->setCXXDirectInitializer(true);
6256
6257 // Store the initialization expressions as a ParenListExpr.
6258 unsigned NumExprs = Exprs.size();
6259 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6260 (Expr **)Exprs.release(),
6261 NumExprs, RParenLoc));
6262 return;
6263 }
Douglas Gregor90f93822009-12-22 22:17:25 +00006264
6265 // Capture the variable that is being initialized and the style of
6266 // initialization.
6267 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6268
6269 // FIXME: Poor source location information.
6270 InitializationKind Kind
6271 = InitializationKind::CreateDirect(VDecl->getLocation(),
6272 LParenLoc, RParenLoc);
6273
6274 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006275 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00006276 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00006277 if (Result.isInvalid()) {
6278 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006279 return;
6280 }
John McCallb4eb64d2010-10-08 02:01:28 +00006281
6282 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00006283
Douglas Gregor53c374f2010-12-07 00:41:46 +00006284 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00006285 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006286 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00006287
John McCall2998d6b2011-01-19 11:48:09 +00006288 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006289}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00006290
Douglas Gregor39da0b82009-09-09 23:08:42 +00006291/// \brief Given a constructor and the set of arguments provided for the
6292/// constructor, convert the arguments and add any required default arguments
6293/// to form a proper call to this constructor.
6294///
6295/// \returns true if an error occurred, false otherwise.
6296bool
6297Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6298 MultiExprArg ArgsPtr,
6299 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00006300 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00006301 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6302 unsigned NumArgs = ArgsPtr.size();
6303 Expr **Args = (Expr **)ArgsPtr.get();
6304
6305 const FunctionProtoType *Proto
6306 = Constructor->getType()->getAs<FunctionProtoType>();
6307 assert(Proto && "Constructor without a prototype?");
6308 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00006309
6310 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006311 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00006312 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006313 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00006314 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00006315
6316 VariadicCallType CallType =
6317 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6318 llvm::SmallVector<Expr *, 8> AllArgs;
6319 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6320 Proto, 0, Args, NumArgs, AllArgs,
6321 CallType);
6322 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6323 ConvertedArgs.push_back(AllArgs[i]);
6324 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00006325}
6326
Anders Carlsson20d45d22009-12-12 00:32:00 +00006327static inline bool
6328CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6329 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006330 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00006331 if (isa<NamespaceDecl>(DC)) {
6332 return SemaRef.Diag(FnDecl->getLocation(),
6333 diag::err_operator_new_delete_declared_in_namespace)
6334 << FnDecl->getDeclName();
6335 }
6336
6337 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00006338 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006339 return SemaRef.Diag(FnDecl->getLocation(),
6340 diag::err_operator_new_delete_declared_static)
6341 << FnDecl->getDeclName();
6342 }
6343
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00006344 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00006345}
6346
Anders Carlsson156c78e2009-12-13 17:53:43 +00006347static inline bool
6348CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6349 CanQualType ExpectedResultType,
6350 CanQualType ExpectedFirstParamType,
6351 unsigned DependentParamTypeDiag,
6352 unsigned InvalidParamTypeDiag) {
6353 QualType ResultType =
6354 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6355
6356 // Check that the result type is not dependent.
6357 if (ResultType->isDependentType())
6358 return SemaRef.Diag(FnDecl->getLocation(),
6359 diag::err_operator_new_delete_dependent_result_type)
6360 << FnDecl->getDeclName() << ExpectedResultType;
6361
6362 // Check that the result type is what we expect.
6363 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6364 return SemaRef.Diag(FnDecl->getLocation(),
6365 diag::err_operator_new_delete_invalid_result_type)
6366 << FnDecl->getDeclName() << ExpectedResultType;
6367
6368 // A function template must have at least 2 parameters.
6369 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6370 return SemaRef.Diag(FnDecl->getLocation(),
6371 diag::err_operator_new_delete_template_too_few_parameters)
6372 << FnDecl->getDeclName();
6373
6374 // The function decl must have at least 1 parameter.
6375 if (FnDecl->getNumParams() == 0)
6376 return SemaRef.Diag(FnDecl->getLocation(),
6377 diag::err_operator_new_delete_too_few_parameters)
6378 << FnDecl->getDeclName();
6379
6380 // Check the the first parameter type is not dependent.
6381 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6382 if (FirstParamType->isDependentType())
6383 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6384 << FnDecl->getDeclName() << ExpectedFirstParamType;
6385
6386 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00006387 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00006388 ExpectedFirstParamType)
6389 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6390 << FnDecl->getDeclName() << ExpectedFirstParamType;
6391
6392 return false;
6393}
6394
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006395static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00006396CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00006397 // C++ [basic.stc.dynamic.allocation]p1:
6398 // A program is ill-formed if an allocation function is declared in a
6399 // namespace scope other than global scope or declared static in global
6400 // scope.
6401 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6402 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00006403
6404 CanQualType SizeTy =
6405 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6406
6407 // C++ [basic.stc.dynamic.allocation]p1:
6408 // The return type shall be void*. The first parameter shall have type
6409 // std::size_t.
6410 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6411 SizeTy,
6412 diag::err_operator_new_dependent_param_type,
6413 diag::err_operator_new_param_type))
6414 return true;
6415
6416 // C++ [basic.stc.dynamic.allocation]p1:
6417 // The first parameter shall not have an associated default argument.
6418 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00006419 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00006420 diag::err_operator_new_default_arg)
6421 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6422
6423 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00006424}
6425
6426static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006427CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6428 // C++ [basic.stc.dynamic.deallocation]p1:
6429 // A program is ill-formed if deallocation functions are declared in a
6430 // namespace scope other than global scope or declared static in global
6431 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00006432 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6433 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006434
6435 // C++ [basic.stc.dynamic.deallocation]p2:
6436 // Each deallocation function shall return void and its first parameter
6437 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00006438 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6439 SemaRef.Context.VoidPtrTy,
6440 diag::err_operator_delete_dependent_param_type,
6441 diag::err_operator_delete_param_type))
6442 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006443
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006444 return false;
6445}
6446
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006447/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6448/// of this overloaded operator is well-formed. If so, returns false;
6449/// otherwise, emits appropriate diagnostics and returns true.
6450bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006451 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006452 "Expected an overloaded operator declaration");
6453
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006454 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6455
Mike Stump1eb44332009-09-09 15:08:12 +00006456 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006457 // The allocation and deallocation functions, operator new,
6458 // operator new[], operator delete and operator delete[], are
6459 // described completely in 3.7.3. The attributes and restrictions
6460 // found in the rest of this subclause do not apply to them unless
6461 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00006462 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00006463 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00006464
Anders Carlssona3ccda52009-12-12 00:26:23 +00006465 if (Op == OO_New || Op == OO_Array_New)
6466 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006467
6468 // C++ [over.oper]p6:
6469 // An operator function shall either be a non-static member
6470 // function or be a non-member function and have at least one
6471 // parameter whose type is a class, a reference to a class, an
6472 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006473 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6474 if (MethodDecl->isStatic())
6475 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006476 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006477 } else {
6478 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006479 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6480 ParamEnd = FnDecl->param_end();
6481 Param != ParamEnd; ++Param) {
6482 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00006483 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6484 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006485 ClassOrEnumParam = true;
6486 break;
6487 }
6488 }
6489
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006490 if (!ClassOrEnumParam)
6491 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006492 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006493 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006494 }
6495
6496 // C++ [over.oper]p8:
6497 // An operator function cannot have default arguments (8.3.6),
6498 // except where explicitly stated below.
6499 //
Mike Stump1eb44332009-09-09 15:08:12 +00006500 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006501 // (C++ [over.call]p1).
6502 if (Op != OO_Call) {
6503 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6504 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00006505 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00006506 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00006507 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00006508 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006509 }
6510 }
6511
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006512 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6513 { false, false, false }
6514#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6515 , { Unary, Binary, MemberOnly }
6516#include "clang/Basic/OperatorKinds.def"
6517 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006518
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006519 bool CanBeUnaryOperator = OperatorUses[Op][0];
6520 bool CanBeBinaryOperator = OperatorUses[Op][1];
6521 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006522
6523 // C++ [over.oper]p8:
6524 // [...] Operator functions cannot have more or fewer parameters
6525 // than the number required for the corresponding operator, as
6526 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00006527 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006528 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006529 if (Op != OO_Call &&
6530 ((NumParams == 1 && !CanBeUnaryOperator) ||
6531 (NumParams == 2 && !CanBeBinaryOperator) ||
6532 (NumParams < 1) || (NumParams > 2))) {
6533 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00006534 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006535 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006536 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006537 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00006538 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006539 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006540 assert(CanBeBinaryOperator &&
6541 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00006542 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00006543 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006544
Chris Lattner416e46f2008-11-21 07:57:12 +00006545 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006546 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006547 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006548
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006549 // Overloaded operators other than operator() cannot be variadic.
6550 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00006551 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006552 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006553 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006554 }
6555
6556 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006557 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6558 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006559 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006560 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006561 }
6562
6563 // C++ [over.inc]p1:
6564 // The user-defined function called operator++ implements the
6565 // prefix and postfix ++ operator. If this function is a member
6566 // function with no parameters, or a non-member function with one
6567 // parameter of class or enumeration type, it defines the prefix
6568 // increment operator ++ for objects of that type. If the function
6569 // is a member function with one parameter (which shall be of type
6570 // int) or a non-member function with two parameters (the second
6571 // of which shall be of type int), it defines the postfix
6572 // increment operator ++ for objects of that type.
6573 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6574 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6575 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00006576 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006577 ParamIsInt = BT->getKind() == BuiltinType::Int;
6578
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00006579 if (!ParamIsInt)
6580 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00006581 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00006582 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006583 }
6584
Douglas Gregor43c7bad2008-11-17 16:14:12 +00006585 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00006586}
Chris Lattner5a003a42008-12-17 07:09:26 +00006587
Sean Hunta6c058d2010-01-13 09:01:02 +00006588/// CheckLiteralOperatorDeclaration - Check whether the declaration
6589/// of this literal operator function is well-formed. If so, returns
6590/// false; otherwise, emits appropriate diagnostics and returns true.
6591bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6592 DeclContext *DC = FnDecl->getDeclContext();
6593 Decl::Kind Kind = DC->getDeclKind();
6594 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6595 Kind != Decl::LinkageSpec) {
6596 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6597 << FnDecl->getDeclName();
6598 return true;
6599 }
6600
6601 bool Valid = false;
6602
Sean Hunt216c2782010-04-07 23:11:06 +00006603 // template <char...> type operator "" name() is the only valid template
6604 // signature, and the only valid signature with no parameters.
6605 if (FnDecl->param_size() == 0) {
6606 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6607 // Must have only one template parameter
6608 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6609 if (Params->size() == 1) {
6610 NonTypeTemplateParmDecl *PmDecl =
6611 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00006612
Sean Hunt216c2782010-04-07 23:11:06 +00006613 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00006614 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6615 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6616 Valid = true;
6617 }
6618 }
6619 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00006620 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00006621 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6622
Sean Hunta6c058d2010-01-13 09:01:02 +00006623 QualType T = (*Param)->getType();
6624
Sean Hunt30019c02010-04-07 22:57:35 +00006625 // unsigned long long int, long double, and any character type are allowed
6626 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006627 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6628 Context.hasSameType(T, Context.LongDoubleTy) ||
6629 Context.hasSameType(T, Context.CharTy) ||
6630 Context.hasSameType(T, Context.WCharTy) ||
6631 Context.hasSameType(T, Context.Char16Ty) ||
6632 Context.hasSameType(T, Context.Char32Ty)) {
6633 if (++Param == FnDecl->param_end())
6634 Valid = true;
6635 goto FinishedParams;
6636 }
6637
Sean Hunt30019c02010-04-07 22:57:35 +00006638 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006639 const PointerType *PT = T->getAs<PointerType>();
6640 if (!PT)
6641 goto FinishedParams;
6642 T = PT->getPointeeType();
6643 if (!T.isConstQualified())
6644 goto FinishedParams;
6645 T = T.getUnqualifiedType();
6646
6647 // Move on to the second parameter;
6648 ++Param;
6649
6650 // If there is no second parameter, the first must be a const char *
6651 if (Param == FnDecl->param_end()) {
6652 if (Context.hasSameType(T, Context.CharTy))
6653 Valid = true;
6654 goto FinishedParams;
6655 }
6656
6657 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6658 // are allowed as the first parameter to a two-parameter function
6659 if (!(Context.hasSameType(T, Context.CharTy) ||
6660 Context.hasSameType(T, Context.WCharTy) ||
6661 Context.hasSameType(T, Context.Char16Ty) ||
6662 Context.hasSameType(T, Context.Char32Ty)))
6663 goto FinishedParams;
6664
6665 // The second and final parameter must be an std::size_t
6666 T = (*Param)->getType().getUnqualifiedType();
6667 if (Context.hasSameType(T, Context.getSizeType()) &&
6668 ++Param == FnDecl->param_end())
6669 Valid = true;
6670 }
6671
6672 // FIXME: This diagnostic is absolutely terrible.
6673FinishedParams:
6674 if (!Valid) {
6675 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6676 << FnDecl->getDeclName();
6677 return true;
6678 }
6679
6680 return false;
6681}
6682
Douglas Gregor074149e2009-01-05 19:45:36 +00006683/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6684/// linkage specification, including the language and (if present)
6685/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6686/// the location of the language string literal, which is provided
6687/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6688/// the '{' brace. Otherwise, this linkage specification does not
6689/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00006690Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6691 SourceLocation LangLoc,
6692 llvm::StringRef Lang,
6693 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006694 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006695 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006696 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006697 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006698 Language = LinkageSpecDecl::lang_cxx;
6699 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006700 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006701 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006702 }
Mike Stump1eb44332009-09-09 15:08:12 +00006703
Chris Lattnercc98eac2008-12-17 07:13:27 +00006704 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006705
Douglas Gregor074149e2009-01-05 19:45:36 +00006706 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006707 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006708 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006709 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006710 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006711}
6712
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006713/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006714/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6715/// valid, it's the position of the closing '}' brace in a linkage
6716/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006717Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006718 Decl *LinkageSpec,
6719 SourceLocation RBraceLoc) {
6720 if (LinkageSpec) {
6721 if (RBraceLoc.isValid()) {
6722 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6723 LSDecl->setRBraceLoc(RBraceLoc);
6724 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006725 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00006726 }
Douglas Gregor074149e2009-01-05 19:45:36 +00006727 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006728}
6729
Douglas Gregord308e622009-05-18 20:51:54 +00006730/// \brief Perform semantic analysis for the variable declaration that
6731/// occurs within a C++ catch clause, returning the newly-created
6732/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006733VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006734 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006735 SourceLocation StartLoc,
6736 SourceLocation Loc,
6737 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00006738 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006739 QualType ExDeclType = TInfo->getType();
6740
Sebastian Redl4b07b292008-12-22 19:15:10 +00006741 // Arrays and functions decay.
6742 if (ExDeclType->isArrayType())
6743 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6744 else if (ExDeclType->isFunctionType())
6745 ExDeclType = Context.getPointerType(ExDeclType);
6746
6747 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6748 // The exception-declaration shall not denote a pointer or reference to an
6749 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006750 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006751 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006752 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006753 Invalid = true;
6754 }
Douglas Gregord308e622009-05-18 20:51:54 +00006755
Douglas Gregora2762912010-03-08 01:47:36 +00006756 // GCC allows catching pointers and references to incomplete types
6757 // as an extension; so do we, but we warn by default.
6758
Sebastian Redl4b07b292008-12-22 19:15:10 +00006759 QualType BaseType = ExDeclType;
6760 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006761 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006762 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006763 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006764 BaseType = Ptr->getPointeeType();
6765 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006766 DK = diag::ext_catch_incomplete_ptr;
6767 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006768 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006769 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006770 BaseType = Ref->getPointeeType();
6771 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006772 DK = diag::ext_catch_incomplete_ref;
6773 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006774 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006775 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006776 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6777 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006778 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006779
Mike Stump1eb44332009-09-09 15:08:12 +00006780 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006781 RequireNonAbstractType(Loc, ExDeclType,
6782 diag::err_abstract_type_in_decl,
6783 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006784 Invalid = true;
6785
John McCall5a180392010-07-24 00:37:23 +00006786 // Only the non-fragile NeXT runtime currently supports C++ catches
6787 // of ObjC types, and no runtime supports catching ObjC types by value.
6788 if (!Invalid && getLangOptions().ObjC1) {
6789 QualType T = ExDeclType;
6790 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6791 T = RT->getPointeeType();
6792
6793 if (T->isObjCObjectType()) {
6794 Diag(Loc, diag::err_objc_object_catch);
6795 Invalid = true;
6796 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00006797 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00006798 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6799 Invalid = true;
6800 }
6801 }
6802 }
6803
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006804 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6805 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006806 ExDecl->setExceptionVariable(true);
6807
Douglas Gregor6d182892010-03-05 23:38:39 +00006808 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00006809 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00006810 // C++ [except.handle]p16:
6811 // The object declared in an exception-declaration or, if the
6812 // exception-declaration does not specify a name, a temporary (12.2) is
6813 // copy-initialized (8.5) from the exception object. [...]
6814 // The object is destroyed when the handler exits, after the destruction
6815 // of any automatic objects initialized within the handler.
6816 //
6817 // We just pretend to initialize the object with itself, then make sure
6818 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00006819 QualType initType = ExDeclType;
6820
6821 InitializedEntity entity =
6822 InitializedEntity::InitializeVariable(ExDecl);
6823 InitializationKind initKind =
6824 InitializationKind::CreateCopy(Loc, SourceLocation());
6825
6826 Expr *opaqueValue =
6827 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6828 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6829 ExprResult result = sequence.Perform(*this, entity, initKind,
6830 MultiExprArg(&opaqueValue, 1));
6831 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00006832 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00006833 else {
6834 // If the constructor used was non-trivial, set this as the
6835 // "initializer".
6836 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6837 if (!construct->getConstructor()->isTrivial()) {
6838 Expr *init = MaybeCreateExprWithCleanups(construct);
6839 ExDecl->setInit(init);
6840 }
6841
6842 // And make sure it's destructable.
6843 FinalizeVarWithDestructor(ExDecl, recordType);
6844 }
Douglas Gregor6d182892010-03-05 23:38:39 +00006845 }
6846 }
6847
Douglas Gregord308e622009-05-18 20:51:54 +00006848 if (Invalid)
6849 ExDecl->setInvalidDecl();
6850
6851 return ExDecl;
6852}
6853
6854/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6855/// handler.
John McCalld226f652010-08-21 09:40:31 +00006856Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006857 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006858 bool Invalid = D.isInvalidType();
6859
6860 // Check for unexpanded parameter packs.
6861 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6862 UPPC_ExceptionType)) {
6863 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6864 D.getIdentifierLoc());
6865 Invalid = true;
6866 }
6867
Sebastian Redl4b07b292008-12-22 19:15:10 +00006868 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006869 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006870 LookupOrdinaryName,
6871 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006872 // The scope should be freshly made just for us. There is just no way
6873 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006874 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006875 if (PrevDecl->isTemplateParameter()) {
6876 // Maybe we will complain about the shadowed template parameter.
6877 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006878 }
6879 }
6880
Chris Lattnereaaebc72009-04-25 08:06:05 +00006881 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006882 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6883 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006884 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006885 }
6886
Douglas Gregor83cb9422010-09-09 17:09:21 +00006887 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006888 D.getSourceRange().getBegin(),
6889 D.getIdentifierLoc(),
6890 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00006891 if (Invalid)
6892 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006893
Sebastian Redl4b07b292008-12-22 19:15:10 +00006894 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006895 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006896 PushOnScopeChains(ExDecl, S);
6897 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006898 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006899
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006900 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006901 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006902}
Anders Carlssonfb311762009-03-14 00:25:26 +00006903
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006904Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006905 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006906 Expr *AssertMessageExpr_,
6907 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00006908 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006909
Anders Carlssonc3082412009-03-14 00:33:21 +00006910 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6911 llvm::APSInt Value(32);
6912 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006913 Diag(StaticAssertLoc,
6914 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00006915 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006916 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006917 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006918
Anders Carlssonc3082412009-03-14 00:33:21 +00006919 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006920 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006921 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006922 }
6923 }
Mike Stump1eb44332009-09-09 15:08:12 +00006924
Douglas Gregor399ad972010-12-15 23:55:21 +00006925 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6926 return 0;
6927
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00006928 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
6929 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00006930
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006931 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006932 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006933}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006934
Douglas Gregor1d869352010-04-07 16:53:43 +00006935/// \brief Perform semantic analysis of the given friend type declaration.
6936///
6937/// \returns A friend declaration that.
6938FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6939 TypeSourceInfo *TSInfo) {
6940 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6941
6942 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006943 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006944
Douglas Gregor06245bf2010-04-07 17:57:12 +00006945 if (!getLangOptions().CPlusPlus0x) {
6946 // C++03 [class.friend]p2:
6947 // An elaborated-type-specifier shall be used in a friend declaration
6948 // for a class.*
6949 //
6950 // * The class-key of the elaborated-type-specifier is required.
6951 if (!ActiveTemplateInstantiations.empty()) {
6952 // Do not complain about the form of friend template types during
6953 // template instantiation; we will already have complained when the
6954 // template was declared.
6955 } else if (!T->isElaboratedTypeSpecifier()) {
6956 // If we evaluated the type to a record type, suggest putting
6957 // a tag in front.
6958 if (const RecordType *RT = T->getAs<RecordType>()) {
6959 RecordDecl *RD = RT->getDecl();
6960
6961 std::string InsertionText = std::string(" ") + RD->getKindName();
6962
6963 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6964 << (unsigned) RD->getTagKind()
6965 << T
6966 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6967 InsertionText);
6968 } else {
6969 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6970 << T
6971 << SourceRange(FriendLoc, TypeRange.getEnd());
6972 }
6973 } else if (T->getAs<EnumType>()) {
6974 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006975 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006976 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006977 }
6978 }
6979
Douglas Gregor06245bf2010-04-07 17:57:12 +00006980 // C++0x [class.friend]p3:
6981 // If the type specifier in a friend declaration designates a (possibly
6982 // cv-qualified) class type, that class is declared as a friend; otherwise,
6983 // the friend declaration is ignored.
6984
6985 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6986 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006987
6988 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6989}
6990
John McCall9a34edb2010-10-19 01:40:49 +00006991/// Handle a friend tag declaration where the scope specifier was
6992/// templated.
6993Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6994 unsigned TagSpec, SourceLocation TagLoc,
6995 CXXScopeSpec &SS,
6996 IdentifierInfo *Name, SourceLocation NameLoc,
6997 AttributeList *Attr,
6998 MultiTemplateParamsArg TempParamLists) {
6999 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7000
7001 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00007002 bool Invalid = false;
7003
7004 if (TemplateParameterList *TemplateParams
7005 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7006 TempParamLists.get(),
7007 TempParamLists.size(),
7008 /*friend*/ true,
7009 isExplicitSpecialization,
7010 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00007011 if (TemplateParams->size() > 0) {
7012 // This is a declaration of a class template.
7013 if (Invalid)
7014 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007015
John McCall9a34edb2010-10-19 01:40:49 +00007016 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7017 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007018 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007019 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00007020 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00007021 } else {
7022 // The "template<>" header is extraneous.
7023 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7024 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7025 isExplicitSpecialization = true;
7026 }
7027 }
7028
7029 if (Invalid) return 0;
7030
7031 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7032
7033 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007034 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00007035 if (TempParamLists.get()[I]->size()) {
7036 isAllExplicitSpecializations = false;
7037 break;
7038 }
7039 }
7040
7041 // FIXME: don't ignore attributes.
7042
7043 // If it's explicit specializations all the way down, just forget
7044 // about the template header and build an appropriate non-templated
7045 // friend. TODO: for source fidelity, remember the headers.
7046 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00007047 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00007048 ElaboratedTypeKeyword Keyword
7049 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007050 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00007051 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007052 if (T.isNull())
7053 return 0;
7054
7055 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7056 if (isa<DependentNameType>(T)) {
7057 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7058 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007059 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007060 TL.setNameLoc(NameLoc);
7061 } else {
7062 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7063 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00007064 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00007065 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7066 }
7067
7068 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7069 TSI, FriendLoc);
7070 Friend->setAccess(AS_public);
7071 CurContext->addDecl(Friend);
7072 return Friend;
7073 }
7074
7075 // Handle the case of a templated-scope friend class. e.g.
7076 // template <class T> class A<T>::B;
7077 // FIXME: we don't support these right now.
7078 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7079 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7080 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7081 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7082 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00007083 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00007084 TL.setNameLoc(NameLoc);
7085
7086 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7087 TSI, FriendLoc);
7088 Friend->setAccess(AS_public);
7089 Friend->setUnsupportedFriend(true);
7090 CurContext->addDecl(Friend);
7091 return Friend;
7092}
7093
7094
John McCalldd4a3b02009-09-16 22:47:08 +00007095/// Handle a friend type declaration. This works in tandem with
7096/// ActOnTag.
7097///
7098/// Notes on friend class templates:
7099///
7100/// We generally treat friend class declarations as if they were
7101/// declaring a class. So, for example, the elaborated type specifier
7102/// in a friend declaration is required to obey the restrictions of a
7103/// class-head (i.e. no typedefs in the scope chain), template
7104/// parameters are required to match up with simple template-ids, &c.
7105/// However, unlike when declaring a template specialization, it's
7106/// okay to refer to a template specialization without an empty
7107/// template parameter declaration, e.g.
7108/// friend class A<T>::B<unsigned>;
7109/// We permit this as a special case; if there are any template
7110/// parameters present at all, require proper matching, i.e.
7111/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00007112Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00007113 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00007114 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00007115
7116 assert(DS.isFriendSpecified());
7117 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7118
John McCalldd4a3b02009-09-16 22:47:08 +00007119 // Try to convert the decl specifier to a type. This works for
7120 // friend templates because ActOnTag never produces a ClassTemplateDecl
7121 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00007122 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00007123 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7124 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00007125 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00007126 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007127
Douglas Gregor6ccab972010-12-16 01:14:37 +00007128 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7129 return 0;
7130
John McCalldd4a3b02009-09-16 22:47:08 +00007131 // This is definitely an error in C++98. It's probably meant to
7132 // be forbidden in C++0x, too, but the specification is just
7133 // poorly written.
7134 //
7135 // The problem is with declarations like the following:
7136 // template <T> friend A<T>::foo;
7137 // where deciding whether a class C is a friend or not now hinges
7138 // on whether there exists an instantiation of A that causes
7139 // 'foo' to equal C. There are restrictions on class-heads
7140 // (which we declare (by fiat) elaborated friend declarations to
7141 // be) that makes this tractable.
7142 //
7143 // FIXME: handle "template <> friend class A<T>;", which
7144 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00007145 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00007146 Diag(Loc, diag::err_tagless_friend_type_template)
7147 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00007148 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00007149 }
Douglas Gregor1d869352010-04-07 16:53:43 +00007150
John McCall02cace72009-08-28 07:59:38 +00007151 // C++98 [class.friend]p1: A friend of a class is a function
7152 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00007153 // This is fixed in DR77, which just barely didn't make the C++03
7154 // deadline. It's also a very silly restriction that seriously
7155 // affects inner classes and which nobody else seems to implement;
7156 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00007157 //
7158 // But note that we could warn about it: it's always useless to
7159 // friend one of your own members (it's not, however, worthless to
7160 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00007161
John McCalldd4a3b02009-09-16 22:47:08 +00007162 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00007163 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00007164 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00007165 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00007166 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00007167 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00007168 DS.getFriendSpecLoc());
7169 else
Douglas Gregor1d869352010-04-07 16:53:43 +00007170 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7171
7172 if (!D)
John McCalld226f652010-08-21 09:40:31 +00007173 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00007174
John McCalldd4a3b02009-09-16 22:47:08 +00007175 D->setAccess(AS_public);
7176 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00007177
John McCalld226f652010-08-21 09:40:31 +00007178 return D;
John McCall02cace72009-08-28 07:59:38 +00007179}
7180
John McCall337ec3d2010-10-12 23:13:28 +00007181Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7182 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00007183 const DeclSpec &DS = D.getDeclSpec();
7184
7185 assert(DS.isFriendSpecified());
7186 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7187
7188 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00007189 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7190 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00007191
7192 // C++ [class.friend]p1
7193 // A friend of a class is a function or class....
7194 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00007195 // It *doesn't* see through dependent types, which is correct
7196 // according to [temp.arg.type]p3:
7197 // If a declaration acquires a function type through a
7198 // type dependent on a template-parameter and this causes
7199 // a declaration that does not use the syntactic form of a
7200 // function declarator to have a function type, the program
7201 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00007202 if (!T->isFunctionType()) {
7203 Diag(Loc, diag::err_unexpected_friend);
7204
7205 // It might be worthwhile to try to recover by creating an
7206 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00007207 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007208 }
7209
7210 // C++ [namespace.memdef]p3
7211 // - If a friend declaration in a non-local class first declares a
7212 // class or function, the friend class or function is a member
7213 // of the innermost enclosing namespace.
7214 // - The name of the friend is not found by simple name lookup
7215 // until a matching declaration is provided in that namespace
7216 // scope (either before or after the class declaration granting
7217 // friendship).
7218 // - If a friend function is called, its name may be found by the
7219 // name lookup that considers functions from namespaces and
7220 // classes associated with the types of the function arguments.
7221 // - When looking for a prior declaration of a class or a function
7222 // declared as a friend, scopes outside the innermost enclosing
7223 // namespace scope are not considered.
7224
John McCall337ec3d2010-10-12 23:13:28 +00007225 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00007226 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7227 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00007228 assert(Name);
7229
Douglas Gregor6ccab972010-12-16 01:14:37 +00007230 // Check for unexpanded parameter packs.
7231 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7232 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7233 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7234 return 0;
7235
John McCall67d1a672009-08-06 02:15:43 +00007236 // The context we found the declaration in, or in which we should
7237 // create the declaration.
7238 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00007239 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00007240 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00007241 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00007242
John McCall337ec3d2010-10-12 23:13:28 +00007243 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00007244
John McCall337ec3d2010-10-12 23:13:28 +00007245 // There are four cases here.
7246 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00007247 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00007248 // there as appropriate.
7249 // Recover from invalid scope qualifiers as if they just weren't there.
7250 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00007251 // C++0x [namespace.memdef]p3:
7252 // If the name in a friend declaration is neither qualified nor
7253 // a template-id and the declaration is a function or an
7254 // elaborated-type-specifier, the lookup to determine whether
7255 // the entity has been previously declared shall not consider
7256 // any scopes outside the innermost enclosing namespace.
7257 // C++0x [class.friend]p11:
7258 // If a friend declaration appears in a local class and the name
7259 // specified is an unqualified name, a prior declaration is
7260 // looked up without considering scopes that are outside the
7261 // innermost enclosing non-class scope. For a friend function
7262 // declaration, if there is no prior declaration, the program is
7263 // ill-formed.
7264 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00007265 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00007266
John McCall29ae6e52010-10-13 05:45:15 +00007267 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00007268 DC = CurContext;
7269 while (true) {
7270 // Skip class contexts. If someone can cite chapter and verse
7271 // for this behavior, that would be nice --- it's what GCC and
7272 // EDG do, and it seems like a reasonable intent, but the spec
7273 // really only says that checks for unqualified existing
7274 // declarations should stop at the nearest enclosing namespace,
7275 // not that they should only consider the nearest enclosing
7276 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00007277 while (DC->isRecord())
7278 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00007279
John McCall68263142009-11-18 22:49:29 +00007280 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00007281
7282 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00007283 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00007284 break;
John McCall29ae6e52010-10-13 05:45:15 +00007285
John McCall8a407372010-10-14 22:22:28 +00007286 if (isTemplateId) {
7287 if (isa<TranslationUnitDecl>(DC)) break;
7288 } else {
7289 if (DC->isFileContext()) break;
7290 }
John McCall67d1a672009-08-06 02:15:43 +00007291 DC = DC->getParent();
7292 }
7293
7294 // C++ [class.friend]p1: A friend of a class is a function or
7295 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00007296 // C++0x changes this for both friend types and functions.
7297 // Most C++ 98 compilers do seem to give an error here, so
7298 // we do, too.
John McCall68263142009-11-18 22:49:29 +00007299 if (!Previous.empty() && DC->Equals(CurContext)
7300 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00007301 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00007302
John McCall380aaa42010-10-13 06:22:15 +00007303 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00007304
John McCall337ec3d2010-10-12 23:13:28 +00007305 // - There's a non-dependent scope specifier, in which case we
7306 // compute it and do a previous lookup there for a function
7307 // or function template.
7308 } else if (!SS.getScopeRep()->isDependent()) {
7309 DC = computeDeclContext(SS);
7310 if (!DC) return 0;
7311
7312 if (RequireCompleteDeclContext(SS, DC)) return 0;
7313
7314 LookupQualifiedName(Previous, DC);
7315
7316 // Ignore things found implicitly in the wrong scope.
7317 // TODO: better diagnostics for this case. Suggesting the right
7318 // qualified scope would be nice...
7319 LookupResult::Filter F = Previous.makeFilter();
7320 while (F.hasNext()) {
7321 NamedDecl *D = F.next();
7322 if (!DC->InEnclosingNamespaceSetOf(
7323 D->getDeclContext()->getRedeclContext()))
7324 F.erase();
7325 }
7326 F.done();
7327
7328 if (Previous.empty()) {
7329 D.setInvalidType();
7330 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7331 return 0;
7332 }
7333
7334 // C++ [class.friend]p1: A friend of a class is a function or
7335 // class that is not a member of the class . . .
7336 if (DC->Equals(CurContext))
7337 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7338
7339 // - There's a scope specifier that does not match any template
7340 // parameter lists, in which case we use some arbitrary context,
7341 // create a method or method template, and wait for instantiation.
7342 // - There's a scope specifier that does match some template
7343 // parameter lists, which we don't handle right now.
7344 } else {
7345 DC = CurContext;
7346 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00007347 }
7348
John McCall29ae6e52010-10-13 05:45:15 +00007349 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00007350 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007351 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7352 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7353 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00007354 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00007355 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7356 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00007357 return 0;
John McCall67d1a672009-08-06 02:15:43 +00007358 }
John McCall67d1a672009-08-06 02:15:43 +00007359 }
7360
Douglas Gregor182ddf02009-09-28 00:08:27 +00007361 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00007362 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00007363 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00007364 IsDefinition,
7365 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00007366 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00007367
Douglas Gregor182ddf02009-09-28 00:08:27 +00007368 assert(ND->getDeclContext() == DC);
7369 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00007370
John McCallab88d972009-08-31 22:39:49 +00007371 // Add the function declaration to the appropriate lookup tables,
7372 // adjusting the redeclarations list as necessary. We don't
7373 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00007374 //
John McCallab88d972009-08-31 22:39:49 +00007375 // Also update the scope-based lookup if the target context's
7376 // lookup context is in lexical scope.
7377 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007378 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00007379 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007380 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00007381 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00007382 }
John McCall02cace72009-08-28 07:59:38 +00007383
7384 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00007385 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00007386 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00007387 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00007388 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00007389
John McCall337ec3d2010-10-12 23:13:28 +00007390 if (ND->isInvalidDecl())
7391 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00007392 else {
7393 FunctionDecl *FD;
7394 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7395 FD = FTD->getTemplatedDecl();
7396 else
7397 FD = cast<FunctionDecl>(ND);
7398
7399 // Mark templated-scope function declarations as unsupported.
7400 if (FD->getNumTemplateParameterLists())
7401 FrD->setUnsupportedFriend(true);
7402 }
John McCall337ec3d2010-10-12 23:13:28 +00007403
John McCalld226f652010-08-21 09:40:31 +00007404 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00007405}
7406
John McCalld226f652010-08-21 09:40:31 +00007407void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7408 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00007409
Sebastian Redl50de12f2009-03-24 22:27:57 +00007410 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7411 if (!Fn) {
7412 Diag(DelLoc, diag::err_deleted_non_function);
7413 return;
7414 }
7415 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7416 Diag(DelLoc, diag::err_deleted_decl_not_first);
7417 Diag(Prev->getLocation(), diag::note_previous_declaration);
7418 // If the declaration wasn't the first, we delete the function anyway for
7419 // recovery.
7420 }
7421 Fn->setDeleted();
7422}
Sebastian Redl13e88542009-04-27 21:33:24 +00007423
7424static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00007425 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00007426 Stmt *SubStmt = *CI;
7427 if (!SubStmt)
7428 continue;
7429 if (isa<ReturnStmt>(SubStmt))
7430 Self.Diag(SubStmt->getSourceRange().getBegin(),
7431 diag::err_return_in_constructor_handler);
7432 if (!isa<Expr>(SubStmt))
7433 SearchForReturnInStmt(Self, SubStmt);
7434 }
7435}
7436
7437void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7438 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7439 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7440 SearchForReturnInStmt(*this, Handler);
7441 }
7442}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007443
Mike Stump1eb44332009-09-09 15:08:12 +00007444bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007445 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00007446 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7447 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007448
Chandler Carruth73857792010-02-15 11:53:20 +00007449 if (Context.hasSameType(NewTy, OldTy) ||
7450 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007451 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00007452
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007453 // Check if the return types are covariant
7454 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00007455
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007456 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007457 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7458 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007459 NewClassTy = NewPT->getPointeeType();
7460 OldClassTy = OldPT->getPointeeType();
7461 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007462 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7463 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7464 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7465 NewClassTy = NewRT->getPointeeType();
7466 OldClassTy = OldRT->getPointeeType();
7467 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007468 }
7469 }
Mike Stump1eb44332009-09-09 15:08:12 +00007470
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007471 // The return types aren't either both pointers or references to a class type.
7472 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007473 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007474 diag::err_different_return_type_for_overriding_virtual_function)
7475 << New->getDeclName() << NewTy << OldTy;
7476 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00007477
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007478 return true;
7479 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007480
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007481 // C++ [class.virtual]p6:
7482 // If the return type of D::f differs from the return type of B::f, the
7483 // class type in the return type of D::f shall be complete at the point of
7484 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00007485 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7486 if (!RT->isBeingDefined() &&
7487 RequireCompleteType(New->getLocation(), NewClassTy,
7488 PDiag(diag::err_covariant_return_incomplete)
7489 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007490 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00007491 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00007492
Douglas Gregora4923eb2009-11-16 21:35:15 +00007493 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007494 // Check if the new class derives from the old class.
7495 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7496 Diag(New->getLocation(),
7497 diag::err_covariant_return_not_derived)
7498 << New->getDeclName() << NewTy << OldTy;
7499 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7500 return true;
7501 }
Mike Stump1eb44332009-09-09 15:08:12 +00007502
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007503 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00007504 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00007505 diag::err_covariant_return_inaccessible_base,
7506 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7507 // FIXME: Should this point to the return type?
7508 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00007509 // FIXME: this note won't trigger for delayed access control
7510 // diagnostics, and it's impossible to get an undelayed error
7511 // here from access control during the original parse because
7512 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007513 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7514 return true;
7515 }
7516 }
Mike Stump1eb44332009-09-09 15:08:12 +00007517
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007518 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00007519 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007520 Diag(New->getLocation(),
7521 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007522 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007523 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7524 return true;
7525 };
Mike Stump1eb44332009-09-09 15:08:12 +00007526
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007527
7528 // The new class type must have the same or less qualifiers as the old type.
7529 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7530 Diag(New->getLocation(),
7531 diag::err_covariant_return_type_class_type_more_qualified)
7532 << New->getDeclName() << NewTy << OldTy;
7533 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7534 return true;
7535 };
Mike Stump1eb44332009-09-09 15:08:12 +00007536
Anders Carlssonc3a68b22009-05-14 19:52:19 +00007537 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00007538}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007539
Douglas Gregor4ba31362009-12-01 17:24:26 +00007540/// \brief Mark the given method pure.
7541///
7542/// \param Method the method to be marked pure.
7543///
7544/// \param InitRange the source range that covers the "0" initializer.
7545bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00007546 SourceLocation EndLoc = InitRange.getEnd();
7547 if (EndLoc.isValid())
7548 Method->setRangeEnd(EndLoc);
7549
Douglas Gregor4ba31362009-12-01 17:24:26 +00007550 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7551 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00007552 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00007553 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00007554
7555 if (!Method->isInvalidDecl())
7556 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7557 << Method->getDeclName() << InitRange;
7558 return true;
7559}
7560
John McCall731ad842009-12-19 09:28:58 +00007561/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7562/// an initializer for the out-of-line declaration 'Dcl'. The scope
7563/// is a fresh scope pushed for just this purpose.
7564///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007565/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7566/// static data member of class X, names should be looked up in the scope of
7567/// class X.
John McCalld226f652010-08-21 09:40:31 +00007568void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007569 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007570 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007571
John McCall731ad842009-12-19 09:28:58 +00007572 // We should only get called for declarations with scope specifiers, like:
7573 // int foo::bar;
7574 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007575 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007576}
7577
7578/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00007579/// initializer for the out-of-line declaration 'D'.
7580void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007581 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00007582 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007583
John McCall731ad842009-12-19 09:28:58 +00007584 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00007585 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00007586}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007587
7588/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7589/// C++ if/switch/while/for statement.
7590/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00007591DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007592 // C++ 6.4p2:
7593 // The declarator shall not specify a function or an array.
7594 // The type-specifier-seq shall not contain typedef and shall not declare a
7595 // new class or enumeration.
7596 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7597 "Parser allowed 'typedef' as storage class of condition decl.");
7598
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007599 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00007600 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7601 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007602
7603 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7604 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7605 // would be created and CXXConditionDeclExpr wants a VarDecl.
7606 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7607 << D.getSourceRange();
7608 return DeclResult();
7609 } else if (OwnedTag && OwnedTag->isDefinition()) {
7610 // The type-specifier-seq shall not declare a new class or enumeration.
7611 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7612 }
7613
John McCalld226f652010-08-21 09:40:31 +00007614 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007615 if (!Dcl)
7616 return DeclResult();
7617
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00007618 return Dcl;
7619}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007620
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007621void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7622 bool DefinitionRequired) {
7623 // Ignore any vtable uses in unevaluated operands or for classes that do
7624 // not have a vtable.
7625 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7626 CurContext->isDependentContext() ||
7627 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00007628 return;
7629
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007630 // Try to insert this class into the map.
7631 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7632 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7633 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7634 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00007635 // If we already had an entry, check to see if we are promoting this vtable
7636 // to required a definition. If so, we need to reappend to the VTableUses
7637 // list, since we may have already processed the first entry.
7638 if (DefinitionRequired && !Pos.first->second) {
7639 Pos.first->second = true;
7640 } else {
7641 // Otherwise, we can early exit.
7642 return;
7643 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007644 }
7645
7646 // Local classes need to have their virtual members marked
7647 // immediately. For all other classes, we mark their virtual members
7648 // at the end of the translation unit.
7649 if (Class->isLocalClass())
7650 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00007651 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007652 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00007653}
7654
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007655bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007656 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00007657 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00007658
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007659 // Note: The VTableUses vector could grow as a result of marking
7660 // the members of a class as "used", so we check the size each
7661 // time through the loop and prefer indices (with are stable) to
7662 // iterators (which are not).
7663 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00007664 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007665 if (!Class)
7666 continue;
7667
7668 SourceLocation Loc = VTableUses[I].second;
7669
7670 // If this class has a key function, but that key function is
7671 // defined in another translation unit, we don't need to emit the
7672 // vtable even though we're using it.
7673 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007674 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007675 switch (KeyFunction->getTemplateSpecializationKind()) {
7676 case TSK_Undeclared:
7677 case TSK_ExplicitSpecialization:
7678 case TSK_ExplicitInstantiationDeclaration:
7679 // The key function is in another translation unit.
7680 continue;
7681
7682 case TSK_ExplicitInstantiationDefinition:
7683 case TSK_ImplicitInstantiation:
7684 // We will be instantiating the key function.
7685 break;
7686 }
7687 } else if (!KeyFunction) {
7688 // If we have a class with no key function that is the subject
7689 // of an explicit instantiation declaration, suppress the
7690 // vtable; it will live with the explicit instantiation
7691 // definition.
7692 bool IsExplicitInstantiationDeclaration
7693 = Class->getTemplateSpecializationKind()
7694 == TSK_ExplicitInstantiationDeclaration;
7695 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7696 REnd = Class->redecls_end();
7697 R != REnd; ++R) {
7698 TemplateSpecializationKind TSK
7699 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7700 if (TSK == TSK_ExplicitInstantiationDeclaration)
7701 IsExplicitInstantiationDeclaration = true;
7702 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7703 IsExplicitInstantiationDeclaration = false;
7704 break;
7705 }
7706 }
7707
7708 if (IsExplicitInstantiationDeclaration)
7709 continue;
7710 }
7711
7712 // Mark all of the virtual members of this class as referenced, so
7713 // that we can build a vtable. Then, tell the AST consumer that a
7714 // vtable for this class is required.
7715 MarkVirtualMembersReferenced(Loc, Class);
7716 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7717 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7718
7719 // Optionally warn if we're emitting a weak vtable.
7720 if (Class->getLinkage() == ExternalLinkage &&
7721 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007722 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007723 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7724 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007725 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007726 VTableUses.clear();
7727
Anders Carlssond6a637f2009-12-07 08:24:59 +00007728 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007729}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007730
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007731void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7732 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007733 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7734 e = RD->method_end(); i != e; ++i) {
7735 CXXMethodDecl *MD = *i;
7736
7737 // C++ [basic.def.odr]p2:
7738 // [...] A virtual member function is used if it is not pure. [...]
7739 if (MD->isVirtual() && !MD->isPure())
7740 MarkDeclarationReferenced(Loc, MD);
7741 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007742
7743 // Only classes that have virtual bases need a VTT.
7744 if (RD->getNumVBases() == 0)
7745 return;
7746
7747 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7748 e = RD->bases_end(); i != e; ++i) {
7749 const CXXRecordDecl *Base =
7750 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007751 if (Base->getNumVBases() == 0)
7752 continue;
7753 MarkVirtualMembersReferenced(Loc, Base);
7754 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007755}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007756
7757/// SetIvarInitializers - This routine builds initialization ASTs for the
7758/// Objective-C implementation whose ivars need be initialized.
7759void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7760 if (!getLangOptions().CPlusPlus)
7761 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007762 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007763 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7764 CollectIvarsToConstructOrDestruct(OID, ivars);
7765 if (ivars.empty())
7766 return;
Sean Huntcbb67482011-01-08 20:30:50 +00007767 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007768 for (unsigned i = 0; i < ivars.size(); i++) {
7769 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007770 if (Field->isInvalidDecl())
7771 continue;
7772
Sean Huntcbb67482011-01-08 20:30:50 +00007773 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007774 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7775 InitializationKind InitKind =
7776 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7777
7778 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007779 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007780 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007781 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007782 // Note, MemberInit could actually come back empty if no initialization
7783 // is required (e.g., because it would call a trivial default constructor)
7784 if (!MemberInit.get() || MemberInit.isInvalid())
7785 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007786
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007787 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00007788 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7789 SourceLocation(),
7790 MemberInit.takeAs<Expr>(),
7791 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007792 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007793
7794 // Be sure that the destructor is accessible and is marked as referenced.
7795 if (const RecordType *RecordTy
7796 = Context.getBaseElementType(Field->getType())
7797 ->getAs<RecordType>()) {
7798 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007799 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007800 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7801 CheckDestructorAccess(Field->getLocation(), Destructor,
7802 PDiag(diag::err_access_dtor_ivar)
7803 << Context.getBaseElementType(Field->getType()));
7804 }
7805 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007806 }
7807 ObjCImplementation->setIvarInitializers(Context,
7808 AllToInit.data(), AllToInit.size());
7809 }
7810}