blob: d2575315654aac84d28ac28d996e43143a91ceab [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000138
John McCallb4eb64d2010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson9351c172009-08-25 03:18:48 +0000157 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000158}
159
Chris Lattner8123a952008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163void
John McCalld226f652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000167 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000168
John McCalld226f652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177 return;
178 }
179
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
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 else
Mike Stump1eb44332009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner3d1cee32008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000437
Douglas Gregorb48fe382008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump1eb44332009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Nick Lewycky56062202010-07-26 16:56:01 +0000467 TypeSourceInfo *TInfo) {
468 QualType BaseType = TInfo->getType();
469
Douglas Gregor2943aed2009-03-03 04:44:36 +0000470 // C++ [class.union]p1:
471 // A union shall not have base classes.
472 if (Class->isUnion()) {
473 Diag(Class->getLocation(), diag::err_base_clause_on_union)
474 << SpecifierRange;
475 return 0;
476 }
477
478 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000479 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000480 Class->getTagKind() == TTK_Class,
481 Access, TInfo);
482
483 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000484
485 // Base specifiers must be record types.
486 if (!BaseType->isRecordType()) {
487 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
488 return 0;
489 }
490
491 // C++ [class.union]p1:
492 // A union shall not be used as a base class.
493 if (BaseType->isUnionType()) {
494 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
495 return 0;
496 }
497
498 // C++ [class.derived]p2:
499 // The class-name in a base-specifier shall not be an incompletely
500 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000501 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000502 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000503 << SpecifierRange)) {
504 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000505 return 0;
John McCall572fc622010-08-17 07:23:57 +0000506 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000507
Eli Friedman1d954f62009-08-15 21:55:26 +0000508 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000509 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000510 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000511 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000512 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000513 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
514 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000515
Sean Huntbbd37c62009-11-21 08:43:09 +0000516 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
517 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
518 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000519 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
520 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000521 return 0;
522 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523
John McCall572fc622010-08-17 07:23:57 +0000524 if (BaseDecl->isInvalidDecl())
525 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000526
527 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000528 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000529 Class->getTagKind() == TTK_Class,
530 Access, TInfo);
Anders Carlsson51f94042009-12-03 17:49:57 +0000531}
532
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000533/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
534/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000535/// example:
536/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000537/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000538BaseResult
John McCalld226f652010-08-21 09:40:31 +0000539Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000540 bool Virtual, AccessSpecifier Access,
John McCallb3d87482010-08-24 05:47:05 +0000541 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000542 if (!classdecl)
543 return true;
544
Douglas Gregor40808ce2009-03-09 23:48:35 +0000545 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000546 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000547 if (!Class)
548 return true;
549
Nick Lewycky56062202010-07-26 16:56:01 +0000550 TypeSourceInfo *TInfo = 0;
551 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000552
553 if (DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
554 UPPC_BaseType))
555 return true;
556
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000558 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000559 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Douglas Gregor2943aed2009-03-03 04:44:36 +0000561 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000562}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000563
Douglas Gregor2943aed2009-03-03 04:44:36 +0000564/// \brief Performs the actual work of attaching the given base class
565/// specifiers to a C++ class.
566bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
567 unsigned NumBases) {
568 if (NumBases == 0)
569 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000570
571 // Used to keep track of which base types we have already seen, so
572 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000573 // that the key is always the unqualified canonical type of the base
574 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000575 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
576
577 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000578 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000579 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000580 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000581 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000583 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000584 if (!Class->hasObjectMember()) {
585 if (const RecordType *FDTTy =
586 NewBaseType.getTypePtr()->getAs<RecordType>())
587 if (FDTTy->getDecl()->hasObjectMember())
588 Class->setHasObjectMember(true);
589 }
590
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000591 if (KnownBaseTypes[NewBaseType]) {
592 // C++ [class.mi]p3:
593 // A class shall not be specified as a direct base class of a
594 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000596 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000597 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000599
600 // Delete the duplicate base class specifier; we're going to
601 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000602 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603
604 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605 } else {
606 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000607 KnownBaseTypes[NewBaseType] = Bases[idx];
608 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609 }
610 }
611
612 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000613 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000614
615 // Delete the remaining (good) base class specifiers, since their
616 // data has been copied into the CXXRecordDecl.
617 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000618 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000619
620 return Invalid;
621}
622
623/// ActOnBaseSpecifiers - Attach the given base specifiers to the
624/// class, after checking whether there are any duplicate base
625/// classes.
John McCalld226f652010-08-21 09:40:31 +0000626void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 unsigned NumBases) {
628 if (!ClassDecl || !Bases || !NumBases)
629 return;
630
631 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000632 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000634}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000635
John McCall3cb0ebd2010-03-10 03:28:59 +0000636static CXXRecordDecl *GetClassForType(QualType T) {
637 if (const RecordType *RT = T->getAs<RecordType>())
638 return cast<CXXRecordDecl>(RT->getDecl());
639 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
640 return ICT->getDecl();
641 else
642 return 0;
643}
644
Douglas Gregora8f32e02009-10-06 17:59:45 +0000645/// \brief Determine whether the type \p Derived is a C++ class that is
646/// derived from the type \p Base.
647bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
648 if (!getLangOptions().CPlusPlus)
649 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000650
651 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
652 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000653 return false;
654
John McCall3cb0ebd2010-03-10 03:28:59 +0000655 CXXRecordDecl *BaseRD = GetClassForType(Base);
656 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000657 return false;
658
John McCall86ff3082010-02-04 22:26:26 +0000659 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
660 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000661}
662
663/// \brief Determine whether the type \p Derived is a C++ class that is
664/// derived from the type \p Base.
665bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
666 if (!getLangOptions().CPlusPlus)
667 return false;
668
John McCall3cb0ebd2010-03-10 03:28:59 +0000669 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
670 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000671 return false;
672
John McCall3cb0ebd2010-03-10 03:28:59 +0000673 CXXRecordDecl *BaseRD = GetClassForType(Base);
674 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000675 return false;
676
Douglas Gregora8f32e02009-10-06 17:59:45 +0000677 return DerivedRD->isDerivedFrom(BaseRD, Paths);
678}
679
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000680void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000681 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000682 assert(BasePathArray.empty() && "Base path array must be empty!");
683 assert(Paths.isRecordingPaths() && "Must record paths!");
684
685 const CXXBasePath &Path = Paths.front();
686
687 // We first go backward and check if we have a virtual base.
688 // FIXME: It would be better if CXXBasePath had the base specifier for
689 // the nearest virtual base.
690 unsigned Start = 0;
691 for (unsigned I = Path.size(); I != 0; --I) {
692 if (Path[I - 1].Base->isVirtual()) {
693 Start = I - 1;
694 break;
695 }
696 }
697
698 // Now add all bases.
699 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000700 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000701}
702
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000703/// \brief Determine whether the given base path includes a virtual
704/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000705bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
706 for (CXXCastPath::const_iterator B = BasePath.begin(),
707 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000708 B != BEnd; ++B)
709 if ((*B)->isVirtual())
710 return true;
711
712 return false;
713}
714
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
716/// conversion (where Derived and Base are class types) is
717/// well-formed, meaning that the conversion is unambiguous (and
718/// that all of the base classes are accessible). Returns true
719/// and emits a diagnostic if the code is ill-formed, returns false
720/// otherwise. Loc is the location where this routine should point to
721/// if there is an error, and Range is the source range to highlight
722/// if there is an error.
723bool
724Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000725 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000726 unsigned AmbigiousBaseConvID,
727 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000728 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000729 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000730 // First, determine whether the path from Derived to Base is
731 // ambiguous. This is slightly more expensive than checking whether
732 // the Derived to Base conversion exists, because here we need to
733 // explore multiple paths to determine if there is an ambiguity.
734 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
735 /*DetectVirtual=*/false);
736 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
737 assert(DerivationOkay &&
738 "Can only be used with a derived-to-base conversion");
739 (void)DerivationOkay;
740
741 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000742 if (InaccessibleBaseID) {
743 // Check that the base class can be accessed.
744 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
745 InaccessibleBaseID)) {
746 case AR_inaccessible:
747 return true;
748 case AR_accessible:
749 case AR_dependent:
750 case AR_delayed:
751 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000752 }
John McCall6b2accb2010-02-10 09:31:12 +0000753 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000754
755 // Build a base path if necessary.
756 if (BasePath)
757 BuildBasePathArray(Paths, *BasePath);
758 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000759 }
760
761 // We know that the derived-to-base conversion is ambiguous, and
762 // we're going to produce a diagnostic. Perform the derived-to-base
763 // search just one more time to compute all of the possible paths so
764 // that we can print them out. This is more expensive than any of
765 // the previous derived-to-base checks we've done, but at this point
766 // performance isn't as much of an issue.
767 Paths.clear();
768 Paths.setRecordingPaths(true);
769 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
770 assert(StillOkay && "Can only be used with a derived-to-base conversion");
771 (void)StillOkay;
772
773 // Build up a textual representation of the ambiguous paths, e.g.,
774 // D -> B -> A, that will be used to illustrate the ambiguous
775 // conversions in the diagnostic. We only print one of the paths
776 // to each base class subobject.
777 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
778
779 Diag(Loc, AmbigiousBaseConvID)
780 << Derived << Base << PathDisplayStr << Range << Name;
781 return true;
782}
783
784bool
785Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000786 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000787 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000788 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000789 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000790 IgnoreAccess ? 0
791 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000792 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000793 Loc, Range, DeclarationName(),
794 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000795}
796
797
798/// @brief Builds a string representing ambiguous paths from a
799/// specific derived class to different subobjects of the same base
800/// class.
801///
802/// This function builds a string that can be used in error messages
803/// to show the different paths that one can take through the
804/// inheritance hierarchy to go from the derived class to different
805/// subobjects of a base class. The result looks something like this:
806/// @code
807/// struct D -> struct B -> struct A
808/// struct D -> struct C -> struct A
809/// @endcode
810std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
811 std::string PathDisplayStr;
812 std::set<unsigned> DisplayedPaths;
813 for (CXXBasePaths::paths_iterator Path = Paths.begin();
814 Path != Paths.end(); ++Path) {
815 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
816 // We haven't displayed a path to this particular base
817 // class subobject yet.
818 PathDisplayStr += "\n ";
819 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
820 for (CXXBasePath::const_iterator Element = Path->begin();
821 Element != Path->end(); ++Element)
822 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
823 }
824 }
825
826 return PathDisplayStr;
827}
828
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829//===----------------------------------------------------------------------===//
830// C++ class member Handling
831//===----------------------------------------------------------------------===//
832
Abramo Bagnara6206d532010-06-05 05:09:32 +0000833/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000834Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
835 SourceLocation ASLoc,
836 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000837 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000838 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000839 ASLoc, ColonLoc);
840 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000841 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000842}
843
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000844/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
845/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
846/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000847/// any.
John McCalld226f652010-08-21 09:40:31 +0000848Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000849Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000850 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000851 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
852 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000853 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000854 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
855 DeclarationName Name = NameInfo.getName();
856 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +0000857
858 // For anonymous bitfields, the location should point to the type.
859 if (Loc.isInvalid())
860 Loc = D.getSourceRange().getBegin();
861
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000862 Expr *BitWidth = static_cast<Expr*>(BW);
863 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864
John McCall4bde1e12010-06-04 08:34:12 +0000865 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000866 assert(!DS.isFriendSpecified());
867
John McCall4bde1e12010-06-04 08:34:12 +0000868 bool isFunc = false;
869 if (D.isFunctionDeclarator())
870 isFunc = true;
871 else if (D.getNumTypeObjects() == 0 &&
872 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000873 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000874 isFunc = TDType->isFunctionType();
875 }
876
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000877 // C++ 9.2p6: A member shall not be declared to have automatic storage
878 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000879 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
880 // data members and cannot be applied to names declared const or static,
881 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000882 switch (DS.getStorageClassSpec()) {
883 case DeclSpec::SCS_unspecified:
884 case DeclSpec::SCS_typedef:
885 case DeclSpec::SCS_static:
886 // FALL THROUGH.
887 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000888 case DeclSpec::SCS_mutable:
889 if (isFunc) {
890 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000891 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000892 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000893 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Sebastian Redla11f42f2008-11-17 23:24:37 +0000895 // FIXME: It would be nicer if the keyword was ignored only for this
896 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000897 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000898 }
899 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000900 default:
901 if (DS.getStorageClassSpecLoc().isValid())
902 Diag(DS.getStorageClassSpecLoc(),
903 diag::err_storageclass_invalid_for_member);
904 else
905 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
906 D.getMutableDeclSpec().ClearStorageClassSpecs();
907 }
908
Sebastian Redl669d5d72008-11-14 23:42:31 +0000909 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
910 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000911 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000912
913 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000914 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +0000915 CXXScopeSpec &SS = D.getCXXScopeSpec();
916
917
918 if (SS.isSet() && !SS.isInvalid()) {
919 // The user provided a superfluous scope specifier inside a class
920 // definition:
921 //
922 // class X {
923 // int X::member;
924 // };
925 DeclContext *DC = 0;
926 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
927 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
928 << Name << FixItHint::CreateRemoval(SS.getRange());
929 else
930 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
931 << Name << SS.getRange();
932
933 SS.clear();
934 }
935
Douglas Gregor37b372b2009-08-20 22:52:58 +0000936 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +0000937 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
939 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000940 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000941 } else {
John McCalld226f652010-08-21 09:40:31 +0000942 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000943 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000944 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000945 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000946
947 // Non-instance-fields can't have a bitfield.
948 if (BitWidth) {
949 if (Member->isInvalidDecl()) {
950 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000951 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000952 // C++ 9.6p3: A bit-field shall not be a static member.
953 // "static member 'A' cannot be a bit-field"
954 Diag(Loc, diag::err_static_not_bitfield)
955 << Name << BitWidth->getSourceRange();
956 } else if (isa<TypedefDecl>(Member)) {
957 // "typedef member 'x' cannot be a bit-field"
958 Diag(Loc, diag::err_typedef_not_bitfield)
959 << Name << BitWidth->getSourceRange();
960 } else {
961 // A function typedef ("typedef int f(); f a;").
962 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
963 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000964 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000965 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner8b963ef2009-03-05 23:01:03 +0000968 BitWidth = 0;
969 Member->setInvalidDecl();
970 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000971
972 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregor37b372b2009-08-20 22:52:58 +0000974 // If we have declared a member function template, set the access of the
975 // templated declaration as well.
976 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
977 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000978 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000979
Douglas Gregor10bd3682008-11-17 22:58:34 +0000980 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000981
Douglas Gregor021c3b32009-03-11 23:00:04 +0000982 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +0000983 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000984 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +0000985 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000986
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000987 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000988 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +0000989 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000990 }
John McCalld226f652010-08-21 09:40:31 +0000991 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992}
993
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000994/// \brief Find the direct and/or virtual base specifiers that
995/// correspond to the given base type, for use in base initialization
996/// within a constructor.
997static bool FindBaseInitializer(Sema &SemaRef,
998 CXXRecordDecl *ClassDecl,
999 QualType BaseType,
1000 const CXXBaseSpecifier *&DirectBaseSpec,
1001 const CXXBaseSpecifier *&VirtualBaseSpec) {
1002 // First, check for a direct base class.
1003 DirectBaseSpec = 0;
1004 for (CXXRecordDecl::base_class_const_iterator Base
1005 = ClassDecl->bases_begin();
1006 Base != ClassDecl->bases_end(); ++Base) {
1007 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1008 // We found a direct base of this type. That's what we're
1009 // initializing.
1010 DirectBaseSpec = &*Base;
1011 break;
1012 }
1013 }
1014
1015 // Check for a virtual base class.
1016 // FIXME: We might be able to short-circuit this if we know in advance that
1017 // there are no virtual bases.
1018 VirtualBaseSpec = 0;
1019 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1020 // We haven't found a base yet; search the class hierarchy for a
1021 // virtual base class.
1022 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1023 /*DetectVirtual=*/false);
1024 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1025 BaseType, Paths)) {
1026 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1027 Path != Paths.end(); ++Path) {
1028 if (Path->back().Base->isVirtual()) {
1029 VirtualBaseSpec = Path->back().Base;
1030 break;
1031 }
1032 }
1033 }
1034 }
1035
1036 return DirectBaseSpec || VirtualBaseSpec;
1037}
1038
Douglas Gregor7ad83902008-11-05 04:29:56 +00001039/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001040MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001041Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001042 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001043 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001044 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001045 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001046 SourceLocation IdLoc,
1047 SourceLocation LParenLoc,
1048 ExprTy **Args, unsigned NumArgs,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001049 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001050 if (!ConstructorD)
1051 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001053 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
1055 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001056 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001057 if (!Constructor) {
1058 // The user wrote a constructor initializer on a function that is
1059 // not a C++ constructor. Ignore the error for now, because we may
1060 // have more member initializers coming; we'll diagnose it just
1061 // once in ActOnMemInitializers.
1062 return true;
1063 }
1064
1065 CXXRecordDecl *ClassDecl = Constructor->getParent();
1066
1067 // C++ [class.base.init]p2:
1068 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001069 // constructor's class and, if not found in that scope, are looked
1070 // up in the scope containing the constructor's definition.
1071 // [Note: if the constructor's class contains a member with the
1072 // same name as a direct or virtual base class of the class, a
1073 // mem-initializer-id naming the member or base class and composed
1074 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001075 // mem-initializer-id for the hidden base class may be specified
1076 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001077 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001078 // Look for a member, first.
1079 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001080 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001081 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001082 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001083 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001084
Francois Pichet00eb3f92010-12-04 09:14:42 +00001085 if (Member)
1086 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001087 LParenLoc, RParenLoc);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001088 // Handle anonymous union case.
1089 if (IndirectFieldDecl* IndirectField
1090 = dyn_cast<IndirectFieldDecl>(*Result.first))
1091 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1092 NumArgs, IdLoc,
1093 LParenLoc, RParenLoc);
1094 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001095 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001096 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001097 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001098 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001099
1100 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001101 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001102 } else {
1103 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1104 LookupParsedName(R, S, &SS);
1105
1106 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1107 if (!TyD) {
1108 if (R.isAmbiguous()) return true;
1109
John McCallfd225442010-04-09 19:01:14 +00001110 // We don't want access-control diagnostics here.
1111 R.suppressDiagnostics();
1112
Douglas Gregor7a886e12010-01-19 06:46:48 +00001113 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1114 bool NotUnknownSpecialization = false;
1115 DeclContext *DC = computeDeclContext(SS, false);
1116 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1117 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1118
1119 if (!NotUnknownSpecialization) {
1120 // When the scope specifier can refer to a member of an unknown
1121 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001122 BaseType = CheckTypenameType(ETK_None,
1123 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001124 *MemberOrBase, SourceLocation(),
1125 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001126 if (BaseType.isNull())
1127 return true;
1128
Douglas Gregor7a886e12010-01-19 06:46:48 +00001129 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001130 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001131 }
1132 }
1133
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001134 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001135 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001136 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1137 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001138 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001139 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001140 // We have found a non-static data member with a similar
1141 // name to what was typed; complain and initialize that
1142 // member.
1143 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1144 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001145 << FixItHint::CreateReplacement(R.getNameLoc(),
1146 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001147 Diag(Member->getLocation(), diag::note_previous_decl)
1148 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001149
1150 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1151 LParenLoc, RParenLoc);
1152 }
1153 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1154 const CXXBaseSpecifier *DirectBaseSpec;
1155 const CXXBaseSpecifier *VirtualBaseSpec;
1156 if (FindBaseInitializer(*this, ClassDecl,
1157 Context.getTypeDeclType(Type),
1158 DirectBaseSpec, VirtualBaseSpec)) {
1159 // We have found a direct or virtual base class with a
1160 // similar name to what was typed; complain and initialize
1161 // that base class.
1162 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1163 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001164 << FixItHint::CreateReplacement(R.getNameLoc(),
1165 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001166
1167 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1168 : VirtualBaseSpec;
1169 Diag(BaseSpec->getSourceRange().getBegin(),
1170 diag::note_base_class_specified_here)
1171 << BaseSpec->getType()
1172 << BaseSpec->getSourceRange();
1173
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001174 TyD = Type;
1175 }
1176 }
1177 }
1178
Douglas Gregor7a886e12010-01-19 06:46:48 +00001179 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001180 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1181 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1182 return true;
1183 }
John McCall2b194412009-12-21 10:41:20 +00001184 }
1185
Douglas Gregor7a886e12010-01-19 06:46:48 +00001186 if (BaseType.isNull()) {
1187 BaseType = Context.getTypeDeclType(TyD);
1188 if (SS.isSet()) {
1189 NestedNameSpecifier *Qualifier =
1190 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001191
Douglas Gregor7a886e12010-01-19 06:46:48 +00001192 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001193 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001194 }
John McCall2b194412009-12-21 10:41:20 +00001195 }
1196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
John McCalla93c9342009-12-07 02:54:59 +00001198 if (!TInfo)
1199 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001200
John McCalla93c9342009-12-07 02:54:59 +00001201 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001202 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001203}
1204
John McCallb4190042009-11-04 23:02:40 +00001205/// Checks an initializer expression for use of uninitialized fields, such as
1206/// containing the field that is being initialized. Returns true if there is an
1207/// uninitialized field was used an updates the SourceLocation parameter; false
1208/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001209static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001210 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001211 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001212 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1213
Nick Lewycky43ad1822010-06-15 07:32:55 +00001214 if (isa<CallExpr>(S)) {
1215 // Do not descend into function calls or constructors, as the use
1216 // of an uninitialized field may be valid. One would have to inspect
1217 // the contents of the function/ctor to determine if it is safe or not.
1218 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1219 // may be safe, depending on what the function/ctor does.
1220 return false;
1221 }
1222 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1223 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001224
1225 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1226 // The member expression points to a static data member.
1227 assert(VD->isStaticDataMember() &&
1228 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001229 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001230 return false;
1231 }
1232
1233 if (isa<EnumConstantDecl>(RhsField)) {
1234 // The member expression points to an enum.
1235 return false;
1236 }
1237
John McCallb4190042009-11-04 23:02:40 +00001238 if (RhsField == LhsField) {
1239 // Initializing a field with itself. Throw a warning.
1240 // But wait; there are exceptions!
1241 // Exception #1: The field may not belong to this record.
1242 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001243 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001244 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1245 // Even though the field matches, it does not belong to this record.
1246 return false;
1247 }
1248 // None of the exceptions triggered; return true to indicate an
1249 // uninitialized field was used.
1250 *L = ME->getMemberLoc();
1251 return true;
1252 }
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001253 } else if (isa<SizeOfAlignOfExpr>(S)) {
1254 // sizeof/alignof doesn't reference contents, do not warn.
1255 return false;
1256 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1257 // address-of doesn't reference contents (the pointer may be dereferenced
1258 // in the same expression but it would be rare; and weird).
1259 if (UOE->getOpcode() == UO_AddrOf)
1260 return false;
John McCallb4190042009-11-04 23:02:40 +00001261 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001262 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1263 it != e; ++it) {
1264 if (!*it) {
1265 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001266 continue;
1267 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001268 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1269 return true;
John McCallb4190042009-11-04 23:02:40 +00001270 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001271 return false;
John McCallb4190042009-11-04 23:02:40 +00001272}
1273
John McCallf312b1e2010-08-26 23:41:50 +00001274MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001275Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001276 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001277 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001278 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001279 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1280 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1281 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001282 "Member must be a FieldDecl or IndirectFieldDecl");
1283
Douglas Gregor464b2f02010-11-05 22:21:31 +00001284 if (Member->isInvalidDecl())
1285 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001286
John McCallb4190042009-11-04 23:02:40 +00001287 // Diagnose value-uses of fields to initialize themselves, e.g.
1288 // foo(foo)
1289 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001290 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001291 for (unsigned i = 0; i < NumArgs; ++i) {
1292 SourceLocation L;
1293 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1294 // FIXME: Return true in the case when other fields are used before being
1295 // uninitialized. For example, let this field be the i'th field. When
1296 // initializing the i'th field, throw a warning if any of the >= i'th
1297 // fields are used, as they are not yet initialized.
1298 // Right now we are only handling the case where the i'th field uses
1299 // itself in its initializer.
1300 Diag(L, diag::warn_field_is_uninit);
1301 }
1302 }
1303
Eli Friedman59c04372009-07-29 19:44:27 +00001304 bool HasDependentArg = false;
1305 for (unsigned i = 0; i < NumArgs; i++)
1306 HasDependentArg |= Args[i]->isTypeDependent();
1307
Chandler Carruth894aed92010-12-06 09:23:57 +00001308 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001309 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001310 // Can't check initialization for a member of dependent type or when
1311 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001312 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1313 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001314
1315 // Erase any temporaries within this evaluation context; we're not
1316 // going to track them in the AST, since we'll be rebuilding the
1317 // ASTs during template instantiation.
1318 ExprTemporaries.erase(
1319 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1320 ExprTemporaries.end());
Chandler Carruth894aed92010-12-06 09:23:57 +00001321 } else {
1322 // Initialize the member.
1323 InitializedEntity MemberEntity =
1324 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1325 : InitializedEntity::InitializeMember(IndirectMember, 0);
1326 InitializationKind Kind =
1327 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001328
Chandler Carruth894aed92010-12-06 09:23:57 +00001329 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1330
1331 ExprResult MemberInit =
1332 InitSeq.Perform(*this, MemberEntity, Kind,
1333 MultiExprArg(*this, Args, NumArgs), 0);
1334 if (MemberInit.isInvalid())
1335 return true;
1336
1337 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1338
1339 // C++0x [class.base.init]p7:
1340 // The initialization of each base and member constitutes a
1341 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001342 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001343 if (MemberInit.isInvalid())
1344 return true;
1345
1346 // If we are in a dependent context, template instantiation will
1347 // perform this type-checking again. Just save the arguments that we
1348 // received in a ParenListExpr.
1349 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1350 // of the information that we have about the member
1351 // initializer. However, deconstructing the ASTs is a dicey process,
1352 // and this approach is far more likely to get the corner cases right.
1353 if (CurContext->isDependentContext())
1354 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1355 RParenLoc);
1356 else
1357 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001358 }
1359
Chandler Carruth894aed92010-12-06 09:23:57 +00001360 if (DirectMember) {
1361 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember,
1362 IdLoc, LParenLoc, Init,
1363 RParenLoc);
1364 } else {
1365 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember,
1366 IdLoc, LParenLoc, Init,
1367 RParenLoc);
1368 }
Eli Friedman59c04372009-07-29 19:44:27 +00001369}
1370
John McCallf312b1e2010-08-26 23:41:50 +00001371MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001372Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001373 Expr **Args, unsigned NumArgs,
1374 SourceLocation LParenLoc, SourceLocation RParenLoc,
1375 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001376 bool HasDependentArg = false;
1377 for (unsigned i = 0; i < NumArgs; i++)
1378 HasDependentArg |= Args[i]->isTypeDependent();
1379
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001380 SourceLocation BaseLoc
1381 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1382
1383 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1384 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1385 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1386
1387 // C++ [class.base.init]p2:
1388 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001389 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001390 // of that class, the mem-initializer is ill-formed. A
1391 // mem-initializer-list can initialize a base class using any
1392 // name that denotes that base class type.
1393 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1394
1395 // Check for direct and virtual base classes.
1396 const CXXBaseSpecifier *DirectBaseSpec = 0;
1397 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1398 if (!Dependent) {
1399 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1400 VirtualBaseSpec);
1401
1402 // C++ [base.class.init]p2:
1403 // Unless the mem-initializer-id names a nonstatic data member of the
1404 // constructor's class or a direct or virtual base of that class, the
1405 // mem-initializer is ill-formed.
1406 if (!DirectBaseSpec && !VirtualBaseSpec) {
1407 // If the class has any dependent bases, then it's possible that
1408 // one of those types will resolve to the same type as
1409 // BaseType. Therefore, just treat this as a dependent base
1410 // class initialization. FIXME: Should we try to check the
1411 // initialization anyway? It seems odd.
1412 if (ClassDecl->hasAnyDependentBases())
1413 Dependent = true;
1414 else
1415 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1416 << BaseType << Context.getTypeDeclType(ClassDecl)
1417 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1418 }
1419 }
1420
1421 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001422 // Can't check initialization for a base of dependent type or when
1423 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001424 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001425 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1426 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001427
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001428 // Erase any temporaries within this evaluation context; we're not
1429 // going to track them in the AST, since we'll be rebuilding the
1430 // ASTs during template instantiation.
1431 ExprTemporaries.erase(
1432 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1433 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001435 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001436 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001437 LParenLoc,
1438 BaseInit.takeAs<Expr>(),
1439 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001440 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001441
1442 // C++ [base.class.init]p2:
1443 // If a mem-initializer-id is ambiguous because it designates both
1444 // a direct non-virtual base class and an inherited virtual base
1445 // class, the mem-initializer is ill-formed.
1446 if (DirectBaseSpec && VirtualBaseSpec)
1447 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001448 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001449
1450 CXXBaseSpecifier *BaseSpec
1451 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1452 if (!BaseSpec)
1453 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1454
1455 // Initialize the base.
1456 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001457 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001458 InitializationKind Kind =
1459 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1460
1461 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1462
John McCall60d7b3a2010-08-24 06:29:42 +00001463 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001464 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001465 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001466 if (BaseInit.isInvalid())
1467 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001468
1469 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001470
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 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001475 if (BaseInit.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 base
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()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001486 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001487 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1488 RParenLoc));
1489 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001490 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001491 LParenLoc,
1492 Init.takeAs<Expr>(),
1493 RParenLoc);
1494 }
1495
1496 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001497 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001498 LParenLoc,
1499 BaseInit.takeAs<Expr>(),
1500 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001501}
1502
Anders Carlssone5ef7402010-04-23 03:10:23 +00001503/// ImplicitInitializerKind - How an implicit base or member initializer should
1504/// initialize its base or member.
1505enum ImplicitInitializerKind {
1506 IIK_Default,
1507 IIK_Copy,
1508 IIK_Move
1509};
1510
Anders Carlssondefefd22010-04-23 02:00:02 +00001511static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001512BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001513 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001514 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001515 bool IsInheritedVirtualBase,
1516 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001517 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001518 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1519 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001520
John McCall60d7b3a2010-08-24 06:29:42 +00001521 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001522
1523 switch (ImplicitInitKind) {
1524 case IIK_Default: {
1525 InitializationKind InitKind
1526 = InitializationKind::CreateDefault(Constructor->getLocation());
1527 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1528 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001529 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001530 break;
1531 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001532
Anders Carlssone5ef7402010-04-23 03:10:23 +00001533 case IIK_Copy: {
1534 ParmVarDecl *Param = Constructor->getParamDecl(0);
1535 QualType ParamType = Param->getType().getNonReferenceType();
1536
1537 Expr *CopyCtorArg =
1538 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001539 Constructor->getLocation(), ParamType,
1540 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001541
Anders Carlssonc7957502010-04-24 22:02:54 +00001542 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001543 QualType ArgTy =
1544 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1545 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001546
1547 CXXCastPath BasePath;
1548 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001549 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001550 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001551 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001552
Anders Carlssone5ef7402010-04-23 03:10:23 +00001553 InitializationKind InitKind
1554 = InitializationKind::CreateDirect(Constructor->getLocation(),
1555 SourceLocation(), SourceLocation());
1556 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1557 &CopyCtorArg, 1);
1558 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001559 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001560 break;
1561 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001562
Anders Carlssone5ef7402010-04-23 03:10:23 +00001563 case IIK_Move:
1564 assert(false && "Unhandled initializer kind!");
1565 }
John McCall9ae2f072010-08-23 23:25:46 +00001566
Douglas Gregor53c374f2010-12-07 00:41:46 +00001567 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001568 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001569 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001570
Anders Carlssondefefd22010-04-23 02:00:02 +00001571 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001572 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1573 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1574 SourceLocation()),
1575 BaseSpec->isVirtual(),
1576 SourceLocation(),
1577 BaseInit.takeAs<Expr>(),
1578 SourceLocation());
1579
Anders Carlssondefefd22010-04-23 02:00:02 +00001580 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001581}
1582
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001583static bool
1584BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001585 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001586 FieldDecl *Field,
1587 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001588 if (Field->isInvalidDecl())
1589 return true;
1590
Chandler Carruthf186b542010-06-29 23:50:44 +00001591 SourceLocation Loc = Constructor->getLocation();
1592
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001593 if (ImplicitInitKind == IIK_Copy) {
1594 ParmVarDecl *Param = Constructor->getParamDecl(0);
1595 QualType ParamType = Param->getType().getNonReferenceType();
1596
1597 Expr *MemberExprBase =
1598 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001599 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001600
1601 // Build a reference to this field within the parameter.
1602 CXXScopeSpec SS;
1603 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1604 Sema::LookupMemberName);
1605 MemberLookup.addDecl(Field, AS_public);
1606 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001607 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001608 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001609 ParamType, Loc,
1610 /*IsArrow=*/false,
1611 SS,
1612 /*FirstQualifierInScope=*/0,
1613 MemberLookup,
1614 /*TemplateArgs=*/0);
1615 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001616 return true;
1617
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001618 // When the field we are copying is an array, create index variables for
1619 // each dimension of the array. We use these index variables to subscript
1620 // the source array, and other clients (e.g., CodeGen) will perform the
1621 // necessary iteration with these index variables.
1622 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1623 QualType BaseType = Field->getType();
1624 QualType SizeType = SemaRef.Context.getSizeType();
1625 while (const ConstantArrayType *Array
1626 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1627 // Create the iteration variable for this array index.
1628 IdentifierInfo *IterationVarName = 0;
1629 {
1630 llvm::SmallString<8> Str;
1631 llvm::raw_svector_ostream OS(Str);
1632 OS << "__i" << IndexVariables.size();
1633 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1634 }
1635 VarDecl *IterationVar
1636 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1637 IterationVarName, SizeType,
1638 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001639 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001640 IndexVariables.push_back(IterationVar);
1641
1642 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001643 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00001644 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001645 assert(!IterationVarRef.isInvalid() &&
1646 "Reference to invented variable cannot fail!");
1647
1648 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001649 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001650 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001651 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001652 Loc);
1653 if (CopyCtorArg.isInvalid())
1654 return true;
1655
1656 BaseType = Array->getElementType();
1657 }
1658
1659 // Construct the entity that we will be initializing. For an array, this
1660 // will be first element in the array, which may require several levels
1661 // of array-subscript entities.
1662 llvm::SmallVector<InitializedEntity, 4> Entities;
1663 Entities.reserve(1 + IndexVariables.size());
1664 Entities.push_back(InitializedEntity::InitializeMember(Field));
1665 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1666 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1667 0,
1668 Entities.back()));
1669
1670 // Direct-initialize to use the copy constructor.
1671 InitializationKind InitKind =
1672 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1673
1674 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1675 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1676 &CopyCtorArgE, 1);
1677
John McCall60d7b3a2010-08-24 06:29:42 +00001678 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001679 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001680 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00001681 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001682 if (MemberInit.isInvalid())
1683 return true;
1684
1685 CXXMemberInit
1686 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1687 MemberInit.takeAs<Expr>(), Loc,
1688 IndexVariables.data(),
1689 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001690 return false;
1691 }
1692
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001693 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1694
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001695 QualType FieldBaseElementType =
1696 SemaRef.Context.getBaseElementType(Field->getType());
1697
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001698 if (FieldBaseElementType->isRecordType()) {
1699 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001700 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001701 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001702
1703 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001704 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001705 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001706
Douglas Gregor53c374f2010-12-07 00:41:46 +00001707 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001708 if (MemberInit.isInvalid())
1709 return true;
1710
1711 CXXMemberInit =
1712 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001713 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001714 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001715 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001716 return false;
1717 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001718
1719 if (FieldBaseElementType->isReferenceType()) {
1720 SemaRef.Diag(Constructor->getLocation(),
1721 diag::err_uninitialized_member_in_ctor)
1722 << (int)Constructor->isImplicit()
1723 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1724 << 0 << Field->getDeclName();
1725 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1726 return true;
1727 }
1728
1729 if (FieldBaseElementType.isConstQualified()) {
1730 SemaRef.Diag(Constructor->getLocation(),
1731 diag::err_uninitialized_member_in_ctor)
1732 << (int)Constructor->isImplicit()
1733 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1734 << 1 << Field->getDeclName();
1735 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1736 return true;
1737 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001738
1739 // Nothing to initialize.
1740 CXXMemberInit = 0;
1741 return false;
1742}
John McCallf1860e52010-05-20 23:23:51 +00001743
1744namespace {
1745struct BaseAndFieldInfo {
1746 Sema &S;
1747 CXXConstructorDecl *Ctor;
1748 bool AnyErrorsInInits;
1749 ImplicitInitializerKind IIK;
1750 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1751 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1752
1753 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1754 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1755 // FIXME: Handle implicit move constructors.
1756 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1757 IIK = IIK_Copy;
1758 else
1759 IIK = IIK_Default;
1760 }
1761};
1762}
1763
1764static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1765 FieldDecl *Top, FieldDecl *Field) {
1766
Chandler Carruthe861c602010-06-30 02:59:29 +00001767 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001768 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001769 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00001770 return false;
1771 }
1772
1773 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1774 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1775 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001776 CXXRecordDecl *FieldClassDecl
1777 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001778
1779 // Even though union members never have non-trivial default
1780 // constructions in C++03, we still build member initializers for aggregate
1781 // record types which can be union members, and C++0x allows non-trivial
1782 // default constructors for union members, so we ensure that only one
1783 // member is initialized for these.
1784 if (FieldClassDecl->isUnion()) {
1785 // First check for an explicit initializer for one field.
1786 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1787 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1788 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001789 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00001790
1791 // Once we've initialized a field of an anonymous union, the union
1792 // field in the class is also initialized, so exit immediately.
1793 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001794 } else if ((*FA)->isAnonymousStructOrUnion()) {
1795 if (CollectFieldInitializer(Info, Top, *FA))
1796 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001797 }
1798 }
1799
1800 // Fallthrough and construct a default initializer for the union as
1801 // a whole, which can call its default constructor if such a thing exists
1802 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1803 // behavior going forward with C++0x, when anonymous unions there are
1804 // finalized, we should revisit this.
1805 } else {
1806 // For structs, we simply descend through to initialize all members where
1807 // necessary.
1808 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1809 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1810 if (CollectFieldInitializer(Info, Top, *FA))
1811 return true;
1812 }
1813 }
John McCallf1860e52010-05-20 23:23:51 +00001814 }
1815
1816 // Don't try to build an implicit initializer if there were semantic
1817 // errors in any of the initializers (and therefore we might be
1818 // missing some that the user actually wrote).
1819 if (Info.AnyErrorsInInits)
1820 return false;
1821
1822 CXXBaseOrMemberInitializer *Init = 0;
1823 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1824 return true;
John McCallf1860e52010-05-20 23:23:51 +00001825
Francois Pichet00eb3f92010-12-04 09:14:42 +00001826 if (Init)
1827 Info.AllToInit.push_back(Init);
1828
John McCallf1860e52010-05-20 23:23:51 +00001829 return false;
1830}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001831
Eli Friedman80c30da2009-11-09 19:20:36 +00001832bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001833Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001834 CXXBaseOrMemberInitializer **Initializers,
1835 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001836 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001837 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001838 // Just store the initializers as written, they will be checked during
1839 // instantiation.
1840 if (NumInitializers > 0) {
1841 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1842 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1843 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1844 memcpy(baseOrMemberInitializers, Initializers,
1845 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1846 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1847 }
1848
1849 return false;
1850 }
1851
John McCallf1860e52010-05-20 23:23:51 +00001852 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001853
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001854 // We need to build the initializer AST according to order of construction
1855 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001856 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001857 if (!ClassDecl)
1858 return true;
1859
Eli Friedman80c30da2009-11-09 19:20:36 +00001860 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001862 for (unsigned i = 0; i < NumInitializers; i++) {
1863 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001864
1865 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001866 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001867 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00001868 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001869 }
1870
Anders Carlsson711f34a2010-04-21 19:52:01 +00001871 // Keep track of the direct virtual bases.
1872 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1873 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1874 E = ClassDecl->bases_end(); I != E; ++I) {
1875 if (I->isVirtual())
1876 DirectVBases.insert(I);
1877 }
1878
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001879 // Push virtual bases before others.
1880 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1881 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1882
1883 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001884 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1885 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001886 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001887 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001888 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001889 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001890 VBase, IsInheritedVirtualBase,
1891 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001892 HadError = true;
1893 continue;
1894 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001895
John McCallf1860e52010-05-20 23:23:51 +00001896 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001897 }
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
John McCallf1860e52010-05-20 23:23:51 +00001900 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001901 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1902 E = ClassDecl->bases_end(); Base != E; ++Base) {
1903 // Virtuals are in the virtual base list and already constructed.
1904 if (Base->isVirtual())
1905 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001907 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001908 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1909 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001910 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001911 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001912 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001913 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001914 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001915 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001916 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001917 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001918
John McCallf1860e52010-05-20 23:23:51 +00001919 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001920 }
1921 }
Mike Stump1eb44332009-09-09 15:08:12 +00001922
John McCallf1860e52010-05-20 23:23:51 +00001923 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001924 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001925 E = ClassDecl->field_end(); Field != E; ++Field) {
1926 if ((*Field)->getType()->isIncompleteArrayType()) {
1927 assert(ClassDecl->hasFlexibleArrayMember() &&
1928 "Incomplete array type is not valid");
1929 continue;
1930 }
John McCallf1860e52010-05-20 23:23:51 +00001931 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001932 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
John McCallf1860e52010-05-20 23:23:51 +00001935 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001936 if (NumInitializers > 0) {
1937 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1938 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1939 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001940 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001941 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001942 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001943
John McCallef027fe2010-03-16 21:39:52 +00001944 // Constructors implicitly reference the base and member
1945 // destructors.
1946 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1947 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001948 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001949
1950 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001951}
1952
Eli Friedman6347f422009-07-21 19:28:10 +00001953static void *GetKeyForTopLevelField(FieldDecl *Field) {
1954 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001955 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001956 if (RT->getDecl()->isAnonymousStructOrUnion())
1957 return static_cast<void *>(RT->getDecl());
1958 }
1959 return static_cast<void *>(Field);
1960}
1961
Anders Carlssonea356fb2010-04-02 05:42:15 +00001962static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1963 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001964}
1965
Anders Carlssonea356fb2010-04-02 05:42:15 +00001966static void *GetKeyForMember(ASTContext &Context,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001967 CXXBaseOrMemberInitializer *Member) {
1968 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001969 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001970
Eli Friedman6347f422009-07-21 19:28:10 +00001971 // For fields injected into the class via declaration of an anonymous union,
1972 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00001973 FieldDecl *Field = Member->getAnyMember();
1974
John McCall3c3ccdb2010-04-10 09:28:51 +00001975 // If the field is a member of an anonymous struct or union, our key
1976 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001977 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001978 if (RD->isAnonymousStructOrUnion()) {
1979 while (true) {
1980 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1981 if (Parent->isAnonymousStructOrUnion())
1982 RD = Parent;
1983 else
1984 break;
1985 }
1986
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001987 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001990 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001991}
1992
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001993static void
1994DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001995 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001996 CXXBaseOrMemberInitializer **Inits,
1997 unsigned NumInits) {
1998 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001999 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002001 // Don't check initializers order unless the warning is enabled at the
2002 // location of at least one initializer.
2003 bool ShouldCheckOrder = false;
2004 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2005 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2006 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2007 Init->getSourceLocation())
2008 != Diagnostic::Ignored) {
2009 ShouldCheckOrder = true;
2010 break;
2011 }
2012 }
2013 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002014 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002015
John McCalld6ca8da2010-04-10 07:37:23 +00002016 // Build the list of bases and members in the order that they'll
2017 // actually be initialized. The explicit initializers should be in
2018 // this same order but may be missing things.
2019 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Anders Carlsson071d6102010-04-02 03:38:04 +00002021 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2022
John McCalld6ca8da2010-04-10 07:37:23 +00002023 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002024 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002025 ClassDecl->vbases_begin(),
2026 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002027 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002028
John McCalld6ca8da2010-04-10 07:37:23 +00002029 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002030 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002031 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002032 if (Base->isVirtual())
2033 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002034 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
John McCalld6ca8da2010-04-10 07:37:23 +00002037 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002038 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2039 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002040 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCalld6ca8da2010-04-10 07:37:23 +00002042 unsigned NumIdealInits = IdealInitKeys.size();
2043 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002044
John McCalld6ca8da2010-04-10 07:37:23 +00002045 CXXBaseOrMemberInitializer *PrevInit = 0;
2046 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2047 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002048 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002049
2050 // Scan forward to try to find this initializer in the idealized
2051 // initializers list.
2052 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2053 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002054 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002055
2056 // If we didn't find this initializer, it must be because we
2057 // scanned past it on a previous iteration. That can only
2058 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002059 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002060 Sema::SemaDiagnosticBuilder D =
2061 SemaRef.Diag(PrevInit->getSourceLocation(),
2062 diag::warn_initializer_out_of_order);
2063
Francois Pichet00eb3f92010-12-04 09:14:42 +00002064 if (PrevInit->isAnyMemberInitializer())
2065 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002066 else
2067 D << 1 << PrevInit->getBaseClassInfo()->getType();
2068
Francois Pichet00eb3f92010-12-04 09:14:42 +00002069 if (Init->isAnyMemberInitializer())
2070 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002071 else
2072 D << 1 << Init->getBaseClassInfo()->getType();
2073
2074 // Move back to the initializer's location in the ideal list.
2075 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2076 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002077 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002078
2079 assert(IdealIndex != NumIdealInits &&
2080 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002081 }
John McCalld6ca8da2010-04-10 07:37:23 +00002082
2083 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002084 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002085}
2086
John McCall3c3ccdb2010-04-10 09:28:51 +00002087namespace {
2088bool CheckRedundantInit(Sema &S,
2089 CXXBaseOrMemberInitializer *Init,
2090 CXXBaseOrMemberInitializer *&PrevInit) {
2091 if (!PrevInit) {
2092 PrevInit = Init;
2093 return false;
2094 }
2095
2096 if (FieldDecl *Field = Init->getMember())
2097 S.Diag(Init->getSourceLocation(),
2098 diag::err_multiple_mem_initialization)
2099 << Field->getDeclName()
2100 << Init->getSourceRange();
2101 else {
2102 Type *BaseClass = Init->getBaseClass();
2103 assert(BaseClass && "neither field nor base");
2104 S.Diag(Init->getSourceLocation(),
2105 diag::err_multiple_base_initialization)
2106 << QualType(BaseClass, 0)
2107 << Init->getSourceRange();
2108 }
2109 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2110 << 0 << PrevInit->getSourceRange();
2111
2112 return true;
2113}
2114
2115typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2116typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2117
2118bool CheckRedundantUnionInit(Sema &S,
2119 CXXBaseOrMemberInitializer *Init,
2120 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002121 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002122 RecordDecl *Parent = Field->getParent();
2123 if (!Parent->isAnonymousStructOrUnion())
2124 return false;
2125
2126 NamedDecl *Child = Field;
2127 do {
2128 if (Parent->isUnion()) {
2129 UnionEntry &En = Unions[Parent];
2130 if (En.first && En.first != Child) {
2131 S.Diag(Init->getSourceLocation(),
2132 diag::err_multiple_mem_union_initialization)
2133 << Field->getDeclName()
2134 << Init->getSourceRange();
2135 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2136 << 0 << En.second->getSourceRange();
2137 return true;
2138 } else if (!En.first) {
2139 En.first = Child;
2140 En.second = Init;
2141 }
2142 }
2143
2144 Child = Parent;
2145 Parent = cast<RecordDecl>(Parent->getDeclContext());
2146 } while (Parent->isAnonymousStructOrUnion());
2147
2148 return false;
2149}
2150}
2151
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002152/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002153void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002154 SourceLocation ColonLoc,
2155 MemInitTy **meminits, unsigned NumMemInits,
2156 bool AnyErrors) {
2157 if (!ConstructorDecl)
2158 return;
2159
2160 AdjustDeclIfTemplate(ConstructorDecl);
2161
2162 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002163 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002164
2165 if (!Constructor) {
2166 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2167 return;
2168 }
2169
2170 CXXBaseOrMemberInitializer **MemInits =
2171 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002172
2173 // Mapping for the duplicate initializers check.
2174 // For member initializers, this is keyed with a FieldDecl*.
2175 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002176 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002177
2178 // Mapping for the inconsistent anonymous-union initializers check.
2179 RedundantUnionMap MemberUnions;
2180
Anders Carlssonea356fb2010-04-02 05:42:15 +00002181 bool HadError = false;
2182 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002183 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002184
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002185 // Set the source order index.
2186 Init->setSourceOrder(i);
2187
Francois Pichet00eb3f92010-12-04 09:14:42 +00002188 if (Init->isAnyMemberInitializer()) {
2189 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002190 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2191 CheckRedundantUnionInit(*this, Init, MemberUnions))
2192 HadError = true;
2193 } else {
2194 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2195 if (CheckRedundantInit(*this, Init, Members[Key]))
2196 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002197 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002198 }
2199
Anders Carlssonea356fb2010-04-02 05:42:15 +00002200 if (HadError)
2201 return;
2202
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002203 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002204
2205 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002206}
2207
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002208void
John McCallef027fe2010-03-16 21:39:52 +00002209Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2210 CXXRecordDecl *ClassDecl) {
2211 // Ignore dependent contexts.
2212 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002213 return;
John McCall58e6f342010-03-16 05:22:47 +00002214
2215 // FIXME: all the access-control diagnostics are positioned on the
2216 // field/base declaration. That's probably good; that said, the
2217 // user might reasonably want to know why the destructor is being
2218 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002219
Anders Carlsson9f853df2009-11-17 04:44:12 +00002220 // Non-static data members.
2221 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2222 E = ClassDecl->field_end(); I != E; ++I) {
2223 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002224 if (Field->isInvalidDecl())
2225 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002226 QualType FieldType = Context.getBaseElementType(Field->getType());
2227
2228 const RecordType* RT = FieldType->getAs<RecordType>();
2229 if (!RT)
2230 continue;
2231
2232 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2233 if (FieldClassDecl->hasTrivialDestructor())
2234 continue;
2235
Douglas Gregordb89f282010-07-01 22:47:18 +00002236 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002237 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002238 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002239 << Field->getDeclName()
2240 << FieldType);
2241
John McCallef027fe2010-03-16 21:39:52 +00002242 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002243 }
2244
John McCall58e6f342010-03-16 05:22:47 +00002245 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2246
Anders Carlsson9f853df2009-11-17 04:44:12 +00002247 // Bases.
2248 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2249 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002250 // Bases are always records in a well-formed non-dependent class.
2251 const RecordType *RT = Base->getType()->getAs<RecordType>();
2252
2253 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002254 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002255 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002256
2257 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002258 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002259 if (BaseClassDecl->hasTrivialDestructor())
2260 continue;
John McCall58e6f342010-03-16 05:22:47 +00002261
Douglas Gregordb89f282010-07-01 22:47:18 +00002262 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002263
2264 // FIXME: caret should be on the start of the class name
2265 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002266 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002267 << Base->getType()
2268 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002269
John McCallef027fe2010-03-16 21:39:52 +00002270 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002271 }
2272
2273 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002274 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2275 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002276
2277 // Bases are always records in a well-formed non-dependent class.
2278 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2279
2280 // Ignore direct virtual bases.
2281 if (DirectVirtualBases.count(RT))
2282 continue;
2283
Anders Carlsson9f853df2009-11-17 04:44:12 +00002284 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002285 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002286 if (BaseClassDecl->hasTrivialDestructor())
2287 continue;
John McCall58e6f342010-03-16 05:22:47 +00002288
Douglas Gregordb89f282010-07-01 22:47:18 +00002289 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002290 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002291 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002292 << VBase->getType());
2293
John McCallef027fe2010-03-16 21:39:52 +00002294 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002295 }
2296}
2297
John McCalld226f652010-08-21 09:40:31 +00002298void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002299 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002300 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Mike Stump1eb44332009-09-09 15:08:12 +00002302 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002303 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002304 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002305}
2306
Mike Stump1eb44332009-09-09 15:08:12 +00002307bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002308 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002309 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002310 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002311 else
John McCall94c3b562010-08-18 09:41:07 +00002312 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002313}
2314
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002315bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002316 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002317 if (!getLangOptions().CPlusPlus)
2318 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Anders Carlsson11f21a02009-03-23 19:10:31 +00002320 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002321 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002322
Ted Kremenek6217b802009-07-29 21:53:49 +00002323 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002324 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002325 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002326 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002328 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002329 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002330 }
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Ted Kremenek6217b802009-07-29 21:53:49 +00002332 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002333 if (!RT)
2334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002335
John McCall86ff3082010-02-04 22:26:26 +00002336 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002337
John McCall94c3b562010-08-18 09:41:07 +00002338 // We can't answer whether something is abstract until it has a
2339 // definition. If it's currently being defined, we'll walk back
2340 // over all the declarations when we have a full definition.
2341 const CXXRecordDecl *Def = RD->getDefinition();
2342 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002343 return false;
2344
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002345 if (!RD->isAbstract())
2346 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002348 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002349 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002350
John McCall94c3b562010-08-18 09:41:07 +00002351 return true;
2352}
2353
2354void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2355 // Check if we've already emitted the list of pure virtual functions
2356 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002357 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002358 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002360 CXXFinalOverriderMap FinalOverriders;
2361 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002363 // Keep a set of seen pure methods so we won't diagnose the same method
2364 // more than once.
2365 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2366
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002367 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2368 MEnd = FinalOverriders.end();
2369 M != MEnd;
2370 ++M) {
2371 for (OverridingMethods::iterator SO = M->second.begin(),
2372 SOEnd = M->second.end();
2373 SO != SOEnd; ++SO) {
2374 // C++ [class.abstract]p4:
2375 // A class is abstract if it contains or inherits at least one
2376 // pure virtual function for which the final overrider is pure
2377 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002379 //
2380 if (SO->second.size() != 1)
2381 continue;
2382
2383 if (!SO->second.front().Method->isPure())
2384 continue;
2385
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002386 if (!SeenPureMethods.insert(SO->second.front().Method))
2387 continue;
2388
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002389 Diag(SO->second.front().Method->getLocation(),
2390 diag::note_pure_virtual_function)
2391 << SO->second.front().Method->getDeclName();
2392 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002393 }
2394
2395 if (!PureVirtualClassDiagSet)
2396 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2397 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002398}
2399
Anders Carlsson8211eff2009-03-24 01:19:16 +00002400namespace {
John McCall94c3b562010-08-18 09:41:07 +00002401struct AbstractUsageInfo {
2402 Sema &S;
2403 CXXRecordDecl *Record;
2404 CanQualType AbstractType;
2405 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002406
John McCall94c3b562010-08-18 09:41:07 +00002407 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2408 : S(S), Record(Record),
2409 AbstractType(S.Context.getCanonicalType(
2410 S.Context.getTypeDeclType(Record))),
2411 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002412
John McCall94c3b562010-08-18 09:41:07 +00002413 void DiagnoseAbstractType() {
2414 if (Invalid) return;
2415 S.DiagnoseAbstractType(Record);
2416 Invalid = true;
2417 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002418
John McCall94c3b562010-08-18 09:41:07 +00002419 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2420};
2421
2422struct CheckAbstractUsage {
2423 AbstractUsageInfo &Info;
2424 const NamedDecl *Ctx;
2425
2426 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2427 : Info(Info), Ctx(Ctx) {}
2428
2429 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2430 switch (TL.getTypeLocClass()) {
2431#define ABSTRACT_TYPELOC(CLASS, PARENT)
2432#define TYPELOC(CLASS, PARENT) \
2433 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2434#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002435 }
John McCall94c3b562010-08-18 09:41:07 +00002436 }
Mike Stump1eb44332009-09-09 15:08:12 +00002437
John McCall94c3b562010-08-18 09:41:07 +00002438 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2439 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2440 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2441 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2442 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002443 }
John McCall94c3b562010-08-18 09:41:07 +00002444 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002445
John McCall94c3b562010-08-18 09:41:07 +00002446 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2447 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
John McCall94c3b562010-08-18 09:41:07 +00002450 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2451 // Visit the type parameters from a permissive context.
2452 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2453 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2454 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2455 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2456 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2457 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002458 }
John McCall94c3b562010-08-18 09:41:07 +00002459 }
Mike Stump1eb44332009-09-09 15:08:12 +00002460
John McCall94c3b562010-08-18 09:41:07 +00002461 // Visit pointee types from a permissive context.
2462#define CheckPolymorphic(Type) \
2463 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2464 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2465 }
2466 CheckPolymorphic(PointerTypeLoc)
2467 CheckPolymorphic(ReferenceTypeLoc)
2468 CheckPolymorphic(MemberPointerTypeLoc)
2469 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002470
John McCall94c3b562010-08-18 09:41:07 +00002471 /// Handle all the types we haven't given a more specific
2472 /// implementation for above.
2473 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2474 // Every other kind of type that we haven't called out already
2475 // that has an inner type is either (1) sugar or (2) contains that
2476 // inner type in some way as a subobject.
2477 if (TypeLoc Next = TL.getNextTypeLoc())
2478 return Visit(Next, Sel);
2479
2480 // If there's no inner type and we're in a permissive context,
2481 // don't diagnose.
2482 if (Sel == Sema::AbstractNone) return;
2483
2484 // Check whether the type matches the abstract type.
2485 QualType T = TL.getType();
2486 if (T->isArrayType()) {
2487 Sel = Sema::AbstractArrayType;
2488 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002489 }
John McCall94c3b562010-08-18 09:41:07 +00002490 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2491 if (CT != Info.AbstractType) return;
2492
2493 // It matched; do some magic.
2494 if (Sel == Sema::AbstractArrayType) {
2495 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2496 << T << TL.getSourceRange();
2497 } else {
2498 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2499 << Sel << T << TL.getSourceRange();
2500 }
2501 Info.DiagnoseAbstractType();
2502 }
2503};
2504
2505void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2506 Sema::AbstractDiagSelID Sel) {
2507 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2508}
2509
2510}
2511
2512/// Check for invalid uses of an abstract type in a method declaration.
2513static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2514 CXXMethodDecl *MD) {
2515 // No need to do the check on definitions, which require that
2516 // the return/param types be complete.
2517 if (MD->isThisDeclarationADefinition())
2518 return;
2519
2520 // For safety's sake, just ignore it if we don't have type source
2521 // information. This should never happen for non-implicit methods,
2522 // but...
2523 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2524 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2525}
2526
2527/// Check for invalid uses of an abstract type within a class definition.
2528static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2529 CXXRecordDecl *RD) {
2530 for (CXXRecordDecl::decl_iterator
2531 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2532 Decl *D = *I;
2533 if (D->isImplicit()) continue;
2534
2535 // Methods and method templates.
2536 if (isa<CXXMethodDecl>(D)) {
2537 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2538 } else if (isa<FunctionTemplateDecl>(D)) {
2539 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2540 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2541
2542 // Fields and static variables.
2543 } else if (isa<FieldDecl>(D)) {
2544 FieldDecl *FD = cast<FieldDecl>(D);
2545 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2546 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2547 } else if (isa<VarDecl>(D)) {
2548 VarDecl *VD = cast<VarDecl>(D);
2549 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2550 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2551
2552 // Nested classes and class templates.
2553 } else if (isa<CXXRecordDecl>(D)) {
2554 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2555 } else if (isa<ClassTemplateDecl>(D)) {
2556 CheckAbstractClassUsage(Info,
2557 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2558 }
2559 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002560}
2561
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002562/// \brief Perform semantic checks on a class definition that has been
2563/// completing, introducing implicitly-declared members, checking for
2564/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002565void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00002566 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002567 return;
2568
John McCall94c3b562010-08-18 09:41:07 +00002569 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2570 AbstractUsageInfo Info(*this, Record);
2571 CheckAbstractClassUsage(Info, Record);
2572 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002573
2574 // If this is not an aggregate type and has no user-declared constructor,
2575 // complain about any non-static data members of reference or const scalar
2576 // type, since they will never get initializers.
2577 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2578 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2579 bool Complained = false;
2580 for (RecordDecl::field_iterator F = Record->field_begin(),
2581 FEnd = Record->field_end();
2582 F != FEnd; ++F) {
2583 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002584 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002585 if (!Complained) {
2586 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2587 << Record->getTagKind() << Record;
2588 Complained = true;
2589 }
2590
2591 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2592 << F->getType()->isReferenceType()
2593 << F->getDeclName();
2594 }
2595 }
2596 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002597
2598 if (Record->isDynamicClass())
2599 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00002600
2601 if (Record->getIdentifier()) {
2602 // C++ [class.mem]p13:
2603 // If T is the name of a class, then each of the following shall have a
2604 // name different from T:
2605 // - every member of every anonymous union that is a member of class T.
2606 //
2607 // C++ [class.mem]p14:
2608 // In addition, if class T has a user-declared constructor (12.1), every
2609 // non-static data member of class T shall have a name different from T.
2610 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00002611 R.first != R.second; ++R.first) {
2612 NamedDecl *D = *R.first;
2613 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2614 isa<IndirectFieldDecl>(D)) {
2615 Diag(D->getLocation(), diag::err_member_name_of_class)
2616 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00002617 break;
2618 }
Francois Pichet87c2e122010-11-21 06:08:52 +00002619 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002620 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002621}
2622
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002623void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002624 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002625 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002626 SourceLocation RBrac,
2627 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002628 if (!TagDecl)
2629 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002630
Douglas Gregor42af25f2009-05-11 19:58:34 +00002631 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002632
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002633 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002634 // strict aliasing violation!
2635 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002636 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002637
Douglas Gregor23c94db2010-07-02 17:43:08 +00002638 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002639 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002640}
2641
Douglas Gregord92ec472010-07-01 05:10:53 +00002642namespace {
2643 /// \brief Helper class that collects exception specifications for
2644 /// implicitly-declared special member functions.
2645 class ImplicitExceptionSpecification {
2646 ASTContext &Context;
2647 bool AllowsAllExceptions;
2648 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2649 llvm::SmallVector<QualType, 4> Exceptions;
2650
2651 public:
2652 explicit ImplicitExceptionSpecification(ASTContext &Context)
2653 : Context(Context), AllowsAllExceptions(false) { }
2654
2655 /// \brief Whether the special member function should have any
2656 /// exception specification at all.
2657 bool hasExceptionSpecification() const {
2658 return !AllowsAllExceptions;
2659 }
2660
2661 /// \brief Whether the special member function should have a
2662 /// throw(...) exception specification (a Microsoft extension).
2663 bool hasAnyExceptionSpecification() const {
2664 return false;
2665 }
2666
2667 /// \brief The number of exceptions in the exception specification.
2668 unsigned size() const { return Exceptions.size(); }
2669
2670 /// \brief The set of exceptions in the exception specification.
2671 const QualType *data() const { return Exceptions.data(); }
2672
2673 /// \brief Note that
2674 void CalledDecl(CXXMethodDecl *Method) {
2675 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002676 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002677 return;
2678
2679 const FunctionProtoType *Proto
2680 = Method->getType()->getAs<FunctionProtoType>();
2681
2682 // If this function can throw any exceptions, make a note of that.
2683 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2684 AllowsAllExceptions = true;
2685 ExceptionsSeen.clear();
2686 Exceptions.clear();
2687 return;
2688 }
2689
2690 // Record the exceptions in this function's exception specification.
2691 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2692 EEnd = Proto->exception_end();
2693 E != EEnd; ++E)
2694 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2695 Exceptions.push_back(*E);
2696 }
2697 };
2698}
2699
2700
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002701/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2702/// special functions, such as the default constructor, copy
2703/// constructor, or destructor, to the given C++ class (C++
2704/// [special]p1). This routine can only be executed just before the
2705/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002706void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002707 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002708 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002709
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002710 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002711 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002712
Douglas Gregora376d102010-07-02 21:50:04 +00002713 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2714 ++ASTContext::NumImplicitCopyAssignmentOperators;
2715
2716 // If we have a dynamic class, then the copy assignment operator may be
2717 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2718 // it shows up in the right place in the vtable and that we diagnose
2719 // problems with the implicit exception specification.
2720 if (ClassDecl->isDynamicClass())
2721 DeclareImplicitCopyAssignment(ClassDecl);
2722 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002723
Douglas Gregor4923aa22010-07-02 20:37:36 +00002724 if (!ClassDecl->hasUserDeclaredDestructor()) {
2725 ++ASTContext::NumImplicitDestructors;
2726
2727 // If we have a dynamic class, then the destructor may be virtual, so we
2728 // have to declare the destructor immediately. This ensures that, e.g., it
2729 // shows up in the right place in the vtable and that we diagnose problems
2730 // with the implicit exception specification.
2731 if (ClassDecl->isDynamicClass())
2732 DeclareImplicitDestructor(ClassDecl);
2733 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002734}
2735
John McCalld226f652010-08-21 09:40:31 +00002736void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002737 if (!D)
2738 return;
2739
2740 TemplateParameterList *Params = 0;
2741 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2742 Params = Template->getTemplateParameters();
2743 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2744 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2745 Params = PartialSpec->getTemplateParameters();
2746 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002747 return;
2748
Douglas Gregor6569d682009-05-27 23:11:45 +00002749 for (TemplateParameterList::iterator Param = Params->begin(),
2750 ParamEnd = Params->end();
2751 Param != ParamEnd; ++Param) {
2752 NamedDecl *Named = cast<NamedDecl>(*Param);
2753 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002754 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002755 IdResolver.AddDecl(Named);
2756 }
2757 }
2758}
2759
John McCalld226f652010-08-21 09:40:31 +00002760void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002761 if (!RecordD) return;
2762 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002763 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002764 PushDeclContext(S, Record);
2765}
2766
John McCalld226f652010-08-21 09:40:31 +00002767void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002768 if (!RecordD) return;
2769 PopDeclContext();
2770}
2771
Douglas Gregor72b505b2008-12-16 21:30:33 +00002772/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2773/// parsing a top-level (non-nested) C++ class, and we are now
2774/// parsing those parts of the given Method declaration that could
2775/// not be parsed earlier (C++ [class.mem]p2), such as default
2776/// arguments. This action should enter the scope of the given
2777/// Method declaration as if we had just parsed the qualified method
2778/// name. However, it should not bring the parameters into scope;
2779/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002780void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002781}
2782
2783/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2784/// C++ method declaration. We're (re-)introducing the given
2785/// function parameter into scope for use in parsing later parts of
2786/// the method declaration. For example, we could see an
2787/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002788void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002789 if (!ParamD)
2790 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002791
John McCalld226f652010-08-21 09:40:31 +00002792 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002793
2794 // If this parameter has an unparsed default argument, clear it out
2795 // to make way for the parsed default argument.
2796 if (Param->hasUnparsedDefaultArg())
2797 Param->setDefaultArg(0);
2798
John McCalld226f652010-08-21 09:40:31 +00002799 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002800 if (Param->getDeclName())
2801 IdResolver.AddDecl(Param);
2802}
2803
2804/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2805/// processing the delayed method declaration for Method. The method
2806/// declaration is now considered finished. There may be a separate
2807/// ActOnStartOfFunctionDef action later (not necessarily
2808/// immediately!) for this method, if it was also defined inside the
2809/// class body.
John McCalld226f652010-08-21 09:40:31 +00002810void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002811 if (!MethodD)
2812 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002814 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
John McCalld226f652010-08-21 09:40:31 +00002816 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002817
2818 // Now that we have our default arguments, check the constructor
2819 // again. It could produce additional diagnostics or affect whether
2820 // the class has implicitly-declared destructors, among other
2821 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002822 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2823 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002824
2825 // Check the default arguments, which we may have added.
2826 if (!Method->isInvalidDecl())
2827 CheckCXXDefaultArguments(Method);
2828}
2829
Douglas Gregor42a552f2008-11-05 20:51:48 +00002830/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002831/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002832/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002833/// emit diagnostics and set the invalid bit to true. In any case, the type
2834/// will be updated to reflect a well-formed type for the constructor and
2835/// returned.
2836QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002837 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002838 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002839
2840 // C++ [class.ctor]p3:
2841 // A constructor shall not be virtual (10.3) or static (9.4). A
2842 // constructor can be invoked for a const, volatile or const
2843 // volatile object. A constructor shall not be declared const,
2844 // volatile, or const volatile (9.3.2).
2845 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002846 if (!D.isInvalidType())
2847 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2848 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2849 << SourceRange(D.getIdentifierLoc());
2850 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002851 }
John McCalld931b082010-08-26 03:08:43 +00002852 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002853 if (!D.isInvalidType())
2854 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2855 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2856 << SourceRange(D.getIdentifierLoc());
2857 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002858 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002859 }
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002861 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00002862 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002863 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002864 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2865 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002866 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002867 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2868 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002869 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002870 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2871 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00002872 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002873 }
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Douglas Gregor42a552f2008-11-05 20:51:48 +00002875 // Rebuild the function type "R" without any type qualifiers (in
2876 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002877 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002878 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00002879 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2880 return R;
2881
2882 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2883 EPI.TypeQuals = 0;
2884
Chris Lattner65401802009-04-25 08:28:21 +00002885 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00002886 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002887}
2888
Douglas Gregor72b505b2008-12-16 21:30:33 +00002889/// CheckConstructor - Checks a fully-formed constructor for
2890/// well-formedness, issuing any diagnostics required. Returns true if
2891/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002892void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002893 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002894 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2895 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002896 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002897
2898 // C++ [class.copy]p3:
2899 // A declaration of a constructor for a class X is ill-formed if
2900 // its first parameter is of type (optionally cv-qualified) X and
2901 // either there are no other parameters or else all other
2902 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002903 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002904 ((Constructor->getNumParams() == 1) ||
2905 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002906 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2907 Constructor->getTemplateSpecializationKind()
2908 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002909 QualType ParamType = Constructor->getParamDecl(0)->getType();
2910 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2911 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002912 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002913 const char *ConstRef
2914 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2915 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002916 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002917 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002918
2919 // FIXME: Rather that making the constructor invalid, we should endeavor
2920 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002921 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002922 }
2923 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002924}
2925
John McCall15442822010-08-04 01:04:25 +00002926/// CheckDestructor - Checks a fully-formed destructor definition for
2927/// well-formedness, issuing any diagnostics required. Returns true
2928/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002929bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002930 CXXRecordDecl *RD = Destructor->getParent();
2931
2932 if (Destructor->isVirtual()) {
2933 SourceLocation Loc;
2934
2935 if (!Destructor->isImplicit())
2936 Loc = Destructor->getLocation();
2937 else
2938 Loc = RD->getLocation();
2939
2940 // If we have a virtual destructor, look up the deallocation function
2941 FunctionDecl *OperatorDelete = 0;
2942 DeclarationName Name =
2943 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002944 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002945 return true;
John McCall5efd91a2010-07-03 18:33:00 +00002946
2947 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00002948
2949 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002950 }
Anders Carlsson37909802009-11-30 21:24:50 +00002951
2952 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002953}
2954
Mike Stump1eb44332009-09-09 15:08:12 +00002955static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002956FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2957 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2958 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00002959 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002960}
2961
Douglas Gregor42a552f2008-11-05 20:51:48 +00002962/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2963/// the well-formednes of the destructor declarator @p D with type @p
2964/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002965/// emit diagnostics and set the declarator to invalid. Even if this happens,
2966/// will be updated to reflect a well-formed type for the destructor and
2967/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00002968QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002969 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002970 // C++ [class.dtor]p1:
2971 // [...] A typedef-name that names a class is a class-name
2972 // (7.1.3); however, a typedef-name that names a class shall not
2973 // be used as the identifier in the declarator for a destructor
2974 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002975 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00002976 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00002977 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002978 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002979
2980 // C++ [class.dtor]p2:
2981 // A destructor is used to destroy objects of its class type. A
2982 // destructor takes no parameters, and no return type can be
2983 // specified for it (not even void). The address of a destructor
2984 // shall not be taken. A destructor shall not be static. A
2985 // destructor can be invoked for a const, volatile or const
2986 // volatile object. A destructor shall not be declared const,
2987 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00002988 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002989 if (!D.isInvalidType())
2990 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2991 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00002992 << SourceRange(D.getIdentifierLoc())
2993 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2994
John McCalld931b082010-08-26 03:08:43 +00002995 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002996 }
Chris Lattner65401802009-04-25 08:28:21 +00002997 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002998 // Destructors don't have return types, but the parser will
2999 // happily parse something like:
3000 //
3001 // class X {
3002 // float ~X();
3003 // };
3004 //
3005 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003006 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3007 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3008 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003011 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00003012 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003013 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003014 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3015 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003016 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003017 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3018 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003019 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003020 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3021 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003022 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003023 }
3024
3025 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003026 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003027 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3028
3029 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003030 FTI.freeArgs();
3031 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003032 }
3033
Mike Stump1eb44332009-09-09 15:08:12 +00003034 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003035 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003036 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003037 D.setInvalidType();
3038 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003039
3040 // Rebuild the function type "R" without any type qualifiers or
3041 // parameters (in case any of the errors above fired) and with
3042 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003043 // types.
John McCalle23cf432010-12-14 08:05:40 +00003044 if (!D.isInvalidType())
3045 return R;
3046
Douglas Gregord92ec472010-07-01 05:10:53 +00003047 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00003048 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3049 EPI.Variadic = false;
3050 EPI.TypeQuals = 0;
3051 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00003052}
3053
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003054/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3055/// well-formednes of the conversion function declarator @p D with
3056/// type @p R. If there are any errors in the declarator, this routine
3057/// will emit diagnostics and return true. Otherwise, it will return
3058/// false. Either way, the type @p R will be updated to reflect a
3059/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003060void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003061 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003062 // C++ [class.conv.fct]p1:
3063 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003064 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003065 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003066 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003067 if (!D.isInvalidType())
3068 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3069 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3070 << SourceRange(D.getIdentifierLoc());
3071 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003072 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003073 }
John McCalla3f81372010-04-13 00:04:31 +00003074
3075 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3076
Chris Lattner6e475012009-04-25 08:35:12 +00003077 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003078 // Conversion functions don't have return types, but the parser will
3079 // happily parse something like:
3080 //
3081 // class X {
3082 // float operator bool();
3083 // };
3084 //
3085 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003086 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3087 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3088 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003089 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003090 }
3091
John McCalla3f81372010-04-13 00:04:31 +00003092 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3093
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003094 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003095 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003096 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3097
3098 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003099 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003100 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003101 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003102 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003103 D.setInvalidType();
3104 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003105
John McCalla3f81372010-04-13 00:04:31 +00003106 // Diagnose "&operator bool()" and other such nonsense. This
3107 // is actually a gcc extension which we don't support.
3108 if (Proto->getResultType() != ConvType) {
3109 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3110 << Proto->getResultType();
3111 D.setInvalidType();
3112 ConvType = Proto->getResultType();
3113 }
3114
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003115 // C++ [class.conv.fct]p4:
3116 // The conversion-type-id shall not represent a function type nor
3117 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003118 if (ConvType->isArrayType()) {
3119 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3120 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003121 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003122 } else if (ConvType->isFunctionType()) {
3123 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3124 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003125 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003126 }
3127
3128 // Rebuild the function type "R" without any parameters (in case any
3129 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003130 // return type.
John McCalle23cf432010-12-14 08:05:40 +00003131 if (D.isInvalidType())
3132 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003133
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003134 // C++0x explicit conversion operators.
3135 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003136 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003137 diag::warn_explicit_conversion_functions)
3138 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003139}
3140
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003141/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3142/// the declaration of the given C++ conversion function. This routine
3143/// is responsible for recording the conversion function in the C++
3144/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003145Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003146 assert(Conversion && "Expected to receive a conversion function declaration");
3147
Douglas Gregor9d350972008-12-12 08:25:50 +00003148 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003149
3150 // Make sure we aren't redeclaring the conversion function.
3151 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003152
3153 // C++ [class.conv.fct]p1:
3154 // [...] A conversion function is never used to convert a
3155 // (possibly cv-qualified) object to the (possibly cv-qualified)
3156 // same object type (or a reference to it), to a (possibly
3157 // cv-qualified) base class of that type (or a reference to it),
3158 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003159 // FIXME: Suppress this warning if the conversion function ends up being a
3160 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003161 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003162 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003163 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003164 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003165 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3166 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003167 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003168 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003169 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3170 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003171 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003172 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003173 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003174 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003175 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003176 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003177 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003178 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003179 }
3180
Douglas Gregore80622f2010-09-29 04:25:11 +00003181 if (FunctionTemplateDecl *ConversionTemplate
3182 = Conversion->getDescribedFunctionTemplate())
3183 return ConversionTemplate;
3184
John McCalld226f652010-08-21 09:40:31 +00003185 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003186}
3187
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003188//===----------------------------------------------------------------------===//
3189// Namespace Handling
3190//===----------------------------------------------------------------------===//
3191
John McCallea318642010-08-26 09:15:37 +00003192
3193
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003194/// ActOnStartNamespaceDef - This is called at the start of a namespace
3195/// definition.
John McCalld226f652010-08-21 09:40:31 +00003196Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003197 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003198 SourceLocation IdentLoc,
3199 IdentifierInfo *II,
3200 SourceLocation LBrace,
3201 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003202 // anonymous namespace starts at its left brace
3203 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3204 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003205 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003206 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003207
3208 Scope *DeclRegionScope = NamespcScope->getParent();
3209
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003210 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3211
John McCall90f14502010-12-10 02:59:44 +00003212 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3213 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003214
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003215 if (II) {
3216 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00003217 // The identifier in an original-namespace-definition shall not
3218 // have been previously defined in the declarative region in
3219 // which the original-namespace-definition appears. The
3220 // identifier in an original-namespace-definition is the name of
3221 // the namespace. Subsequently in that declarative region, it is
3222 // treated as an original-namespace-name.
3223 //
3224 // Since namespace names are unique in their scope, and we don't
3225 // look through using directives, just
3226 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3227 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Douglas Gregor44b43212008-12-11 16:49:14 +00003229 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3230 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003231 if (Namespc->isInline() != OrigNS->isInline()) {
3232 // inline-ness must match
3233 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3234 << Namespc->isInline();
3235 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3236 Namespc->setInvalidDecl();
3237 // Recover by ignoring the new namespace's inline status.
3238 Namespc->setInline(OrigNS->isInline());
3239 }
3240
Douglas Gregor44b43212008-12-11 16:49:14 +00003241 // Attach this namespace decl to the chain of extended namespace
3242 // definitions.
3243 OrigNS->setNextNamespace(Namespc);
3244 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003245
Mike Stump1eb44332009-09-09 15:08:12 +00003246 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003247 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003248 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003249 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003250 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003251 } else if (PrevDecl) {
3252 // This is an invalid name redefinition.
3253 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3254 << Namespc->getDeclName();
3255 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3256 Namespc->setInvalidDecl();
3257 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003258 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003259 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003260 // This is the first "real" definition of the namespace "std", so update
3261 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003262 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003263 // We had already defined a dummy namespace "std". Link this new
3264 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003265 StdNS->setNextNamespace(Namespc);
3266 StdNS->setLocation(IdentLoc);
3267 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003268 }
3269
3270 // Make our StdNamespace cache point at the first real definition of the
3271 // "std" namespace.
3272 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003273 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003274
3275 PushOnScopeChains(Namespc, DeclRegionScope);
3276 } else {
John McCall9aeed322009-10-01 00:25:31 +00003277 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003278 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003279
3280 // Link the anonymous namespace into its parent.
3281 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003282 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003283 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3284 PrevDecl = TU->getAnonymousNamespace();
3285 TU->setAnonymousNamespace(Namespc);
3286 } else {
3287 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3288 PrevDecl = ND->getAnonymousNamespace();
3289 ND->setAnonymousNamespace(Namespc);
3290 }
3291
3292 // Link the anonymous namespace with its previous declaration.
3293 if (PrevDecl) {
3294 assert(PrevDecl->isAnonymousNamespace());
3295 assert(!PrevDecl->getNextNamespace());
3296 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3297 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003298
3299 if (Namespc->isInline() != PrevDecl->isInline()) {
3300 // inline-ness must match
3301 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3302 << Namespc->isInline();
3303 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3304 Namespc->setInvalidDecl();
3305 // Recover by ignoring the new namespace's inline status.
3306 Namespc->setInline(PrevDecl->isInline());
3307 }
John McCall5fdd7642009-12-16 02:06:49 +00003308 }
John McCall9aeed322009-10-01 00:25:31 +00003309
Douglas Gregora4181472010-03-24 00:46:35 +00003310 CurContext->addDecl(Namespc);
3311
John McCall9aeed322009-10-01 00:25:31 +00003312 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3313 // behaves as if it were replaced by
3314 // namespace unique { /* empty body */ }
3315 // using namespace unique;
3316 // namespace unique { namespace-body }
3317 // where all occurrences of 'unique' in a translation unit are
3318 // replaced by the same identifier and this identifier differs
3319 // from all other identifiers in the entire program.
3320
3321 // We just create the namespace with an empty name and then add an
3322 // implicit using declaration, just like the standard suggests.
3323 //
3324 // CodeGen enforces the "universally unique" aspect by giving all
3325 // declarations semantically contained within an anonymous
3326 // namespace internal linkage.
3327
John McCall5fdd7642009-12-16 02:06:49 +00003328 if (!PrevDecl) {
3329 UsingDirectiveDecl* UD
3330 = UsingDirectiveDecl::Create(Context, CurContext,
3331 /* 'using' */ LBrace,
3332 /* 'namespace' */ SourceLocation(),
3333 /* qualifier */ SourceRange(),
3334 /* NNS */ NULL,
3335 /* identifier */ SourceLocation(),
3336 Namespc,
3337 /* Ancestor */ CurContext);
3338 UD->setImplicit();
3339 CurContext->addDecl(UD);
3340 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003341 }
3342
3343 // Although we could have an invalid decl (i.e. the namespace name is a
3344 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003345 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3346 // for the namespace has the declarations that showed up in that particular
3347 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003348 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003349 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003350}
3351
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003352/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3353/// is a namespace alias, returns the namespace it points to.
3354static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3355 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3356 return AD->getNamespace();
3357 return dyn_cast_or_null<NamespaceDecl>(D);
3358}
3359
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003360/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3361/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003362void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003363 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3364 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3365 Namespc->setRBracLoc(RBrace);
3366 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003367 if (Namespc->hasAttr<VisibilityAttr>())
3368 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003369}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003370
John McCall384aff82010-08-25 07:42:41 +00003371CXXRecordDecl *Sema::getStdBadAlloc() const {
3372 return cast_or_null<CXXRecordDecl>(
3373 StdBadAlloc.get(Context.getExternalSource()));
3374}
3375
3376NamespaceDecl *Sema::getStdNamespace() const {
3377 return cast_or_null<NamespaceDecl>(
3378 StdNamespace.get(Context.getExternalSource()));
3379}
3380
Douglas Gregor66992202010-06-29 17:53:46 +00003381/// \brief Retrieve the special "std" namespace, which may require us to
3382/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003383NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003384 if (!StdNamespace) {
3385 // The "std" namespace has not yet been defined, so build one implicitly.
3386 StdNamespace = NamespaceDecl::Create(Context,
3387 Context.getTranslationUnitDecl(),
3388 SourceLocation(),
3389 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003390 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003391 }
3392
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003393 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003394}
3395
John McCalld226f652010-08-21 09:40:31 +00003396Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003397 SourceLocation UsingLoc,
3398 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003399 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003400 SourceLocation IdentLoc,
3401 IdentifierInfo *NamespcName,
3402 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003403 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3404 assert(NamespcName && "Invalid NamespcName.");
3405 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00003406
3407 // This can only happen along a recovery path.
3408 while (S->getFlags() & Scope::TemplateParamScope)
3409 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003410 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003411
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003412 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003413 NestedNameSpecifier *Qualifier = 0;
3414 if (SS.isSet())
3415 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3416
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003417 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003418 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3419 LookupParsedName(R, S, &SS);
3420 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003421 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003422
Douglas Gregor66992202010-06-29 17:53:46 +00003423 if (R.empty()) {
3424 // Allow "using namespace std;" or "using namespace ::std;" even if
3425 // "std" hasn't been defined yet, for GCC compatibility.
3426 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3427 NamespcName->isStr("std")) {
3428 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003429 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003430 R.resolveKind();
3431 }
3432 // Otherwise, attempt typo correction.
3433 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3434 CTC_NoKeywords, 0)) {
3435 if (R.getAsSingle<NamespaceDecl>() ||
3436 R.getAsSingle<NamespaceAliasDecl>()) {
3437 if (DeclContext *DC = computeDeclContext(SS, false))
3438 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3439 << NamespcName << DC << Corrected << SS.getRange()
3440 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3441 else
3442 Diag(IdentLoc, diag::err_using_directive_suggest)
3443 << NamespcName << Corrected
3444 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3445 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3446 << Corrected;
3447
3448 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003449 } else {
3450 R.clear();
3451 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003452 }
3453 }
3454 }
3455
John McCallf36e02d2009-10-09 21:13:30 +00003456 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003457 NamedDecl *Named = R.getFoundDecl();
3458 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3459 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003460 // C++ [namespace.udir]p1:
3461 // A using-directive specifies that the names in the nominated
3462 // namespace can be used in the scope in which the
3463 // using-directive appears after the using-directive. During
3464 // unqualified name lookup (3.4.1), the names appear as if they
3465 // were declared in the nearest enclosing namespace which
3466 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003467 // namespace. [Note: in this context, "contains" means "contains
3468 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003469
3470 // Find enclosing context containing both using-directive and
3471 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003472 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003473 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3474 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3475 CommonAncestor = CommonAncestor->getParent();
3476
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003477 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003478 SS.getRange(),
3479 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003480 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003481 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003482 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003483 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003484 }
3485
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003486 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00003487 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003488}
3489
3490void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3491 // If scope has associated entity, then using directive is at namespace
3492 // or translation unit scope. We add UsingDirectiveDecls, into
3493 // it's lookup structure.
3494 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003495 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003496 else
3497 // Otherwise it is block-sope. using-directives will affect lookup
3498 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003499 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003500}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003501
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003502
John McCalld226f652010-08-21 09:40:31 +00003503Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00003504 AccessSpecifier AS,
3505 bool HasUsingKeyword,
3506 SourceLocation UsingLoc,
3507 CXXScopeSpec &SS,
3508 UnqualifiedId &Name,
3509 AttributeList *AttrList,
3510 bool IsTypeName,
3511 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003512 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Douglas Gregor12c118a2009-11-04 16:30:06 +00003514 switch (Name.getKind()) {
3515 case UnqualifiedId::IK_Identifier:
3516 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003517 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003518 case UnqualifiedId::IK_ConversionFunctionId:
3519 break;
3520
3521 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003522 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003523 // C++0x inherited constructors.
3524 if (getLangOptions().CPlusPlus0x) break;
3525
Douglas Gregor12c118a2009-11-04 16:30:06 +00003526 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3527 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003528 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003529
3530 case UnqualifiedId::IK_DestructorName:
3531 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3532 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003533 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003534
3535 case UnqualifiedId::IK_TemplateId:
3536 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3537 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003538 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003539 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003540
3541 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3542 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003543 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003544 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003545
John McCall60fa3cf2009-12-11 02:10:03 +00003546 // Warn about using declarations.
3547 // TODO: store that the declaration was written without 'using' and
3548 // talk about access decls instead of using decls in the
3549 // diagnostics.
3550 if (!HasUsingKeyword) {
3551 UsingLoc = Name.getSourceRange().getBegin();
3552
3553 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003554 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003555 }
3556
Douglas Gregor56c04582010-12-16 00:46:58 +00003557 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3558 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3559 return 0;
3560
John McCall9488ea12009-11-17 05:59:44 +00003561 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003562 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003563 /* IsInstantiation */ false,
3564 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003565 if (UD)
3566 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003567
John McCalld226f652010-08-21 09:40:31 +00003568 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003569}
3570
Douglas Gregor09acc982010-07-07 23:08:52 +00003571/// \brief Determine whether a using declaration considers the given
3572/// declarations as "equivalent", e.g., if they are redeclarations of
3573/// the same entity or are both typedefs of the same type.
3574static bool
3575IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3576 bool &SuppressRedeclaration) {
3577 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3578 SuppressRedeclaration = false;
3579 return true;
3580 }
3581
3582 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3583 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3584 SuppressRedeclaration = true;
3585 return Context.hasSameType(TD1->getUnderlyingType(),
3586 TD2->getUnderlyingType());
3587 }
3588
3589 return false;
3590}
3591
3592
John McCall9f54ad42009-12-10 09:41:52 +00003593/// Determines whether to create a using shadow decl for a particular
3594/// decl, given the set of decls existing prior to this using lookup.
3595bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3596 const LookupResult &Previous) {
3597 // Diagnose finding a decl which is not from a base class of the
3598 // current class. We do this now because there are cases where this
3599 // function will silently decide not to build a shadow decl, which
3600 // will pre-empt further diagnostics.
3601 //
3602 // We don't need to do this in C++0x because we do the check once on
3603 // the qualifier.
3604 //
3605 // FIXME: diagnose the following if we care enough:
3606 // struct A { int foo; };
3607 // struct B : A { using A::foo; };
3608 // template <class T> struct C : A {};
3609 // template <class T> struct D : C<T> { using B::foo; } // <---
3610 // This is invalid (during instantiation) in C++03 because B::foo
3611 // resolves to the using decl in B, which is not a base class of D<T>.
3612 // We can't diagnose it immediately because C<T> is an unknown
3613 // specialization. The UsingShadowDecl in D<T> then points directly
3614 // to A::foo, which will look well-formed when we instantiate.
3615 // The right solution is to not collapse the shadow-decl chain.
3616 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3617 DeclContext *OrigDC = Orig->getDeclContext();
3618
3619 // Handle enums and anonymous structs.
3620 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3621 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3622 while (OrigRec->isAnonymousStructOrUnion())
3623 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3624
3625 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3626 if (OrigDC == CurContext) {
3627 Diag(Using->getLocation(),
3628 diag::err_using_decl_nested_name_specifier_is_current_class)
3629 << Using->getNestedNameRange();
3630 Diag(Orig->getLocation(), diag::note_using_decl_target);
3631 return true;
3632 }
3633
3634 Diag(Using->getNestedNameRange().getBegin(),
3635 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3636 << Using->getTargetNestedNameDecl()
3637 << cast<CXXRecordDecl>(CurContext)
3638 << Using->getNestedNameRange();
3639 Diag(Orig->getLocation(), diag::note_using_decl_target);
3640 return true;
3641 }
3642 }
3643
3644 if (Previous.empty()) return false;
3645
3646 NamedDecl *Target = Orig;
3647 if (isa<UsingShadowDecl>(Target))
3648 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3649
John McCalld7533ec2009-12-11 02:33:26 +00003650 // If the target happens to be one of the previous declarations, we
3651 // don't have a conflict.
3652 //
3653 // FIXME: but we might be increasing its access, in which case we
3654 // should redeclare it.
3655 NamedDecl *NonTag = 0, *Tag = 0;
3656 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3657 I != E; ++I) {
3658 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003659 bool Result;
3660 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3661 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003662
3663 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3664 }
3665
John McCall9f54ad42009-12-10 09:41:52 +00003666 if (Target->isFunctionOrFunctionTemplate()) {
3667 FunctionDecl *FD;
3668 if (isa<FunctionTemplateDecl>(Target))
3669 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3670 else
3671 FD = cast<FunctionDecl>(Target);
3672
3673 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003674 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003675 case Ovl_Overload:
3676 return false;
3677
3678 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003679 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003680 break;
3681
3682 // We found a decl with the exact signature.
3683 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003684 // If we're in a record, we want to hide the target, so we
3685 // return true (without a diagnostic) to tell the caller not to
3686 // build a shadow decl.
3687 if (CurContext->isRecord())
3688 return true;
3689
3690 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003691 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003692 break;
3693 }
3694
3695 Diag(Target->getLocation(), diag::note_using_decl_target);
3696 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3697 return true;
3698 }
3699
3700 // Target is not a function.
3701
John McCall9f54ad42009-12-10 09:41:52 +00003702 if (isa<TagDecl>(Target)) {
3703 // No conflict between a tag and a non-tag.
3704 if (!Tag) return false;
3705
John McCall41ce66f2009-12-10 19:51:03 +00003706 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003707 Diag(Target->getLocation(), diag::note_using_decl_target);
3708 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3709 return true;
3710 }
3711
3712 // No conflict between a tag and a non-tag.
3713 if (!NonTag) return false;
3714
John McCall41ce66f2009-12-10 19:51:03 +00003715 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003716 Diag(Target->getLocation(), diag::note_using_decl_target);
3717 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3718 return true;
3719}
3720
John McCall9488ea12009-11-17 05:59:44 +00003721/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003722UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003723 UsingDecl *UD,
3724 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003725
3726 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003727 NamedDecl *Target = Orig;
3728 if (isa<UsingShadowDecl>(Target)) {
3729 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3730 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003731 }
3732
3733 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003734 = UsingShadowDecl::Create(Context, CurContext,
3735 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003736 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00003737
3738 Shadow->setAccess(UD->getAccess());
3739 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3740 Shadow->setInvalidDecl();
3741
John McCall9488ea12009-11-17 05:59:44 +00003742 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003743 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003744 else
John McCall604e7f12009-12-08 07:46:18 +00003745 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00003746
John McCall604e7f12009-12-08 07:46:18 +00003747
John McCall9f54ad42009-12-10 09:41:52 +00003748 return Shadow;
3749}
John McCall604e7f12009-12-08 07:46:18 +00003750
John McCall9f54ad42009-12-10 09:41:52 +00003751/// Hides a using shadow declaration. This is required by the current
3752/// using-decl implementation when a resolvable using declaration in a
3753/// class is followed by a declaration which would hide or override
3754/// one or more of the using decl's targets; for example:
3755///
3756/// struct Base { void foo(int); };
3757/// struct Derived : Base {
3758/// using Base::foo;
3759/// void foo(int);
3760/// };
3761///
3762/// The governing language is C++03 [namespace.udecl]p12:
3763///
3764/// When a using-declaration brings names from a base class into a
3765/// derived class scope, member functions in the derived class
3766/// override and/or hide member functions with the same name and
3767/// parameter types in a base class (rather than conflicting).
3768///
3769/// There are two ways to implement this:
3770/// (1) optimistically create shadow decls when they're not hidden
3771/// by existing declarations, or
3772/// (2) don't create any shadow decls (or at least don't make them
3773/// visible) until we've fully parsed/instantiated the class.
3774/// The problem with (1) is that we might have to retroactively remove
3775/// a shadow decl, which requires several O(n) operations because the
3776/// decl structures are (very reasonably) not designed for removal.
3777/// (2) avoids this but is very fiddly and phase-dependent.
3778void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003779 if (Shadow->getDeclName().getNameKind() ==
3780 DeclarationName::CXXConversionFunctionName)
3781 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3782
John McCall9f54ad42009-12-10 09:41:52 +00003783 // Remove it from the DeclContext...
3784 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003785
John McCall9f54ad42009-12-10 09:41:52 +00003786 // ...and the scope, if applicable...
3787 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003788 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003789 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003790 }
3791
John McCall9f54ad42009-12-10 09:41:52 +00003792 // ...and the using decl.
3793 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3794
3795 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003796 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003797}
3798
John McCall7ba107a2009-11-18 02:36:19 +00003799/// Builds a using declaration.
3800///
3801/// \param IsInstantiation - Whether this call arises from an
3802/// instantiation of an unresolved using declaration. We treat
3803/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003804NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3805 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003806 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003807 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003808 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003809 bool IsInstantiation,
3810 bool IsTypeName,
3811 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003812 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003813 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003814 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003815
Anders Carlsson550b14b2009-08-28 05:49:21 +00003816 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003818 if (SS.isEmpty()) {
3819 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003820 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003821 }
Mike Stump1eb44332009-09-09 15:08:12 +00003822
John McCall9f54ad42009-12-10 09:41:52 +00003823 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003824 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003825 ForRedeclaration);
3826 Previous.setHideTags(false);
3827 if (S) {
3828 LookupName(Previous, S);
3829
3830 // It is really dumb that we have to do this.
3831 LookupResult::Filter F = Previous.makeFilter();
3832 while (F.hasNext()) {
3833 NamedDecl *D = F.next();
3834 if (!isDeclInScope(D, CurContext, S))
3835 F.erase();
3836 }
3837 F.done();
3838 } else {
3839 assert(IsInstantiation && "no scope in non-instantiation");
3840 assert(CurContext->isRecord() && "scope not record in instantiation");
3841 LookupQualifiedName(Previous, CurContext);
3842 }
3843
Mike Stump1eb44332009-09-09 15:08:12 +00003844 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003845 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3846
John McCall9f54ad42009-12-10 09:41:52 +00003847 // Check for invalid redeclarations.
3848 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3849 return 0;
3850
3851 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003852 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3853 return 0;
3854
John McCallaf8e6ed2009-11-12 03:15:40 +00003855 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003856 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003857 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003858 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003859 // FIXME: not all declaration name kinds are legal here
3860 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3861 UsingLoc, TypenameLoc,
3862 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003863 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003864 } else {
3865 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003866 UsingLoc, SS.getRange(),
3867 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003868 }
John McCalled976492009-12-04 22:46:56 +00003869 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003870 D = UsingDecl::Create(Context, CurContext,
3871 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003872 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003873 }
John McCalled976492009-12-04 22:46:56 +00003874 D->setAccess(AS);
3875 CurContext->addDecl(D);
3876
3877 if (!LookupContext) return D;
3878 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003879
John McCall77bb1aa2010-05-01 00:40:08 +00003880 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003881 UD->setInvalidDecl();
3882 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003883 }
3884
John McCall604e7f12009-12-08 07:46:18 +00003885 // Look up the target name.
3886
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003887 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003888
John McCall604e7f12009-12-08 07:46:18 +00003889 // Unlike most lookups, we don't always want to hide tag
3890 // declarations: tag names are visible through the using declaration
3891 // even if hidden by ordinary names, *except* in a dependent context
3892 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003893 if (!IsInstantiation)
3894 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003895
John McCalla24dc2e2009-11-17 02:14:36 +00003896 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003897
John McCallf36e02d2009-10-09 21:13:30 +00003898 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003899 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003900 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003901 UD->setInvalidDecl();
3902 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003903 }
3904
John McCalled976492009-12-04 22:46:56 +00003905 if (R.isAmbiguous()) {
3906 UD->setInvalidDecl();
3907 return UD;
3908 }
Mike Stump1eb44332009-09-09 15:08:12 +00003909
John McCall7ba107a2009-11-18 02:36:19 +00003910 if (IsTypeName) {
3911 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003912 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003913 Diag(IdentLoc, diag::err_using_typename_non_type);
3914 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3915 Diag((*I)->getUnderlyingDecl()->getLocation(),
3916 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003917 UD->setInvalidDecl();
3918 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003919 }
3920 } else {
3921 // If we asked for a non-typename and we got a type, error out,
3922 // but only if this is an instantiation of an unresolved using
3923 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003924 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003925 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3926 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003927 UD->setInvalidDecl();
3928 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003929 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003930 }
3931
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003932 // C++0x N2914 [namespace.udecl]p6:
3933 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003934 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003935 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3936 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003937 UD->setInvalidDecl();
3938 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003939 }
Mike Stump1eb44332009-09-09 15:08:12 +00003940
John McCall9f54ad42009-12-10 09:41:52 +00003941 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3942 if (!CheckUsingShadowDecl(UD, *I, Previous))
3943 BuildUsingShadowDecl(S, UD, *I);
3944 }
John McCall9488ea12009-11-17 05:59:44 +00003945
3946 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003947}
3948
John McCall9f54ad42009-12-10 09:41:52 +00003949/// Checks that the given using declaration is not an invalid
3950/// redeclaration. Note that this is checking only for the using decl
3951/// itself, not for any ill-formedness among the UsingShadowDecls.
3952bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3953 bool isTypeName,
3954 const CXXScopeSpec &SS,
3955 SourceLocation NameLoc,
3956 const LookupResult &Prev) {
3957 // C++03 [namespace.udecl]p8:
3958 // C++0x [namespace.udecl]p10:
3959 // A using-declaration is a declaration and can therefore be used
3960 // repeatedly where (and only where) multiple declarations are
3961 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00003962 //
John McCall8a726212010-11-29 18:01:58 +00003963 // That's in non-member contexts.
3964 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00003965 return false;
3966
3967 NestedNameSpecifier *Qual
3968 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3969
3970 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3971 NamedDecl *D = *I;
3972
3973 bool DTypename;
3974 NestedNameSpecifier *DQual;
3975 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3976 DTypename = UD->isTypeName();
3977 DQual = UD->getTargetNestedNameDecl();
3978 } else if (UnresolvedUsingValueDecl *UD
3979 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3980 DTypename = false;
3981 DQual = UD->getTargetNestedNameSpecifier();
3982 } else if (UnresolvedUsingTypenameDecl *UD
3983 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3984 DTypename = true;
3985 DQual = UD->getTargetNestedNameSpecifier();
3986 } else continue;
3987
3988 // using decls differ if one says 'typename' and the other doesn't.
3989 // FIXME: non-dependent using decls?
3990 if (isTypeName != DTypename) continue;
3991
3992 // using decls differ if they name different scopes (but note that
3993 // template instantiation can cause this check to trigger when it
3994 // didn't before instantiation).
3995 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3996 Context.getCanonicalNestedNameSpecifier(DQual))
3997 continue;
3998
3999 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004000 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004001 return true;
4002 }
4003
4004 return false;
4005}
4006
John McCall604e7f12009-12-08 07:46:18 +00004007
John McCalled976492009-12-04 22:46:56 +00004008/// Checks that the given nested-name qualifier used in a using decl
4009/// in the current context is appropriately related to the current
4010/// scope. If an error is found, diagnoses it and returns true.
4011bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4012 const CXXScopeSpec &SS,
4013 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004014 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004015
John McCall604e7f12009-12-08 07:46:18 +00004016 if (!CurContext->isRecord()) {
4017 // C++03 [namespace.udecl]p3:
4018 // C++0x [namespace.udecl]p8:
4019 // A using-declaration for a class member shall be a member-declaration.
4020
4021 // If we weren't able to compute a valid scope, it must be a
4022 // dependent class scope.
4023 if (!NamedContext || NamedContext->isRecord()) {
4024 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4025 << SS.getRange();
4026 return true;
4027 }
4028
4029 // Otherwise, everything is known to be fine.
4030 return false;
4031 }
4032
4033 // The current scope is a record.
4034
4035 // If the named context is dependent, we can't decide much.
4036 if (!NamedContext) {
4037 // FIXME: in C++0x, we can diagnose if we can prove that the
4038 // nested-name-specifier does not refer to a base class, which is
4039 // still possible in some cases.
4040
4041 // Otherwise we have to conservatively report that things might be
4042 // okay.
4043 return false;
4044 }
4045
4046 if (!NamedContext->isRecord()) {
4047 // Ideally this would point at the last name in the specifier,
4048 // but we don't have that level of source info.
4049 Diag(SS.getRange().getBegin(),
4050 diag::err_using_decl_nested_name_specifier_is_not_class)
4051 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4052 return true;
4053 }
4054
4055 if (getLangOptions().CPlusPlus0x) {
4056 // C++0x [namespace.udecl]p3:
4057 // In a using-declaration used as a member-declaration, the
4058 // nested-name-specifier shall name a base class of the class
4059 // being defined.
4060
4061 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4062 cast<CXXRecordDecl>(NamedContext))) {
4063 if (CurContext == NamedContext) {
4064 Diag(NameLoc,
4065 diag::err_using_decl_nested_name_specifier_is_current_class)
4066 << SS.getRange();
4067 return true;
4068 }
4069
4070 Diag(SS.getRange().getBegin(),
4071 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4072 << (NestedNameSpecifier*) SS.getScopeRep()
4073 << cast<CXXRecordDecl>(CurContext)
4074 << SS.getRange();
4075 return true;
4076 }
4077
4078 return false;
4079 }
4080
4081 // C++03 [namespace.udecl]p4:
4082 // A using-declaration used as a member-declaration shall refer
4083 // to a member of a base class of the class being defined [etc.].
4084
4085 // Salient point: SS doesn't have to name a base class as long as
4086 // lookup only finds members from base classes. Therefore we can
4087 // diagnose here only if we can prove that that can't happen,
4088 // i.e. if the class hierarchies provably don't intersect.
4089
4090 // TODO: it would be nice if "definitely valid" results were cached
4091 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4092 // need to be repeated.
4093
4094 struct UserData {
4095 llvm::DenseSet<const CXXRecordDecl*> Bases;
4096
4097 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4098 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4099 Data->Bases.insert(Base);
4100 return true;
4101 }
4102
4103 bool hasDependentBases(const CXXRecordDecl *Class) {
4104 return !Class->forallBases(collect, this);
4105 }
4106
4107 /// Returns true if the base is dependent or is one of the
4108 /// accumulated base classes.
4109 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4110 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4111 return !Data->Bases.count(Base);
4112 }
4113
4114 bool mightShareBases(const CXXRecordDecl *Class) {
4115 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4116 }
4117 };
4118
4119 UserData Data;
4120
4121 // Returns false if we find a dependent base.
4122 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4123 return false;
4124
4125 // Returns false if the class has a dependent base or if it or one
4126 // of its bases is present in the base set of the current context.
4127 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4128 return false;
4129
4130 Diag(SS.getRange().getBegin(),
4131 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4132 << (NestedNameSpecifier*) SS.getScopeRep()
4133 << cast<CXXRecordDecl>(CurContext)
4134 << SS.getRange();
4135
4136 return true;
John McCalled976492009-12-04 22:46:56 +00004137}
4138
John McCalld226f652010-08-21 09:40:31 +00004139Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004140 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004141 SourceLocation AliasLoc,
4142 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004143 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004144 SourceLocation IdentLoc,
4145 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Anders Carlsson81c85c42009-03-28 23:53:49 +00004147 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004148 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4149 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004150
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004151 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004152 NamedDecl *PrevDecl
4153 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4154 ForRedeclaration);
4155 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4156 PrevDecl = 0;
4157
4158 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004159 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004160 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004161 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004162 // FIXME: At some point, we'll want to create the (redundant)
4163 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004164 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004165 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004166 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004167 }
Mike Stump1eb44332009-09-09 15:08:12 +00004168
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004169 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4170 diag::err_redefinition_different_kind;
4171 Diag(AliasLoc, DiagID) << Alias;
4172 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004173 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004174 }
4175
John McCalla24dc2e2009-11-17 02:14:36 +00004176 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004177 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004178
John McCallf36e02d2009-10-09 21:13:30 +00004179 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004180 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4181 CTC_NoKeywords, 0)) {
4182 if (R.getAsSingle<NamespaceDecl>() ||
4183 R.getAsSingle<NamespaceAliasDecl>()) {
4184 if (DeclContext *DC = computeDeclContext(SS, false))
4185 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4186 << Ident << DC << Corrected << SS.getRange()
4187 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4188 else
4189 Diag(IdentLoc, diag::err_using_directive_suggest)
4190 << Ident << Corrected
4191 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4192
4193 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4194 << Corrected;
4195
4196 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004197 } else {
4198 R.clear();
4199 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004200 }
4201 }
4202
4203 if (R.empty()) {
4204 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004205 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004206 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004207 }
Mike Stump1eb44332009-09-09 15:08:12 +00004208
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004209 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004210 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4211 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004212 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004213 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004214
John McCall3dbd3d52010-02-16 06:53:13 +00004215 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004216 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004217}
4218
Douglas Gregor39957dc2010-05-01 15:04:51 +00004219namespace {
4220 /// \brief Scoped object used to handle the state changes required in Sema
4221 /// to implicitly define the body of a C++ member function;
4222 class ImplicitlyDefinedFunctionScope {
4223 Sema &S;
4224 DeclContext *PreviousContext;
4225
4226 public:
4227 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4228 : S(S), PreviousContext(S.CurContext)
4229 {
4230 S.CurContext = Method;
4231 S.PushFunctionScope();
4232 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4233 }
4234
4235 ~ImplicitlyDefinedFunctionScope() {
4236 S.PopExpressionEvaluationContext();
4237 S.PopFunctionOrBlockScope();
4238 S.CurContext = PreviousContext;
4239 }
4240 };
4241}
4242
Sebastian Redl751025d2010-09-13 22:02:47 +00004243static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4244 CXXRecordDecl *D) {
4245 ASTContext &Context = Self.Context;
4246 QualType ClassType = Context.getTypeDeclType(D);
4247 DeclarationName ConstructorName
4248 = Context.DeclarationNames.getCXXConstructorName(
4249 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4250
4251 DeclContext::lookup_const_iterator Con, ConEnd;
4252 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4253 Con != ConEnd; ++Con) {
4254 // FIXME: In C++0x, a constructor template can be a default constructor.
4255 if (isa<FunctionTemplateDecl>(*Con))
4256 continue;
4257
4258 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4259 if (Constructor->isDefaultConstructor())
4260 return Constructor;
4261 }
4262 return 0;
4263}
4264
Douglas Gregor23c94db2010-07-02 17:43:08 +00004265CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4266 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004267 // C++ [class.ctor]p5:
4268 // A default constructor for a class X is a constructor of class X
4269 // that can be called without an argument. If there is no
4270 // user-declared constructor for class X, a default constructor is
4271 // implicitly declared. An implicitly-declared default constructor
4272 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004273 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4274 "Should not build implicit default constructor!");
4275
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004276 // C++ [except.spec]p14:
4277 // An implicitly declared special member function (Clause 12) shall have an
4278 // exception-specification. [...]
4279 ImplicitExceptionSpecification ExceptSpec(Context);
4280
4281 // Direct base-class destructors.
4282 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4283 BEnd = ClassDecl->bases_end();
4284 B != BEnd; ++B) {
4285 if (B->isVirtual()) // Handled below.
4286 continue;
4287
Douglas Gregor18274032010-07-03 00:47:00 +00004288 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4289 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4290 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4291 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004292 else if (CXXConstructorDecl *Constructor
4293 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004294 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004295 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004296 }
4297
4298 // Virtual base-class destructors.
4299 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4300 BEnd = ClassDecl->vbases_end();
4301 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004302 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4303 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4304 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4305 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4306 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004307 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004308 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004309 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004310 }
4311
4312 // Field destructors.
4313 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4314 FEnd = ClassDecl->field_end();
4315 F != FEnd; ++F) {
4316 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004317 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4318 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4319 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4320 ExceptSpec.CalledDecl(
4321 DeclareImplicitDefaultConstructor(FieldClassDecl));
4322 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004323 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004324 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004325 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004326 }
John McCalle23cf432010-12-14 08:05:40 +00004327
4328 FunctionProtoType::ExtProtoInfo EPI;
4329 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4330 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4331 EPI.NumExceptions = ExceptSpec.size();
4332 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004333
4334 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004335 CanQualType ClassType
4336 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4337 DeclarationName Name
4338 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004339 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004340 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004341 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004342 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004343 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004344 /*TInfo=*/0,
4345 /*isExplicit=*/false,
4346 /*isInline=*/true,
4347 /*isImplicitlyDeclared=*/true);
4348 DefaultCon->setAccess(AS_public);
4349 DefaultCon->setImplicit();
4350 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004351
4352 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004353 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4354
Douglas Gregor23c94db2010-07-02 17:43:08 +00004355 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004356 PushOnScopeChains(DefaultCon, S, false);
4357 ClassDecl->addDecl(DefaultCon);
4358
Douglas Gregor32df23e2010-07-01 22:02:46 +00004359 return DefaultCon;
4360}
4361
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004362void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4363 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004364 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004365 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004366 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004367
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004368 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004369 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004370
Douglas Gregor39957dc2010-05-01 15:04:51 +00004371 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004372 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004373 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4374 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004375 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004376 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004377 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004378 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004379 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004380
4381 SourceLocation Loc = Constructor->getLocation();
4382 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4383
4384 Constructor->setUsed();
4385 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004386}
4387
Douglas Gregor23c94db2010-07-02 17:43:08 +00004388CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004389 // C++ [class.dtor]p2:
4390 // If a class has no user-declared destructor, a destructor is
4391 // declared implicitly. An implicitly-declared destructor is an
4392 // inline public member of its class.
4393
4394 // C++ [except.spec]p14:
4395 // An implicitly declared special member function (Clause 12) shall have
4396 // an exception-specification.
4397 ImplicitExceptionSpecification ExceptSpec(Context);
4398
4399 // Direct base-class destructors.
4400 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4401 BEnd = ClassDecl->bases_end();
4402 B != BEnd; ++B) {
4403 if (B->isVirtual()) // Handled below.
4404 continue;
4405
4406 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4407 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004408 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004409 }
4410
4411 // Virtual base-class destructors.
4412 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4413 BEnd = ClassDecl->vbases_end();
4414 B != BEnd; ++B) {
4415 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4416 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004417 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004418 }
4419
4420 // Field destructors.
4421 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4422 FEnd = ClassDecl->field_end();
4423 F != FEnd; ++F) {
4424 if (const RecordType *RecordTy
4425 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4426 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004427 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004428 }
4429
Douglas Gregor4923aa22010-07-02 20:37:36 +00004430 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004431 FunctionProtoType::ExtProtoInfo EPI;
4432 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4433 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4434 EPI.NumExceptions = ExceptSpec.size();
4435 EPI.Exceptions = ExceptSpec.data();
4436 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004437
4438 CanQualType ClassType
4439 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4440 DeclarationName Name
4441 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004442 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004443 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004444 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004445 /*isInline=*/true,
4446 /*isImplicitlyDeclared=*/true);
4447 Destructor->setAccess(AS_public);
4448 Destructor->setImplicit();
4449 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004450
4451 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004452 ++ASTContext::NumImplicitDestructorsDeclared;
4453
4454 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004455 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004456 PushOnScopeChains(Destructor, S, false);
4457 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004458
4459 // This could be uniqued if it ever proves significant.
4460 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4461
4462 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004463
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004464 return Destructor;
4465}
4466
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004467void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004468 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004469 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004470 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004471 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004472 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004473
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004474 if (Destructor->isInvalidDecl())
4475 return;
4476
Douglas Gregor39957dc2010-05-01 15:04:51 +00004477 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004478
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004479 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004480 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4481 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004483 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004484 Diag(CurrentLocation, diag::note_member_synthesized_at)
4485 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4486
4487 Destructor->setInvalidDecl();
4488 return;
4489 }
4490
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004491 SourceLocation Loc = Destructor->getLocation();
4492 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4493
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004494 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004495 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004496}
4497
Douglas Gregor06a9f362010-05-01 20:49:11 +00004498/// \brief Builds a statement that copies the given entity from \p From to
4499/// \c To.
4500///
4501/// This routine is used to copy the members of a class with an
4502/// implicitly-declared copy assignment operator. When the entities being
4503/// copied are arrays, this routine builds for loops to copy them.
4504///
4505/// \param S The Sema object used for type-checking.
4506///
4507/// \param Loc The location where the implicit copy is being generated.
4508///
4509/// \param T The type of the expressions being copied. Both expressions must
4510/// have this type.
4511///
4512/// \param To The expression we are copying to.
4513///
4514/// \param From The expression we are copying from.
4515///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004516/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4517/// Otherwise, it's a non-static member subobject.
4518///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004519/// \param Depth Internal parameter recording the depth of the recursion.
4520///
4521/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004522static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004523BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004524 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004525 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004526 // C++0x [class.copy]p30:
4527 // Each subobject is assigned in the manner appropriate to its type:
4528 //
4529 // - if the subobject is of class type, the copy assignment operator
4530 // for the class is used (as if by explicit qualification; that is,
4531 // ignoring any possible virtual overriding functions in more derived
4532 // classes);
4533 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4534 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4535
4536 // Look for operator=.
4537 DeclarationName Name
4538 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4539 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4540 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4541
4542 // Filter out any result that isn't a copy-assignment operator.
4543 LookupResult::Filter F = OpLookup.makeFilter();
4544 while (F.hasNext()) {
4545 NamedDecl *D = F.next();
4546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4547 if (Method->isCopyAssignmentOperator())
4548 continue;
4549
4550 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004551 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004552 F.done();
4553
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004554 // Suppress the protected check (C++ [class.protected]) for each of the
4555 // assignment operators we found. This strange dance is required when
4556 // we're assigning via a base classes's copy-assignment operator. To
4557 // ensure that we're getting the right base class subobject (without
4558 // ambiguities), we need to cast "this" to that subobject type; to
4559 // ensure that we don't go through the virtual call mechanism, we need
4560 // to qualify the operator= name with the base class (see below). However,
4561 // this means that if the base class has a protected copy assignment
4562 // operator, the protected member access check will fail. So, we
4563 // rewrite "protected" access to "public" access in this case, since we
4564 // know by construction that we're calling from a derived class.
4565 if (CopyingBaseSubobject) {
4566 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4567 L != LEnd; ++L) {
4568 if (L.getAccess() == AS_protected)
4569 L.setAccess(AS_public);
4570 }
4571 }
4572
Douglas Gregor06a9f362010-05-01 20:49:11 +00004573 // Create the nested-name-specifier that will be used to qualify the
4574 // reference to operator=; this is required to suppress the virtual
4575 // call mechanism.
4576 CXXScopeSpec SS;
4577 SS.setRange(Loc);
4578 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4579 T.getTypePtr()));
4580
4581 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004582 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004583 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004584 /*FirstQualifierInScope=*/0, OpLookup,
4585 /*TemplateArgs=*/0,
4586 /*SuppressQualifierCheck=*/true);
4587 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004588 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004589
4590 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004591
John McCall60d7b3a2010-08-24 06:29:42 +00004592 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004593 OpEqualRef.takeAs<Expr>(),
4594 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004595 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004596 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004597
4598 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004599 }
John McCallb0207482010-03-16 06:11:48 +00004600
Douglas Gregor06a9f362010-05-01 20:49:11 +00004601 // - if the subobject is of scalar type, the built-in assignment
4602 // operator is used.
4603 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4604 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004605 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004606 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004607 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004608
4609 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004610 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004611
4612 // - if the subobject is an array, each element is assigned, in the
4613 // manner appropriate to the element type;
4614
4615 // Construct a loop over the array bounds, e.g.,
4616 //
4617 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4618 //
4619 // that will copy each of the array elements.
4620 QualType SizeType = S.Context.getSizeType();
4621
4622 // Create the iteration variable.
4623 IdentifierInfo *IterationVarName = 0;
4624 {
4625 llvm::SmallString<8> Str;
4626 llvm::raw_svector_ostream OS(Str);
4627 OS << "__i" << Depth;
4628 IterationVarName = &S.Context.Idents.get(OS.str());
4629 }
4630 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4631 IterationVarName, SizeType,
4632 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004633 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004634
4635 // Initialize the iteration variable to zero.
4636 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004637 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004638
4639 // Create a reference to the iteration variable; we'll use this several
4640 // times throughout.
4641 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00004642 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004643 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4644
4645 // Create the DeclStmt that holds the iteration variable.
4646 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4647
4648 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004649 llvm::APInt Upper
4650 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004651 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00004652 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00004653 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4654 BO_NE, S.Context.BoolTy,
4655 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004656
4657 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004658 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00004659 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4660 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004661
4662 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004663 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4664 IterationVarRef, Loc));
4665 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4666 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004667
4668 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00004669 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4670 To, From, CopyingBaseSubobject,
4671 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004672 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004673 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004674
4675 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004676 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004677 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004678 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004679 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004680}
4681
Douglas Gregora376d102010-07-02 21:50:04 +00004682/// \brief Determine whether the given class has a copy assignment operator
4683/// that accepts a const-qualified argument.
4684static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4685 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4686
4687 if (!Class->hasDeclaredCopyAssignment())
4688 S.DeclareImplicitCopyAssignment(Class);
4689
4690 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4691 DeclarationName OpName
4692 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4693
4694 DeclContext::lookup_const_iterator Op, OpEnd;
4695 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4696 // C++ [class.copy]p9:
4697 // A user-declared copy assignment operator is a non-static non-template
4698 // member function of class X with exactly one parameter of type X, X&,
4699 // const X&, volatile X& or const volatile X&.
4700 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4701 if (!Method)
4702 continue;
4703
4704 if (Method->isStatic())
4705 continue;
4706 if (Method->getPrimaryTemplate())
4707 continue;
4708 const FunctionProtoType *FnType =
4709 Method->getType()->getAs<FunctionProtoType>();
4710 assert(FnType && "Overloaded operator has no prototype.");
4711 // Don't assert on this; an invalid decl might have been left in the AST.
4712 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4713 continue;
4714 bool AcceptsConst = true;
4715 QualType ArgType = FnType->getArgType(0);
4716 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4717 ArgType = Ref->getPointeeType();
4718 // Is it a non-const lvalue reference?
4719 if (!ArgType.isConstQualified())
4720 AcceptsConst = false;
4721 }
4722 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4723 continue;
4724
4725 // We have a single argument of type cv X or cv X&, i.e. we've found the
4726 // copy assignment operator. Return whether it accepts const arguments.
4727 return AcceptsConst;
4728 }
4729 assert(Class->isInvalidDecl() &&
4730 "No copy assignment operator declared in valid code.");
4731 return false;
4732}
4733
Douglas Gregor23c94db2010-07-02 17:43:08 +00004734CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004735 // Note: The following rules are largely analoguous to the copy
4736 // constructor rules. Note that virtual bases are not taken into account
4737 // for determining the argument type of the operator. Note also that
4738 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004739
4740
Douglas Gregord3c35902010-07-01 16:36:15 +00004741 // C++ [class.copy]p10:
4742 // If the class definition does not explicitly declare a copy
4743 // assignment operator, one is declared implicitly.
4744 // The implicitly-defined copy assignment operator for a class X
4745 // will have the form
4746 //
4747 // X& X::operator=(const X&)
4748 //
4749 // if
4750 bool HasConstCopyAssignment = true;
4751
4752 // -- each direct base class B of X has a copy assignment operator
4753 // whose parameter is of type const B&, const volatile B& or B,
4754 // and
4755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4756 BaseEnd = ClassDecl->bases_end();
4757 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4758 assert(!Base->getType()->isDependentType() &&
4759 "Cannot generate implicit members for class with dependent bases.");
4760 const CXXRecordDecl *BaseClassDecl
4761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004762 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004763 }
4764
4765 // -- for all the nonstatic data members of X that are of a class
4766 // type M (or array thereof), each such class type has a copy
4767 // assignment operator whose parameter is of type const M&,
4768 // const volatile M& or M.
4769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4770 FieldEnd = ClassDecl->field_end();
4771 HasConstCopyAssignment && Field != FieldEnd;
4772 ++Field) {
4773 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4774 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4775 const CXXRecordDecl *FieldClassDecl
4776 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004777 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004778 }
4779 }
4780
4781 // Otherwise, the implicitly declared copy assignment operator will
4782 // have the form
4783 //
4784 // X& X::operator=(X&)
4785 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4786 QualType RetType = Context.getLValueReferenceType(ArgType);
4787 if (HasConstCopyAssignment)
4788 ArgType = ArgType.withConst();
4789 ArgType = Context.getLValueReferenceType(ArgType);
4790
Douglas Gregorb87786f2010-07-01 17:48:08 +00004791 // C++ [except.spec]p14:
4792 // An implicitly declared special member function (Clause 12) shall have an
4793 // exception-specification. [...]
4794 ImplicitExceptionSpecification ExceptSpec(Context);
4795 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4796 BaseEnd = ClassDecl->bases_end();
4797 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004798 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004799 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004800
4801 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4802 DeclareImplicitCopyAssignment(BaseClassDecl);
4803
Douglas Gregorb87786f2010-07-01 17:48:08 +00004804 if (CXXMethodDecl *CopyAssign
4805 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4806 ExceptSpec.CalledDecl(CopyAssign);
4807 }
4808 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4809 FieldEnd = ClassDecl->field_end();
4810 Field != FieldEnd;
4811 ++Field) {
4812 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4813 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004814 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004815 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004816
4817 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4818 DeclareImplicitCopyAssignment(FieldClassDecl);
4819
Douglas Gregorb87786f2010-07-01 17:48:08 +00004820 if (CXXMethodDecl *CopyAssign
4821 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4822 ExceptSpec.CalledDecl(CopyAssign);
4823 }
4824 }
4825
Douglas Gregord3c35902010-07-01 16:36:15 +00004826 // An implicitly-declared copy assignment operator is an inline public
4827 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00004828 FunctionProtoType::ExtProtoInfo EPI;
4829 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4830 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4831 EPI.NumExceptions = ExceptSpec.size();
4832 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00004833 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004834 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004835 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004836 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00004837 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00004838 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004839 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004840 /*isInline=*/true);
4841 CopyAssignment->setAccess(AS_public);
4842 CopyAssignment->setImplicit();
4843 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004844
4845 // Add the parameter to the operator.
4846 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4847 ClassDecl->getLocation(),
4848 /*Id=*/0,
4849 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004850 SC_None,
4851 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004852 CopyAssignment->setParams(&FromParam, 1);
4853
Douglas Gregora376d102010-07-02 21:50:04 +00004854 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004855 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4856
Douglas Gregor23c94db2010-07-02 17:43:08 +00004857 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004858 PushOnScopeChains(CopyAssignment, S, false);
4859 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004860
4861 AddOverriddenMethods(ClassDecl, CopyAssignment);
4862 return CopyAssignment;
4863}
4864
Douglas Gregor06a9f362010-05-01 20:49:11 +00004865void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4866 CXXMethodDecl *CopyAssignOperator) {
4867 assert((CopyAssignOperator->isImplicit() &&
4868 CopyAssignOperator->isOverloadedOperator() &&
4869 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004870 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004871 "DefineImplicitCopyAssignment called for wrong function");
4872
4873 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4874
4875 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4876 CopyAssignOperator->setInvalidDecl();
4877 return;
4878 }
4879
4880 CopyAssignOperator->setUsed();
4881
4882 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004883 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004884
4885 // C++0x [class.copy]p30:
4886 // The implicitly-defined or explicitly-defaulted copy assignment operator
4887 // for a non-union class X performs memberwise copy assignment of its
4888 // subobjects. The direct base classes of X are assigned first, in the
4889 // order of their declaration in the base-specifier-list, and then the
4890 // immediate non-static data members of X are assigned, in the order in
4891 // which they were declared in the class definition.
4892
4893 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004894 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004895
4896 // The parameter for the "other" object, which we are copying from.
4897 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4898 Qualifiers OtherQuals = Other->getType().getQualifiers();
4899 QualType OtherRefType = Other->getType();
4900 if (const LValueReferenceType *OtherRef
4901 = OtherRefType->getAs<LValueReferenceType>()) {
4902 OtherRefType = OtherRef->getPointeeType();
4903 OtherQuals = OtherRefType.getQualifiers();
4904 }
4905
4906 // Our location for everything implicitly-generated.
4907 SourceLocation Loc = CopyAssignOperator->getLocation();
4908
4909 // Construct a reference to the "other" object. We'll be using this
4910 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00004911 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004912 assert(OtherRef && "Reference to parameter cannot fail!");
4913
4914 // Construct the "this" pointer. We'll be using this throughout the generated
4915 // ASTs.
4916 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4917 assert(This && "Reference to this cannot fail!");
4918
4919 // Assign base classes.
4920 bool Invalid = false;
4921 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4922 E = ClassDecl->bases_end(); Base != E; ++Base) {
4923 // Form the assignment:
4924 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4925 QualType BaseType = Base->getType().getUnqualifiedType();
4926 CXXRecordDecl *BaseClassDecl = 0;
4927 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4928 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4929 else {
4930 Invalid = true;
4931 continue;
4932 }
4933
John McCallf871d0c2010-08-07 06:22:56 +00004934 CXXCastPath BasePath;
4935 BasePath.push_back(Base);
4936
Douglas Gregor06a9f362010-05-01 20:49:11 +00004937 // Construct the "from" expression, which is an implicit cast to the
4938 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00004939 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004940 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004941 CK_UncheckedDerivedToBase,
4942 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004943
4944 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004945 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004946
4947 // Implicitly cast "this" to the appropriately-qualified base type.
4948 Expr *ToE = To.takeAs<Expr>();
4949 ImpCastExprToType(ToE,
4950 Context.getCVRQualifiedType(BaseType,
4951 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004952 CK_UncheckedDerivedToBase,
4953 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004954 To = Owned(ToE);
4955
4956 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004957 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004958 To.get(), From,
4959 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004960 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004961 Diag(CurrentLocation, diag::note_member_synthesized_at)
4962 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4963 CopyAssignOperator->setInvalidDecl();
4964 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004965 }
4966
4967 // Success! Record the copy.
4968 Statements.push_back(Copy.takeAs<Expr>());
4969 }
4970
4971 // \brief Reference to the __builtin_memcpy function.
4972 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00004973 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00004974 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004975
4976 // Assign non-static members.
4977 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4978 FieldEnd = ClassDecl->field_end();
4979 Field != FieldEnd; ++Field) {
4980 // Check for members of reference type; we can't copy those.
4981 if (Field->getType()->isReferenceType()) {
4982 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4983 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4984 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004985 Diag(CurrentLocation, diag::note_member_synthesized_at)
4986 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004987 Invalid = true;
4988 continue;
4989 }
4990
4991 // Check for members of const-qualified, non-class type.
4992 QualType BaseType = Context.getBaseElementType(Field->getType());
4993 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4994 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4995 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4996 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004997 Diag(CurrentLocation, diag::note_member_synthesized_at)
4998 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004999 Invalid = true;
5000 continue;
5001 }
5002
5003 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005004 if (FieldType->isIncompleteArrayType()) {
5005 assert(ClassDecl->hasFlexibleArrayMember() &&
5006 "Incomplete array type is not valid");
5007 continue;
5008 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005009
5010 // Build references to the field in the object we're copying from and to.
5011 CXXScopeSpec SS; // Intentionally empty
5012 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5013 LookupMemberName);
5014 MemberLookup.addDecl(*Field);
5015 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005016 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005017 Loc, /*IsArrow=*/false,
5018 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005019 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005020 Loc, /*IsArrow=*/true,
5021 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005022 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5023 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5024
5025 // If the field should be copied with __builtin_memcpy rather than via
5026 // explicit assignments, do so. This optimization only applies for arrays
5027 // of scalars and arrays of class type with trivial copy-assignment
5028 // operators.
5029 if (FieldType->isArrayType() &&
5030 (!BaseType->isRecordType() ||
5031 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5032 ->hasTrivialCopyAssignment())) {
5033 // Compute the size of the memory buffer to be copied.
5034 QualType SizeType = Context.getSizeType();
5035 llvm::APInt Size(Context.getTypeSize(SizeType),
5036 Context.getTypeSizeInChars(BaseType).getQuantity());
5037 for (const ConstantArrayType *Array
5038 = Context.getAsConstantArrayType(FieldType);
5039 Array;
5040 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005041 llvm::APInt ArraySize
5042 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005043 Size *= ArraySize;
5044 }
5045
5046 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005047 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5048 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005049
5050 bool NeedsCollectableMemCpy =
5051 (BaseType->isRecordType() &&
5052 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5053
5054 if (NeedsCollectableMemCpy) {
5055 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005056 // Create a reference to the __builtin_objc_memmove_collectable function.
5057 LookupResult R(*this,
5058 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005059 Loc, LookupOrdinaryName);
5060 LookupName(R, TUScope, true);
5061
5062 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5063 if (!CollectableMemCpy) {
5064 // Something went horribly wrong earlier, and we will have
5065 // complained about it.
5066 Invalid = true;
5067 continue;
5068 }
5069
5070 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5071 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005072 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005073 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5074 }
5075 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005076 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005077 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005078 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5079 LookupOrdinaryName);
5080 LookupName(R, TUScope, true);
5081
5082 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5083 if (!BuiltinMemCpy) {
5084 // Something went horribly wrong earlier, and we will have complained
5085 // about it.
5086 Invalid = true;
5087 continue;
5088 }
5089
5090 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5091 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005092 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005093 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5094 }
5095
John McCallca0408f2010-08-23 06:44:23 +00005096 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005097 CallArgs.push_back(To.takeAs<Expr>());
5098 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005099 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005100 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005101 if (NeedsCollectableMemCpy)
5102 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005103 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005104 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005105 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005106 else
5107 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005108 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005109 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005110 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005111
Douglas Gregor06a9f362010-05-01 20:49:11 +00005112 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5113 Statements.push_back(Call.takeAs<Expr>());
5114 continue;
5115 }
5116
5117 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005118 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005119 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005120 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005121 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005122 Diag(CurrentLocation, diag::note_member_synthesized_at)
5123 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5124 CopyAssignOperator->setInvalidDecl();
5125 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005126 }
5127
5128 // Success! Record the copy.
5129 Statements.push_back(Copy.takeAs<Stmt>());
5130 }
5131
5132 if (!Invalid) {
5133 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005134 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005135
John McCall60d7b3a2010-08-24 06:29:42 +00005136 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005137 if (Return.isInvalid())
5138 Invalid = true;
5139 else {
5140 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005141
5142 if (Trap.hasErrorOccurred()) {
5143 Diag(CurrentLocation, diag::note_member_synthesized_at)
5144 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5145 Invalid = true;
5146 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005147 }
5148 }
5149
5150 if (Invalid) {
5151 CopyAssignOperator->setInvalidDecl();
5152 return;
5153 }
5154
John McCall60d7b3a2010-08-24 06:29:42 +00005155 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005156 /*isStmtExpr=*/false);
5157 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5158 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005159}
5160
Douglas Gregor23c94db2010-07-02 17:43:08 +00005161CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5162 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005163 // C++ [class.copy]p4:
5164 // If the class definition does not explicitly declare a copy
5165 // constructor, one is declared implicitly.
5166
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005167 // C++ [class.copy]p5:
5168 // The implicitly-declared copy constructor for a class X will
5169 // have the form
5170 //
5171 // X::X(const X&)
5172 //
5173 // if
5174 bool HasConstCopyConstructor = true;
5175
5176 // -- each direct or virtual base class B of X has a copy
5177 // constructor whose first parameter is of type const B& or
5178 // const volatile B&, and
5179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5180 BaseEnd = ClassDecl->bases_end();
5181 HasConstCopyConstructor && Base != BaseEnd;
5182 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005183 // Virtual bases are handled below.
5184 if (Base->isVirtual())
5185 continue;
5186
Douglas Gregor22584312010-07-02 23:41:54 +00005187 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005188 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005189 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5190 DeclareImplicitCopyConstructor(BaseClassDecl);
5191
Douglas Gregor598a8542010-07-01 18:27:03 +00005192 HasConstCopyConstructor
5193 = BaseClassDecl->hasConstCopyConstructor(Context);
5194 }
5195
5196 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5197 BaseEnd = ClassDecl->vbases_end();
5198 HasConstCopyConstructor && Base != BaseEnd;
5199 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005200 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005201 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005202 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5203 DeclareImplicitCopyConstructor(BaseClassDecl);
5204
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005205 HasConstCopyConstructor
5206 = BaseClassDecl->hasConstCopyConstructor(Context);
5207 }
5208
5209 // -- for all the nonstatic data members of X that are of a
5210 // class type M (or array thereof), each such class type
5211 // has a copy constructor whose first parameter is of type
5212 // const M& or const volatile M&.
5213 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5214 FieldEnd = ClassDecl->field_end();
5215 HasConstCopyConstructor && Field != FieldEnd;
5216 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005217 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005218 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005219 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005220 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005221 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5222 DeclareImplicitCopyConstructor(FieldClassDecl);
5223
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005224 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005225 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005226 }
5227 }
5228
5229 // Otherwise, the implicitly declared copy constructor will have
5230 // the form
5231 //
5232 // X::X(X&)
5233 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5234 QualType ArgType = ClassType;
5235 if (HasConstCopyConstructor)
5236 ArgType = ArgType.withConst();
5237 ArgType = Context.getLValueReferenceType(ArgType);
5238
Douglas Gregor0d405db2010-07-01 20:59:04 +00005239 // C++ [except.spec]p14:
5240 // An implicitly declared special member function (Clause 12) shall have an
5241 // exception-specification. [...]
5242 ImplicitExceptionSpecification ExceptSpec(Context);
5243 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5244 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5245 BaseEnd = ClassDecl->bases_end();
5246 Base != BaseEnd;
5247 ++Base) {
5248 // Virtual bases are handled below.
5249 if (Base->isVirtual())
5250 continue;
5251
Douglas Gregor22584312010-07-02 23:41:54 +00005252 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005253 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005254 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5255 DeclareImplicitCopyConstructor(BaseClassDecl);
5256
Douglas Gregor0d405db2010-07-01 20:59:04 +00005257 if (CXXConstructorDecl *CopyConstructor
5258 = BaseClassDecl->getCopyConstructor(Context, Quals))
5259 ExceptSpec.CalledDecl(CopyConstructor);
5260 }
5261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5262 BaseEnd = ClassDecl->vbases_end();
5263 Base != BaseEnd;
5264 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005265 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005266 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005267 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5268 DeclareImplicitCopyConstructor(BaseClassDecl);
5269
Douglas Gregor0d405db2010-07-01 20:59:04 +00005270 if (CXXConstructorDecl *CopyConstructor
5271 = BaseClassDecl->getCopyConstructor(Context, Quals))
5272 ExceptSpec.CalledDecl(CopyConstructor);
5273 }
5274 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5275 FieldEnd = ClassDecl->field_end();
5276 Field != FieldEnd;
5277 ++Field) {
5278 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5279 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005280 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005281 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005282 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5283 DeclareImplicitCopyConstructor(FieldClassDecl);
5284
Douglas Gregor0d405db2010-07-01 20:59:04 +00005285 if (CXXConstructorDecl *CopyConstructor
5286 = FieldClassDecl->getCopyConstructor(Context, Quals))
5287 ExceptSpec.CalledDecl(CopyConstructor);
5288 }
5289 }
5290
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005291 // An implicitly-declared copy constructor is an inline public
5292 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005293 FunctionProtoType::ExtProtoInfo EPI;
5294 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5295 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5296 EPI.NumExceptions = ExceptSpec.size();
5297 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005298 DeclarationName Name
5299 = Context.DeclarationNames.getCXXConstructorName(
5300 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005301 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005302 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005303 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005304 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005305 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005306 /*TInfo=*/0,
5307 /*isExplicit=*/false,
5308 /*isInline=*/true,
5309 /*isImplicitlyDeclared=*/true);
5310 CopyConstructor->setAccess(AS_public);
5311 CopyConstructor->setImplicit();
5312 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5313
Douglas Gregor22584312010-07-02 23:41:54 +00005314 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005315 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5316
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005317 // Add the parameter to the constructor.
5318 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5319 ClassDecl->getLocation(),
5320 /*IdentifierInfo=*/0,
5321 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005322 SC_None,
5323 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005324 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005325 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005326 PushOnScopeChains(CopyConstructor, S, false);
5327 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005328
5329 return CopyConstructor;
5330}
5331
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005332void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5333 CXXConstructorDecl *CopyConstructor,
5334 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005335 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005336 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005337 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005338 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Anders Carlsson63010a72010-04-23 16:24:12 +00005340 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005341 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005342
Douglas Gregor39957dc2010-05-01 15:04:51 +00005343 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005344 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005345
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005346 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5347 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005348 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005349 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005350 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005351 } else {
5352 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5353 CopyConstructor->getLocation(),
5354 MultiStmtArg(*this, 0, 0),
5355 /*isStmtExpr=*/false)
5356 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005357 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005358
5359 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005360}
5361
John McCall60d7b3a2010-08-24 06:29:42 +00005362ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005363Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005364 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005365 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005366 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005367 unsigned ConstructKind,
5368 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005369 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Douglas Gregor2f599792010-04-02 18:24:57 +00005371 // C++0x [class.copy]p34:
5372 // When certain criteria are met, an implementation is allowed to
5373 // omit the copy/move construction of a class object, even if the
5374 // copy/move constructor and/or destructor for the object have
5375 // side effects. [...]
5376 // - when a temporary class object that has not been bound to a
5377 // reference (12.2) would be copied/moved to a class object
5378 // with the same cv-unqualified type, the copy/move operation
5379 // can be omitted by constructing the temporary object
5380 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005381 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5382 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005383 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005384 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005385 }
Mike Stump1eb44332009-09-09 15:08:12 +00005386
5387 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005388 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005389 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005390}
5391
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005392/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5393/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005394ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005395Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5396 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005397 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005398 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005399 unsigned ConstructKind,
5400 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005401 unsigned NumExprs = ExprArgs.size();
5402 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Douglas Gregor7edfb692009-11-23 12:27:39 +00005404 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005405 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005406 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005407 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005408 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5409 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005410}
5411
Mike Stump1eb44332009-09-09 15:08:12 +00005412bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005413 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005414 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005415 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005416 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005417 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005418 move(Exprs), false, CXXConstructExpr::CK_Complete,
5419 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005420 if (TempResult.isInvalid())
5421 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005422
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005423 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005424 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005425 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005426 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005427 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005428
Anders Carlssonfe2de492009-08-25 05:18:00 +00005429 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005430}
5431
John McCall68c6c9a2010-02-02 09:10:11 +00005432void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5433 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005434 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005435 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005436 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005437 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005438 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005439 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005440 << VD->getDeclName()
5441 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005442
John McCallae792222010-09-18 05:25:11 +00005443 // TODO: this should be re-enabled for static locals by !CXAAtExit
5444 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005445 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005446 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005447}
5448
Mike Stump1eb44332009-09-09 15:08:12 +00005449/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005450/// ActOnDeclarator, when a C++ direct initializer is present.
5451/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005452void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005453 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005454 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005455 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005456 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005457
5458 // If there is no declaration, there was an error parsing it. Just ignore
5459 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005460 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005461 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005462
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005463 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5464 if (!VDecl) {
5465 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5466 RealDecl->setInvalidDecl();
5467 return;
5468 }
5469
Douglas Gregor83ddad32009-08-26 21:14:46 +00005470 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005471 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005472 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5473 //
5474 // Clients that want to distinguish between the two forms, can check for
5475 // direct initializer using VarDecl::hasCXXDirectInitializer().
5476 // A major benefit is that clients that don't particularly care about which
5477 // exactly form was it (like the CodeGen) can handle both cases without
5478 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005479
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005480 // C++ 8.5p11:
5481 // The form of initialization (using parentheses or '=') is generally
5482 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005483 // class type.
5484
Douglas Gregor4dffad62010-02-11 22:55:30 +00005485 if (!VDecl->getType()->isDependentType() &&
5486 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005487 diag::err_typecheck_decl_incomplete_type)) {
5488 VDecl->setInvalidDecl();
5489 return;
5490 }
5491
Douglas Gregor90f93822009-12-22 22:17:25 +00005492 // The variable can not have an abstract class type.
5493 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5494 diag::err_abstract_type_in_decl,
5495 AbstractVariableType))
5496 VDecl->setInvalidDecl();
5497
Sebastian Redl31310a22010-02-01 20:16:42 +00005498 const VarDecl *Def;
5499 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005500 Diag(VDecl->getLocation(), diag::err_redefinition)
5501 << VDecl->getDeclName();
5502 Diag(Def->getLocation(), diag::note_previous_definition);
5503 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005504 return;
5505 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005506
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005507 // C++ [class.static.data]p4
5508 // If a static data member is of const integral or const
5509 // enumeration type, its declaration in the class definition can
5510 // specify a constant-initializer which shall be an integral
5511 // constant expression (5.19). In that case, the member can appear
5512 // in integral constant expressions. The member shall still be
5513 // defined in a namespace scope if it is used in the program and the
5514 // namespace scope definition shall not contain an initializer.
5515 //
5516 // We already performed a redefinition check above, but for static
5517 // data members we also need to check whether there was an in-class
5518 // declaration with an initializer.
5519 const VarDecl* PrevInit = 0;
5520 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5521 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5522 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5523 return;
5524 }
5525
Douglas Gregora31040f2010-12-16 01:31:22 +00005526 bool IsDependent = false;
5527 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5528 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5529 VDecl->setInvalidDecl();
5530 return;
5531 }
5532
5533 if (Exprs.get()[I]->isTypeDependent())
5534 IsDependent = true;
5535 }
5536
Douglas Gregor4dffad62010-02-11 22:55:30 +00005537 // If either the declaration has a dependent type or if any of the
5538 // expressions is type-dependent, we represent the initialization
5539 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00005540 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00005541 // Let clients know that initialization was done with a direct initializer.
5542 VDecl->setCXXDirectInitializer(true);
5543
5544 // Store the initialization expressions as a ParenListExpr.
5545 unsigned NumExprs = Exprs.size();
5546 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5547 (Expr **)Exprs.release(),
5548 NumExprs, RParenLoc));
5549 return;
5550 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005551
5552 // Capture the variable that is being initialized and the style of
5553 // initialization.
5554 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5555
5556 // FIXME: Poor source location information.
5557 InitializationKind Kind
5558 = InitializationKind::CreateDirect(VDecl->getLocation(),
5559 LParenLoc, RParenLoc);
5560
5561 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005562 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005563 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005564 if (Result.isInvalid()) {
5565 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005566 return;
5567 }
John McCallb4eb64d2010-10-08 02:01:28 +00005568
5569 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005570
Douglas Gregor53c374f2010-12-07 00:41:46 +00005571 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00005572 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005573 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005574
John McCall4204f072010-08-02 21:13:48 +00005575 if (!VDecl->isInvalidDecl() &&
5576 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005577 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005578 !VDecl->getInit()->isConstantInitializer(Context,
5579 VDecl->getType()->isReferenceType()))
5580 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5581 << VDecl->getInit()->getSourceRange();
5582
John McCall68c6c9a2010-02-02 09:10:11 +00005583 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5584 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005585}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005586
Douglas Gregor39da0b82009-09-09 23:08:42 +00005587/// \brief Given a constructor and the set of arguments provided for the
5588/// constructor, convert the arguments and add any required default arguments
5589/// to form a proper call to this constructor.
5590///
5591/// \returns true if an error occurred, false otherwise.
5592bool
5593Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5594 MultiExprArg ArgsPtr,
5595 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005596 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005597 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5598 unsigned NumArgs = ArgsPtr.size();
5599 Expr **Args = (Expr **)ArgsPtr.get();
5600
5601 const FunctionProtoType *Proto
5602 = Constructor->getType()->getAs<FunctionProtoType>();
5603 assert(Proto && "Constructor without a prototype?");
5604 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005605
5606 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005607 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005608 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005609 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005610 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005611
5612 VariadicCallType CallType =
5613 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5614 llvm::SmallVector<Expr *, 8> AllArgs;
5615 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5616 Proto, 0, Args, NumArgs, AllArgs,
5617 CallType);
5618 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5619 ConvertedArgs.push_back(AllArgs[i]);
5620 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005621}
5622
Anders Carlsson20d45d22009-12-12 00:32:00 +00005623static inline bool
5624CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5625 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005626 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005627 if (isa<NamespaceDecl>(DC)) {
5628 return SemaRef.Diag(FnDecl->getLocation(),
5629 diag::err_operator_new_delete_declared_in_namespace)
5630 << FnDecl->getDeclName();
5631 }
5632
5633 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005634 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005635 return SemaRef.Diag(FnDecl->getLocation(),
5636 diag::err_operator_new_delete_declared_static)
5637 << FnDecl->getDeclName();
5638 }
5639
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005640 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005641}
5642
Anders Carlsson156c78e2009-12-13 17:53:43 +00005643static inline bool
5644CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5645 CanQualType ExpectedResultType,
5646 CanQualType ExpectedFirstParamType,
5647 unsigned DependentParamTypeDiag,
5648 unsigned InvalidParamTypeDiag) {
5649 QualType ResultType =
5650 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5651
5652 // Check that the result type is not dependent.
5653 if (ResultType->isDependentType())
5654 return SemaRef.Diag(FnDecl->getLocation(),
5655 diag::err_operator_new_delete_dependent_result_type)
5656 << FnDecl->getDeclName() << ExpectedResultType;
5657
5658 // Check that the result type is what we expect.
5659 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5660 return SemaRef.Diag(FnDecl->getLocation(),
5661 diag::err_operator_new_delete_invalid_result_type)
5662 << FnDecl->getDeclName() << ExpectedResultType;
5663
5664 // A function template must have at least 2 parameters.
5665 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5666 return SemaRef.Diag(FnDecl->getLocation(),
5667 diag::err_operator_new_delete_template_too_few_parameters)
5668 << FnDecl->getDeclName();
5669
5670 // The function decl must have at least 1 parameter.
5671 if (FnDecl->getNumParams() == 0)
5672 return SemaRef.Diag(FnDecl->getLocation(),
5673 diag::err_operator_new_delete_too_few_parameters)
5674 << FnDecl->getDeclName();
5675
5676 // Check the the first parameter type is not dependent.
5677 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5678 if (FirstParamType->isDependentType())
5679 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5680 << FnDecl->getDeclName() << ExpectedFirstParamType;
5681
5682 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005683 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005684 ExpectedFirstParamType)
5685 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5686 << FnDecl->getDeclName() << ExpectedFirstParamType;
5687
5688 return false;
5689}
5690
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005691static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005692CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005693 // C++ [basic.stc.dynamic.allocation]p1:
5694 // A program is ill-formed if an allocation function is declared in a
5695 // namespace scope other than global scope or declared static in global
5696 // scope.
5697 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5698 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005699
5700 CanQualType SizeTy =
5701 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5702
5703 // C++ [basic.stc.dynamic.allocation]p1:
5704 // The return type shall be void*. The first parameter shall have type
5705 // std::size_t.
5706 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5707 SizeTy,
5708 diag::err_operator_new_dependent_param_type,
5709 diag::err_operator_new_param_type))
5710 return true;
5711
5712 // C++ [basic.stc.dynamic.allocation]p1:
5713 // The first parameter shall not have an associated default argument.
5714 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005715 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005716 diag::err_operator_new_default_arg)
5717 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5718
5719 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005720}
5721
5722static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005723CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5724 // C++ [basic.stc.dynamic.deallocation]p1:
5725 // A program is ill-formed if deallocation functions are declared in a
5726 // namespace scope other than global scope or declared static in global
5727 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005728 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5729 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005730
5731 // C++ [basic.stc.dynamic.deallocation]p2:
5732 // Each deallocation function shall return void and its first parameter
5733 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005734 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5735 SemaRef.Context.VoidPtrTy,
5736 diag::err_operator_delete_dependent_param_type,
5737 diag::err_operator_delete_param_type))
5738 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005739
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005740 return false;
5741}
5742
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005743/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5744/// of this overloaded operator is well-formed. If so, returns false;
5745/// otherwise, emits appropriate diagnostics and returns true.
5746bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005747 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005748 "Expected an overloaded operator declaration");
5749
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005750 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5751
Mike Stump1eb44332009-09-09 15:08:12 +00005752 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005753 // The allocation and deallocation functions, operator new,
5754 // operator new[], operator delete and operator delete[], are
5755 // described completely in 3.7.3. The attributes and restrictions
5756 // found in the rest of this subclause do not apply to them unless
5757 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005758 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005759 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005760
Anders Carlssona3ccda52009-12-12 00:26:23 +00005761 if (Op == OO_New || Op == OO_Array_New)
5762 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005763
5764 // C++ [over.oper]p6:
5765 // An operator function shall either be a non-static member
5766 // function or be a non-member function and have at least one
5767 // parameter whose type is a class, a reference to a class, an
5768 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005769 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5770 if (MethodDecl->isStatic())
5771 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005772 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005773 } else {
5774 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005775 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5776 ParamEnd = FnDecl->param_end();
5777 Param != ParamEnd; ++Param) {
5778 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005779 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5780 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005781 ClassOrEnumParam = true;
5782 break;
5783 }
5784 }
5785
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005786 if (!ClassOrEnumParam)
5787 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005788 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005789 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005790 }
5791
5792 // C++ [over.oper]p8:
5793 // An operator function cannot have default arguments (8.3.6),
5794 // except where explicitly stated below.
5795 //
Mike Stump1eb44332009-09-09 15:08:12 +00005796 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005797 // (C++ [over.call]p1).
5798 if (Op != OO_Call) {
5799 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5800 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005801 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005802 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005803 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005804 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005805 }
5806 }
5807
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005808 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5809 { false, false, false }
5810#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5811 , { Unary, Binary, MemberOnly }
5812#include "clang/Basic/OperatorKinds.def"
5813 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005814
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005815 bool CanBeUnaryOperator = OperatorUses[Op][0];
5816 bool CanBeBinaryOperator = OperatorUses[Op][1];
5817 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005818
5819 // C++ [over.oper]p8:
5820 // [...] Operator functions cannot have more or fewer parameters
5821 // than the number required for the corresponding operator, as
5822 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005823 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005824 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005825 if (Op != OO_Call &&
5826 ((NumParams == 1 && !CanBeUnaryOperator) ||
5827 (NumParams == 2 && !CanBeBinaryOperator) ||
5828 (NumParams < 1) || (NumParams > 2))) {
5829 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005830 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005831 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005832 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005833 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005834 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005835 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005836 assert(CanBeBinaryOperator &&
5837 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005838 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005839 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005840
Chris Lattner416e46f2008-11-21 07:57:12 +00005841 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005842 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005843 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005844
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005845 // Overloaded operators other than operator() cannot be variadic.
5846 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005847 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005848 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005849 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005850 }
5851
5852 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005853 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5854 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005855 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005856 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005857 }
5858
5859 // C++ [over.inc]p1:
5860 // The user-defined function called operator++ implements the
5861 // prefix and postfix ++ operator. If this function is a member
5862 // function with no parameters, or a non-member function with one
5863 // parameter of class or enumeration type, it defines the prefix
5864 // increment operator ++ for objects of that type. If the function
5865 // is a member function with one parameter (which shall be of type
5866 // int) or a non-member function with two parameters (the second
5867 // of which shall be of type int), it defines the postfix
5868 // increment operator ++ for objects of that type.
5869 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5870 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5871 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005872 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005873 ParamIsInt = BT->getKind() == BuiltinType::Int;
5874
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005875 if (!ParamIsInt)
5876 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005877 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005878 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005879 }
5880
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005881 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005882}
Chris Lattner5a003a42008-12-17 07:09:26 +00005883
Sean Hunta6c058d2010-01-13 09:01:02 +00005884/// CheckLiteralOperatorDeclaration - Check whether the declaration
5885/// of this literal operator function is well-formed. If so, returns
5886/// false; otherwise, emits appropriate diagnostics and returns true.
5887bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5888 DeclContext *DC = FnDecl->getDeclContext();
5889 Decl::Kind Kind = DC->getDeclKind();
5890 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5891 Kind != Decl::LinkageSpec) {
5892 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5893 << FnDecl->getDeclName();
5894 return true;
5895 }
5896
5897 bool Valid = false;
5898
Sean Hunt216c2782010-04-07 23:11:06 +00005899 // template <char...> type operator "" name() is the only valid template
5900 // signature, and the only valid signature with no parameters.
5901 if (FnDecl->param_size() == 0) {
5902 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5903 // Must have only one template parameter
5904 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5905 if (Params->size() == 1) {
5906 NonTypeTemplateParmDecl *PmDecl =
5907 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005908
Sean Hunt216c2782010-04-07 23:11:06 +00005909 // The template parameter must be a char parameter pack.
5910 // FIXME: This test will always fail because non-type parameter packs
5911 // have not been implemented.
5912 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5913 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5914 Valid = true;
5915 }
5916 }
5917 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005918 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005919 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5920
Sean Hunta6c058d2010-01-13 09:01:02 +00005921 QualType T = (*Param)->getType();
5922
Sean Hunt30019c02010-04-07 22:57:35 +00005923 // unsigned long long int, long double, and any character type are allowed
5924 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005925 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5926 Context.hasSameType(T, Context.LongDoubleTy) ||
5927 Context.hasSameType(T, Context.CharTy) ||
5928 Context.hasSameType(T, Context.WCharTy) ||
5929 Context.hasSameType(T, Context.Char16Ty) ||
5930 Context.hasSameType(T, Context.Char32Ty)) {
5931 if (++Param == FnDecl->param_end())
5932 Valid = true;
5933 goto FinishedParams;
5934 }
5935
Sean Hunt30019c02010-04-07 22:57:35 +00005936 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005937 const PointerType *PT = T->getAs<PointerType>();
5938 if (!PT)
5939 goto FinishedParams;
5940 T = PT->getPointeeType();
5941 if (!T.isConstQualified())
5942 goto FinishedParams;
5943 T = T.getUnqualifiedType();
5944
5945 // Move on to the second parameter;
5946 ++Param;
5947
5948 // If there is no second parameter, the first must be a const char *
5949 if (Param == FnDecl->param_end()) {
5950 if (Context.hasSameType(T, Context.CharTy))
5951 Valid = true;
5952 goto FinishedParams;
5953 }
5954
5955 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5956 // are allowed as the first parameter to a two-parameter function
5957 if (!(Context.hasSameType(T, Context.CharTy) ||
5958 Context.hasSameType(T, Context.WCharTy) ||
5959 Context.hasSameType(T, Context.Char16Ty) ||
5960 Context.hasSameType(T, Context.Char32Ty)))
5961 goto FinishedParams;
5962
5963 // The second and final parameter must be an std::size_t
5964 T = (*Param)->getType().getUnqualifiedType();
5965 if (Context.hasSameType(T, Context.getSizeType()) &&
5966 ++Param == FnDecl->param_end())
5967 Valid = true;
5968 }
5969
5970 // FIXME: This diagnostic is absolutely terrible.
5971FinishedParams:
5972 if (!Valid) {
5973 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5974 << FnDecl->getDeclName();
5975 return true;
5976 }
5977
5978 return false;
5979}
5980
Douglas Gregor074149e2009-01-05 19:45:36 +00005981/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5982/// linkage specification, including the language and (if present)
5983/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5984/// the location of the language string literal, which is provided
5985/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5986/// the '{' brace. Otherwise, this linkage specification does not
5987/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00005988Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5989 SourceLocation LangLoc,
5990 llvm::StringRef Lang,
5991 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005992 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005993 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005994 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005995 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005996 Language = LinkageSpecDecl::lang_cxx;
5997 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005998 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00005999 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006000 }
Mike Stump1eb44332009-09-09 15:08:12 +00006001
Chris Lattnercc98eac2008-12-17 07:13:27 +00006002 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006003
Douglas Gregor074149e2009-01-05 19:45:36 +00006004 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006005 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006006 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006007 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006008 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006009 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006010}
6011
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006012/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006013/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6014/// valid, it's the position of the closing '}' brace in a linkage
6015/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006016Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6017 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006018 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006019 if (LinkageSpec)
6020 PopDeclContext();
6021 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006022}
6023
Douglas Gregord308e622009-05-18 20:51:54 +00006024/// \brief Perform semantic analysis for the variable declaration that
6025/// occurs within a C++ catch clause, returning the newly-created
6026/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006027VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006028 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006029 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006030 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006031 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006032 QualType ExDeclType = TInfo->getType();
6033
Sebastian Redl4b07b292008-12-22 19:15:10 +00006034 // Arrays and functions decay.
6035 if (ExDeclType->isArrayType())
6036 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6037 else if (ExDeclType->isFunctionType())
6038 ExDeclType = Context.getPointerType(ExDeclType);
6039
6040 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6041 // The exception-declaration shall not denote a pointer or reference to an
6042 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006043 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006044 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006045 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006046 Invalid = true;
6047 }
Douglas Gregord308e622009-05-18 20:51:54 +00006048
Douglas Gregora2762912010-03-08 01:47:36 +00006049 // GCC allows catching pointers and references to incomplete types
6050 // as an extension; so do we, but we warn by default.
6051
Sebastian Redl4b07b292008-12-22 19:15:10 +00006052 QualType BaseType = ExDeclType;
6053 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006054 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006055 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006056 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006057 BaseType = Ptr->getPointeeType();
6058 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006059 DK = diag::ext_catch_incomplete_ptr;
6060 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006061 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006062 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006063 BaseType = Ref->getPointeeType();
6064 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006065 DK = diag::ext_catch_incomplete_ref;
6066 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006067 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006068 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006069 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6070 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006071 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006072
Mike Stump1eb44332009-09-09 15:08:12 +00006073 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006074 RequireNonAbstractType(Loc, ExDeclType,
6075 diag::err_abstract_type_in_decl,
6076 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006077 Invalid = true;
6078
John McCall5a180392010-07-24 00:37:23 +00006079 // Only the non-fragile NeXT runtime currently supports C++ catches
6080 // of ObjC types, and no runtime supports catching ObjC types by value.
6081 if (!Invalid && getLangOptions().ObjC1) {
6082 QualType T = ExDeclType;
6083 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6084 T = RT->getPointeeType();
6085
6086 if (T->isObjCObjectType()) {
6087 Diag(Loc, diag::err_objc_object_catch);
6088 Invalid = true;
6089 } else if (T->isObjCObjectPointerType()) {
6090 if (!getLangOptions().NeXTRuntime) {
6091 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6092 Invalid = true;
6093 } else if (!getLangOptions().ObjCNonFragileABI) {
6094 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6095 Invalid = true;
6096 }
6097 }
6098 }
6099
Mike Stump1eb44332009-09-09 15:08:12 +00006100 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006101 Name, ExDeclType, TInfo, SC_None,
6102 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006103 ExDecl->setExceptionVariable(true);
6104
Douglas Gregor6d182892010-03-05 23:38:39 +00006105 if (!Invalid) {
6106 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6107 // C++ [except.handle]p16:
6108 // The object declared in an exception-declaration or, if the
6109 // exception-declaration does not specify a name, a temporary (12.2) is
6110 // copy-initialized (8.5) from the exception object. [...]
6111 // The object is destroyed when the handler exits, after the destruction
6112 // of any automatic objects initialized within the handler.
6113 //
6114 // We just pretend to initialize the object with itself, then make sure
6115 // it can be destroyed later.
6116 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6117 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006118 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006119 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6120 SourceLocation());
6121 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006122 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006123 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006124 if (Result.isInvalid())
6125 Invalid = true;
6126 else
6127 FinalizeVarWithDestructor(ExDecl, RecordTy);
6128 }
6129 }
6130
Douglas Gregord308e622009-05-18 20:51:54 +00006131 if (Invalid)
6132 ExDecl->setInvalidDecl();
6133
6134 return ExDecl;
6135}
6136
6137/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6138/// handler.
John McCalld226f652010-08-21 09:40:31 +00006139Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006140 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006141 bool Invalid = D.isInvalidType();
6142
6143 // Check for unexpanded parameter packs.
6144 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6145 UPPC_ExceptionType)) {
6146 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6147 D.getIdentifierLoc());
6148 Invalid = true;
6149 }
6150
John McCallbf1a0282010-06-04 23:28:52 +00006151 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006152
Sebastian Redl4b07b292008-12-22 19:15:10 +00006153 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006154 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006155 LookupOrdinaryName,
6156 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006157 // The scope should be freshly made just for us. There is just no way
6158 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006159 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006160 if (PrevDecl->isTemplateParameter()) {
6161 // Maybe we will complain about the shadowed template parameter.
6162 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006163 }
6164 }
6165
Chris Lattnereaaebc72009-04-25 08:06:05 +00006166 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006167 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6168 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006169 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006170 }
6171
Douglas Gregor83cb9422010-09-09 17:09:21 +00006172 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006173 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006174 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006175
Chris Lattnereaaebc72009-04-25 08:06:05 +00006176 if (Invalid)
6177 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006178
Sebastian Redl4b07b292008-12-22 19:15:10 +00006179 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006180 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006181 PushOnScopeChains(ExDecl, S);
6182 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006183 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006184
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006185 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006186 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006187}
Anders Carlssonfb311762009-03-14 00:25:26 +00006188
John McCalld226f652010-08-21 09:40:31 +00006189Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006190 Expr *AssertExpr,
6191 Expr *AssertMessageExpr_) {
6192 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006193
Anders Carlssonc3082412009-03-14 00:33:21 +00006194 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6195 llvm::APSInt Value(32);
6196 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6197 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6198 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006199 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006200 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006201
Anders Carlssonc3082412009-03-14 00:33:21 +00006202 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006203 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006204 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006205 }
6206 }
Mike Stump1eb44332009-09-09 15:08:12 +00006207
Douglas Gregor399ad972010-12-15 23:55:21 +00006208 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6209 return 0;
6210
Mike Stump1eb44332009-09-09 15:08:12 +00006211 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006212 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006213
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006214 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006215 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006216}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006217
Douglas Gregor1d869352010-04-07 16:53:43 +00006218/// \brief Perform semantic analysis of the given friend type declaration.
6219///
6220/// \returns A friend declaration that.
6221FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6222 TypeSourceInfo *TSInfo) {
6223 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6224
6225 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006226 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006227
Douglas Gregor06245bf2010-04-07 17:57:12 +00006228 if (!getLangOptions().CPlusPlus0x) {
6229 // C++03 [class.friend]p2:
6230 // An elaborated-type-specifier shall be used in a friend declaration
6231 // for a class.*
6232 //
6233 // * The class-key of the elaborated-type-specifier is required.
6234 if (!ActiveTemplateInstantiations.empty()) {
6235 // Do not complain about the form of friend template types during
6236 // template instantiation; we will already have complained when the
6237 // template was declared.
6238 } else if (!T->isElaboratedTypeSpecifier()) {
6239 // If we evaluated the type to a record type, suggest putting
6240 // a tag in front.
6241 if (const RecordType *RT = T->getAs<RecordType>()) {
6242 RecordDecl *RD = RT->getDecl();
6243
6244 std::string InsertionText = std::string(" ") + RD->getKindName();
6245
6246 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6247 << (unsigned) RD->getTagKind()
6248 << T
6249 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6250 InsertionText);
6251 } else {
6252 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6253 << T
6254 << SourceRange(FriendLoc, TypeRange.getEnd());
6255 }
6256 } else if (T->getAs<EnumType>()) {
6257 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006258 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006259 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006260 }
6261 }
6262
Douglas Gregor06245bf2010-04-07 17:57:12 +00006263 // C++0x [class.friend]p3:
6264 // If the type specifier in a friend declaration designates a (possibly
6265 // cv-qualified) class type, that class is declared as a friend; otherwise,
6266 // the friend declaration is ignored.
6267
6268 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6269 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006270
6271 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6272}
6273
John McCall9a34edb2010-10-19 01:40:49 +00006274/// Handle a friend tag declaration where the scope specifier was
6275/// templated.
6276Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6277 unsigned TagSpec, SourceLocation TagLoc,
6278 CXXScopeSpec &SS,
6279 IdentifierInfo *Name, SourceLocation NameLoc,
6280 AttributeList *Attr,
6281 MultiTemplateParamsArg TempParamLists) {
6282 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6283
6284 bool isExplicitSpecialization = false;
6285 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6286 bool Invalid = false;
6287
6288 if (TemplateParameterList *TemplateParams
6289 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6290 TempParamLists.get(),
6291 TempParamLists.size(),
6292 /*friend*/ true,
6293 isExplicitSpecialization,
6294 Invalid)) {
6295 --NumMatchedTemplateParamLists;
6296
6297 if (TemplateParams->size() > 0) {
6298 // This is a declaration of a class template.
6299 if (Invalid)
6300 return 0;
6301
6302 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6303 SS, Name, NameLoc, Attr,
6304 TemplateParams, AS_public).take();
6305 } else {
6306 // The "template<>" header is extraneous.
6307 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6308 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6309 isExplicitSpecialization = true;
6310 }
6311 }
6312
6313 if (Invalid) return 0;
6314
6315 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6316
6317 bool isAllExplicitSpecializations = true;
6318 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6319 if (TempParamLists.get()[I]->size()) {
6320 isAllExplicitSpecializations = false;
6321 break;
6322 }
6323 }
6324
6325 // FIXME: don't ignore attributes.
6326
6327 // If it's explicit specializations all the way down, just forget
6328 // about the template header and build an appropriate non-templated
6329 // friend. TODO: for source fidelity, remember the headers.
6330 if (isAllExplicitSpecializations) {
6331 ElaboratedTypeKeyword Keyword
6332 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6333 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6334 TagLoc, SS.getRange(), NameLoc);
6335 if (T.isNull())
6336 return 0;
6337
6338 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6339 if (isa<DependentNameType>(T)) {
6340 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6341 TL.setKeywordLoc(TagLoc);
6342 TL.setQualifierRange(SS.getRange());
6343 TL.setNameLoc(NameLoc);
6344 } else {
6345 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6346 TL.setKeywordLoc(TagLoc);
6347 TL.setQualifierRange(SS.getRange());
6348 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6349 }
6350
6351 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6352 TSI, FriendLoc);
6353 Friend->setAccess(AS_public);
6354 CurContext->addDecl(Friend);
6355 return Friend;
6356 }
6357
6358 // Handle the case of a templated-scope friend class. e.g.
6359 // template <class T> class A<T>::B;
6360 // FIXME: we don't support these right now.
6361 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6362 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6363 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6364 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6365 TL.setKeywordLoc(TagLoc);
6366 TL.setQualifierRange(SS.getRange());
6367 TL.setNameLoc(NameLoc);
6368
6369 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6370 TSI, FriendLoc);
6371 Friend->setAccess(AS_public);
6372 Friend->setUnsupportedFriend(true);
6373 CurContext->addDecl(Friend);
6374 return Friend;
6375}
6376
6377
John McCalldd4a3b02009-09-16 22:47:08 +00006378/// Handle a friend type declaration. This works in tandem with
6379/// ActOnTag.
6380///
6381/// Notes on friend class templates:
6382///
6383/// We generally treat friend class declarations as if they were
6384/// declaring a class. So, for example, the elaborated type specifier
6385/// in a friend declaration is required to obey the restrictions of a
6386/// class-head (i.e. no typedefs in the scope chain), template
6387/// parameters are required to match up with simple template-ids, &c.
6388/// However, unlike when declaring a template specialization, it's
6389/// okay to refer to a template specialization without an empty
6390/// template parameter declaration, e.g.
6391/// friend class A<T>::B<unsigned>;
6392/// We permit this as a special case; if there are any template
6393/// parameters present at all, require proper matching, i.e.
6394/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006395Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006396 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006397 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006398
6399 assert(DS.isFriendSpecified());
6400 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6401
John McCalldd4a3b02009-09-16 22:47:08 +00006402 // Try to convert the decl specifier to a type. This works for
6403 // friend templates because ActOnTag never produces a ClassTemplateDecl
6404 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006405 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006406 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6407 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006408 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006409 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006410
Douglas Gregor6ccab972010-12-16 01:14:37 +00006411 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6412 return 0;
6413
John McCalldd4a3b02009-09-16 22:47:08 +00006414 // This is definitely an error in C++98. It's probably meant to
6415 // be forbidden in C++0x, too, but the specification is just
6416 // poorly written.
6417 //
6418 // The problem is with declarations like the following:
6419 // template <T> friend A<T>::foo;
6420 // where deciding whether a class C is a friend or not now hinges
6421 // on whether there exists an instantiation of A that causes
6422 // 'foo' to equal C. There are restrictions on class-heads
6423 // (which we declare (by fiat) elaborated friend declarations to
6424 // be) that makes this tractable.
6425 //
6426 // FIXME: handle "template <> friend class A<T>;", which
6427 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006428 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006429 Diag(Loc, diag::err_tagless_friend_type_template)
6430 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006431 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006432 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006433
John McCall02cace72009-08-28 07:59:38 +00006434 // C++98 [class.friend]p1: A friend of a class is a function
6435 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006436 // This is fixed in DR77, which just barely didn't make the C++03
6437 // deadline. It's also a very silly restriction that seriously
6438 // affects inner classes and which nobody else seems to implement;
6439 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006440 //
6441 // But note that we could warn about it: it's always useless to
6442 // friend one of your own members (it's not, however, worthless to
6443 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006444
John McCalldd4a3b02009-09-16 22:47:08 +00006445 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006446 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006447 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006448 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006449 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006450 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006451 DS.getFriendSpecLoc());
6452 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006453 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6454
6455 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006456 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006457
John McCalldd4a3b02009-09-16 22:47:08 +00006458 D->setAccess(AS_public);
6459 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006460
John McCalld226f652010-08-21 09:40:31 +00006461 return D;
John McCall02cace72009-08-28 07:59:38 +00006462}
6463
John McCall337ec3d2010-10-12 23:13:28 +00006464Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6465 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006466 const DeclSpec &DS = D.getDeclSpec();
6467
6468 assert(DS.isFriendSpecified());
6469 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6470
6471 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006472 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6473 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006474
6475 // C++ [class.friend]p1
6476 // A friend of a class is a function or class....
6477 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006478 // It *doesn't* see through dependent types, which is correct
6479 // according to [temp.arg.type]p3:
6480 // If a declaration acquires a function type through a
6481 // type dependent on a template-parameter and this causes
6482 // a declaration that does not use the syntactic form of a
6483 // function declarator to have a function type, the program
6484 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006485 if (!T->isFunctionType()) {
6486 Diag(Loc, diag::err_unexpected_friend);
6487
6488 // It might be worthwhile to try to recover by creating an
6489 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006490 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006491 }
6492
6493 // C++ [namespace.memdef]p3
6494 // - If a friend declaration in a non-local class first declares a
6495 // class or function, the friend class or function is a member
6496 // of the innermost enclosing namespace.
6497 // - The name of the friend is not found by simple name lookup
6498 // until a matching declaration is provided in that namespace
6499 // scope (either before or after the class declaration granting
6500 // friendship).
6501 // - If a friend function is called, its name may be found by the
6502 // name lookup that considers functions from namespaces and
6503 // classes associated with the types of the function arguments.
6504 // - When looking for a prior declaration of a class or a function
6505 // declared as a friend, scopes outside the innermost enclosing
6506 // namespace scope are not considered.
6507
John McCall337ec3d2010-10-12 23:13:28 +00006508 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006509 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6510 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006511 assert(Name);
6512
Douglas Gregor6ccab972010-12-16 01:14:37 +00006513 // Check for unexpanded parameter packs.
6514 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6515 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6516 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6517 return 0;
6518
John McCall67d1a672009-08-06 02:15:43 +00006519 // The context we found the declaration in, or in which we should
6520 // create the declaration.
6521 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006522 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006523 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006524 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006525
John McCall337ec3d2010-10-12 23:13:28 +00006526 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006527
John McCall337ec3d2010-10-12 23:13:28 +00006528 // There are four cases here.
6529 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006530 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006531 // there as appropriate.
6532 // Recover from invalid scope qualifiers as if they just weren't there.
6533 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006534 // C++0x [namespace.memdef]p3:
6535 // If the name in a friend declaration is neither qualified nor
6536 // a template-id and the declaration is a function or an
6537 // elaborated-type-specifier, the lookup to determine whether
6538 // the entity has been previously declared shall not consider
6539 // any scopes outside the innermost enclosing namespace.
6540 // C++0x [class.friend]p11:
6541 // If a friend declaration appears in a local class and the name
6542 // specified is an unqualified name, a prior declaration is
6543 // looked up without considering scopes that are outside the
6544 // innermost enclosing non-class scope. For a friend function
6545 // declaration, if there is no prior declaration, the program is
6546 // ill-formed.
6547 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006548 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006549
John McCall29ae6e52010-10-13 05:45:15 +00006550 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006551 DC = CurContext;
6552 while (true) {
6553 // Skip class contexts. If someone can cite chapter and verse
6554 // for this behavior, that would be nice --- it's what GCC and
6555 // EDG do, and it seems like a reasonable intent, but the spec
6556 // really only says that checks for unqualified existing
6557 // declarations should stop at the nearest enclosing namespace,
6558 // not that they should only consider the nearest enclosing
6559 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006560 while (DC->isRecord())
6561 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006562
John McCall68263142009-11-18 22:49:29 +00006563 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006564
6565 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006566 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006567 break;
John McCall29ae6e52010-10-13 05:45:15 +00006568
John McCall8a407372010-10-14 22:22:28 +00006569 if (isTemplateId) {
6570 if (isa<TranslationUnitDecl>(DC)) break;
6571 } else {
6572 if (DC->isFileContext()) break;
6573 }
John McCall67d1a672009-08-06 02:15:43 +00006574 DC = DC->getParent();
6575 }
6576
6577 // C++ [class.friend]p1: A friend of a class is a function or
6578 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006579 // C++0x changes this for both friend types and functions.
6580 // Most C++ 98 compilers do seem to give an error here, so
6581 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006582 if (!Previous.empty() && DC->Equals(CurContext)
6583 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006584 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006585
John McCall380aaa42010-10-13 06:22:15 +00006586 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006587
John McCall337ec3d2010-10-12 23:13:28 +00006588 // - There's a non-dependent scope specifier, in which case we
6589 // compute it and do a previous lookup there for a function
6590 // or function template.
6591 } else if (!SS.getScopeRep()->isDependent()) {
6592 DC = computeDeclContext(SS);
6593 if (!DC) return 0;
6594
6595 if (RequireCompleteDeclContext(SS, DC)) return 0;
6596
6597 LookupQualifiedName(Previous, DC);
6598
6599 // Ignore things found implicitly in the wrong scope.
6600 // TODO: better diagnostics for this case. Suggesting the right
6601 // qualified scope would be nice...
6602 LookupResult::Filter F = Previous.makeFilter();
6603 while (F.hasNext()) {
6604 NamedDecl *D = F.next();
6605 if (!DC->InEnclosingNamespaceSetOf(
6606 D->getDeclContext()->getRedeclContext()))
6607 F.erase();
6608 }
6609 F.done();
6610
6611 if (Previous.empty()) {
6612 D.setInvalidType();
6613 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6614 return 0;
6615 }
6616
6617 // C++ [class.friend]p1: A friend of a class is a function or
6618 // class that is not a member of the class . . .
6619 if (DC->Equals(CurContext))
6620 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6621
6622 // - There's a scope specifier that does not match any template
6623 // parameter lists, in which case we use some arbitrary context,
6624 // create a method or method template, and wait for instantiation.
6625 // - There's a scope specifier that does match some template
6626 // parameter lists, which we don't handle right now.
6627 } else {
6628 DC = CurContext;
6629 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006630 }
6631
John McCall29ae6e52010-10-13 05:45:15 +00006632 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006633 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006634 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6635 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6636 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006637 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006638 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6639 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006640 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006641 }
John McCall67d1a672009-08-06 02:15:43 +00006642 }
6643
Douglas Gregor182ddf02009-09-28 00:08:27 +00006644 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006645 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006646 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006647 IsDefinition,
6648 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006649 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006650
Douglas Gregor182ddf02009-09-28 00:08:27 +00006651 assert(ND->getDeclContext() == DC);
6652 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006653
John McCallab88d972009-08-31 22:39:49 +00006654 // Add the function declaration to the appropriate lookup tables,
6655 // adjusting the redeclarations list as necessary. We don't
6656 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006657 //
John McCallab88d972009-08-31 22:39:49 +00006658 // Also update the scope-based lookup if the target context's
6659 // lookup context is in lexical scope.
6660 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006661 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006662 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006663 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006664 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006665 }
John McCall02cace72009-08-28 07:59:38 +00006666
6667 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006668 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006669 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006670 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006671 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006672
John McCall337ec3d2010-10-12 23:13:28 +00006673 if (ND->isInvalidDecl())
6674 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006675 else {
6676 FunctionDecl *FD;
6677 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6678 FD = FTD->getTemplatedDecl();
6679 else
6680 FD = cast<FunctionDecl>(ND);
6681
6682 // Mark templated-scope function declarations as unsupported.
6683 if (FD->getNumTemplateParameterLists())
6684 FrD->setUnsupportedFriend(true);
6685 }
John McCall337ec3d2010-10-12 23:13:28 +00006686
John McCalld226f652010-08-21 09:40:31 +00006687 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006688}
6689
John McCalld226f652010-08-21 09:40:31 +00006690void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6691 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006692
Sebastian Redl50de12f2009-03-24 22:27:57 +00006693 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6694 if (!Fn) {
6695 Diag(DelLoc, diag::err_deleted_non_function);
6696 return;
6697 }
6698 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6699 Diag(DelLoc, diag::err_deleted_decl_not_first);
6700 Diag(Prev->getLocation(), diag::note_previous_declaration);
6701 // If the declaration wasn't the first, we delete the function anyway for
6702 // recovery.
6703 }
6704 Fn->setDeleted();
6705}
Sebastian Redl13e88542009-04-27 21:33:24 +00006706
6707static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6708 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6709 ++CI) {
6710 Stmt *SubStmt = *CI;
6711 if (!SubStmt)
6712 continue;
6713 if (isa<ReturnStmt>(SubStmt))
6714 Self.Diag(SubStmt->getSourceRange().getBegin(),
6715 diag::err_return_in_constructor_handler);
6716 if (!isa<Expr>(SubStmt))
6717 SearchForReturnInStmt(Self, SubStmt);
6718 }
6719}
6720
6721void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6722 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6723 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6724 SearchForReturnInStmt(*this, Handler);
6725 }
6726}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006727
Mike Stump1eb44332009-09-09 15:08:12 +00006728bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006729 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006730 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6731 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006732
Chandler Carruth73857792010-02-15 11:53:20 +00006733 if (Context.hasSameType(NewTy, OldTy) ||
6734 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006735 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006736
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006737 // Check if the return types are covariant
6738 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006739
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006740 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006741 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6742 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006743 NewClassTy = NewPT->getPointeeType();
6744 OldClassTy = OldPT->getPointeeType();
6745 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006746 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6747 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6748 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6749 NewClassTy = NewRT->getPointeeType();
6750 OldClassTy = OldRT->getPointeeType();
6751 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006752 }
6753 }
Mike Stump1eb44332009-09-09 15:08:12 +00006754
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006755 // The return types aren't either both pointers or references to a class type.
6756 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006757 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006758 diag::err_different_return_type_for_overriding_virtual_function)
6759 << New->getDeclName() << NewTy << OldTy;
6760 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006761
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006762 return true;
6763 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006764
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006765 // C++ [class.virtual]p6:
6766 // If the return type of D::f differs from the return type of B::f, the
6767 // class type in the return type of D::f shall be complete at the point of
6768 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006769 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6770 if (!RT->isBeingDefined() &&
6771 RequireCompleteType(New->getLocation(), NewClassTy,
6772 PDiag(diag::err_covariant_return_incomplete)
6773 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006774 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006775 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006776
Douglas Gregora4923eb2009-11-16 21:35:15 +00006777 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006778 // Check if the new class derives from the old class.
6779 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6780 Diag(New->getLocation(),
6781 diag::err_covariant_return_not_derived)
6782 << New->getDeclName() << NewTy << OldTy;
6783 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6784 return true;
6785 }
Mike Stump1eb44332009-09-09 15:08:12 +00006786
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006787 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006788 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006789 diag::err_covariant_return_inaccessible_base,
6790 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6791 // FIXME: Should this point to the return type?
6792 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006793 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6794 return true;
6795 }
6796 }
Mike Stump1eb44332009-09-09 15:08:12 +00006797
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006798 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006799 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006800 Diag(New->getLocation(),
6801 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006802 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006803 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6804 return true;
6805 };
Mike Stump1eb44332009-09-09 15:08:12 +00006806
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006807
6808 // The new class type must have the same or less qualifiers as the old type.
6809 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6810 Diag(New->getLocation(),
6811 diag::err_covariant_return_type_class_type_more_qualified)
6812 << New->getDeclName() << NewTy << OldTy;
6813 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6814 return true;
6815 };
Mike Stump1eb44332009-09-09 15:08:12 +00006816
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006817 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006818}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006819
Sean Huntbbd37c62009-11-21 08:43:09 +00006820bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6821 const CXXMethodDecl *Old)
6822{
6823 if (Old->hasAttr<FinalAttr>()) {
6824 Diag(New->getLocation(), diag::err_final_function_overridden)
6825 << New->getDeclName();
6826 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6827 return true;
6828 }
6829
6830 return false;
6831}
6832
Douglas Gregor4ba31362009-12-01 17:24:26 +00006833/// \brief Mark the given method pure.
6834///
6835/// \param Method the method to be marked pure.
6836///
6837/// \param InitRange the source range that covers the "0" initializer.
6838bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6839 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6840 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006841 return false;
6842 }
6843
6844 if (!Method->isInvalidDecl())
6845 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6846 << Method->getDeclName() << InitRange;
6847 return true;
6848}
6849
John McCall731ad842009-12-19 09:28:58 +00006850/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6851/// an initializer for the out-of-line declaration 'Dcl'. The scope
6852/// is a fresh scope pushed for just this purpose.
6853///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006854/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6855/// static data member of class X, names should be looked up in the scope of
6856/// class X.
John McCalld226f652010-08-21 09:40:31 +00006857void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006858 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006859 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006860
John McCall731ad842009-12-19 09:28:58 +00006861 // We should only get called for declarations with scope specifiers, like:
6862 // int foo::bar;
6863 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006864 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006865}
6866
6867/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006868/// initializer for the out-of-line declaration 'D'.
6869void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006870 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006871 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006872
John McCall731ad842009-12-19 09:28:58 +00006873 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006874 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006875}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006876
6877/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6878/// C++ if/switch/while/for statement.
6879/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006880DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006881 // C++ 6.4p2:
6882 // The declarator shall not specify a function or an array.
6883 // The type-specifier-seq shall not contain typedef and shall not declare a
6884 // new class or enumeration.
6885 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6886 "Parser allowed 'typedef' as storage class of condition decl.");
6887
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006888 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006889 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6890 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006891
6892 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6893 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6894 // would be created and CXXConditionDeclExpr wants a VarDecl.
6895 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6896 << D.getSourceRange();
6897 return DeclResult();
6898 } else if (OwnedTag && OwnedTag->isDefinition()) {
6899 // The type-specifier-seq shall not declare a new class or enumeration.
6900 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6901 }
6902
John McCalld226f652010-08-21 09:40:31 +00006903 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006904 if (!Dcl)
6905 return DeclResult();
6906
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006907 return Dcl;
6908}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006909
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006910void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6911 bool DefinitionRequired) {
6912 // Ignore any vtable uses in unevaluated operands or for classes that do
6913 // not have a vtable.
6914 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6915 CurContext->isDependentContext() ||
6916 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006917 return;
6918
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006919 // Try to insert this class into the map.
6920 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6921 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6922 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6923 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006924 // If we already had an entry, check to see if we are promoting this vtable
6925 // to required a definition. If so, we need to reappend to the VTableUses
6926 // list, since we may have already processed the first entry.
6927 if (DefinitionRequired && !Pos.first->second) {
6928 Pos.first->second = true;
6929 } else {
6930 // Otherwise, we can early exit.
6931 return;
6932 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006933 }
6934
6935 // Local classes need to have their virtual members marked
6936 // immediately. For all other classes, we mark their virtual members
6937 // at the end of the translation unit.
6938 if (Class->isLocalClass())
6939 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006940 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006941 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006942}
6943
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006944bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006945 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006946 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00006947
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006948 // Note: The VTableUses vector could grow as a result of marking
6949 // the members of a class as "used", so we check the size each
6950 // time through the loop and prefer indices (with are stable) to
6951 // iterators (which are not).
6952 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006953 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006954 if (!Class)
6955 continue;
6956
6957 SourceLocation Loc = VTableUses[I].second;
6958
6959 // If this class has a key function, but that key function is
6960 // defined in another translation unit, we don't need to emit the
6961 // vtable even though we're using it.
6962 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006963 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006964 switch (KeyFunction->getTemplateSpecializationKind()) {
6965 case TSK_Undeclared:
6966 case TSK_ExplicitSpecialization:
6967 case TSK_ExplicitInstantiationDeclaration:
6968 // The key function is in another translation unit.
6969 continue;
6970
6971 case TSK_ExplicitInstantiationDefinition:
6972 case TSK_ImplicitInstantiation:
6973 // We will be instantiating the key function.
6974 break;
6975 }
6976 } else if (!KeyFunction) {
6977 // If we have a class with no key function that is the subject
6978 // of an explicit instantiation declaration, suppress the
6979 // vtable; it will live with the explicit instantiation
6980 // definition.
6981 bool IsExplicitInstantiationDeclaration
6982 = Class->getTemplateSpecializationKind()
6983 == TSK_ExplicitInstantiationDeclaration;
6984 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6985 REnd = Class->redecls_end();
6986 R != REnd; ++R) {
6987 TemplateSpecializationKind TSK
6988 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6989 if (TSK == TSK_ExplicitInstantiationDeclaration)
6990 IsExplicitInstantiationDeclaration = true;
6991 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6992 IsExplicitInstantiationDeclaration = false;
6993 break;
6994 }
6995 }
6996
6997 if (IsExplicitInstantiationDeclaration)
6998 continue;
6999 }
7000
7001 // Mark all of the virtual members of this class as referenced, so
7002 // that we can build a vtable. Then, tell the AST consumer that a
7003 // vtable for this class is required.
7004 MarkVirtualMembersReferenced(Loc, Class);
7005 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7006 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7007
7008 // Optionally warn if we're emitting a weak vtable.
7009 if (Class->getLinkage() == ExternalLinkage &&
7010 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007011 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007012 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7013 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007014 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007015 VTableUses.clear();
7016
Anders Carlssond6a637f2009-12-07 08:24:59 +00007017 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007018}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007019
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007020void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7021 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007022 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7023 e = RD->method_end(); i != e; ++i) {
7024 CXXMethodDecl *MD = *i;
7025
7026 // C++ [basic.def.odr]p2:
7027 // [...] A virtual member function is used if it is not pure. [...]
7028 if (MD->isVirtual() && !MD->isPure())
7029 MarkDeclarationReferenced(Loc, MD);
7030 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007031
7032 // Only classes that have virtual bases need a VTT.
7033 if (RD->getNumVBases() == 0)
7034 return;
7035
7036 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7037 e = RD->bases_end(); i != e; ++i) {
7038 const CXXRecordDecl *Base =
7039 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007040 if (Base->getNumVBases() == 0)
7041 continue;
7042 MarkVirtualMembersReferenced(Loc, Base);
7043 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007044}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007045
7046/// SetIvarInitializers - This routine builds initialization ASTs for the
7047/// Objective-C implementation whose ivars need be initialized.
7048void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7049 if (!getLangOptions().CPlusPlus)
7050 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007051 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007052 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7053 CollectIvarsToConstructOrDestruct(OID, ivars);
7054 if (ivars.empty())
7055 return;
7056 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7057 for (unsigned i = 0; i < ivars.size(); i++) {
7058 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007059 if (Field->isInvalidDecl())
7060 continue;
7061
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007062 CXXBaseOrMemberInitializer *Member;
7063 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7064 InitializationKind InitKind =
7065 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7066
7067 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007068 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007069 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007070 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007071 // Note, MemberInit could actually come back empty if no initialization
7072 // is required (e.g., because it would call a trivial default constructor)
7073 if (!MemberInit.get() || MemberInit.isInvalid())
7074 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007075
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007076 Member =
7077 new (Context) CXXBaseOrMemberInitializer(Context,
7078 Field, SourceLocation(),
7079 SourceLocation(),
7080 MemberInit.takeAs<Expr>(),
7081 SourceLocation());
7082 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007083
7084 // Be sure that the destructor is accessible and is marked as referenced.
7085 if (const RecordType *RecordTy
7086 = Context.getBaseElementType(Field->getType())
7087 ->getAs<RecordType>()) {
7088 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007089 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007090 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7091 CheckDestructorAccess(Field->getLocation(), Destructor,
7092 PDiag(diag::err_access_dtor_ivar)
7093 << Context.getBaseElementType(Field->getType()));
7094 }
7095 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007096 }
7097 ObjCImplementation->setIvarInitializers(Context,
7098 AllToInit.data(), AllToInit.size());
7099 }
7100}