blob: 0021c798235219b18c09ca98efe9940aabd7d0e0 [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
Douglas Gregor6fb07292010-12-21 07:41:49 +00004055 if (!NamedContext->isDependentContext() &&
4056 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4057 return true;
4058
John McCall604e7f12009-12-08 07:46:18 +00004059 if (getLangOptions().CPlusPlus0x) {
4060 // C++0x [namespace.udecl]p3:
4061 // In a using-declaration used as a member-declaration, the
4062 // nested-name-specifier shall name a base class of the class
4063 // being defined.
4064
4065 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4066 cast<CXXRecordDecl>(NamedContext))) {
4067 if (CurContext == NamedContext) {
4068 Diag(NameLoc,
4069 diag::err_using_decl_nested_name_specifier_is_current_class)
4070 << SS.getRange();
4071 return true;
4072 }
4073
4074 Diag(SS.getRange().getBegin(),
4075 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4076 << (NestedNameSpecifier*) SS.getScopeRep()
4077 << cast<CXXRecordDecl>(CurContext)
4078 << SS.getRange();
4079 return true;
4080 }
4081
4082 return false;
4083 }
4084
4085 // C++03 [namespace.udecl]p4:
4086 // A using-declaration used as a member-declaration shall refer
4087 // to a member of a base class of the class being defined [etc.].
4088
4089 // Salient point: SS doesn't have to name a base class as long as
4090 // lookup only finds members from base classes. Therefore we can
4091 // diagnose here only if we can prove that that can't happen,
4092 // i.e. if the class hierarchies provably don't intersect.
4093
4094 // TODO: it would be nice if "definitely valid" results were cached
4095 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4096 // need to be repeated.
4097
4098 struct UserData {
4099 llvm::DenseSet<const CXXRecordDecl*> Bases;
4100
4101 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4102 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4103 Data->Bases.insert(Base);
4104 return true;
4105 }
4106
4107 bool hasDependentBases(const CXXRecordDecl *Class) {
4108 return !Class->forallBases(collect, this);
4109 }
4110
4111 /// Returns true if the base is dependent or is one of the
4112 /// accumulated base classes.
4113 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4114 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4115 return !Data->Bases.count(Base);
4116 }
4117
4118 bool mightShareBases(const CXXRecordDecl *Class) {
4119 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4120 }
4121 };
4122
4123 UserData Data;
4124
4125 // Returns false if we find a dependent base.
4126 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4127 return false;
4128
4129 // Returns false if the class has a dependent base or if it or one
4130 // of its bases is present in the base set of the current context.
4131 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4132 return false;
4133
4134 Diag(SS.getRange().getBegin(),
4135 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4136 << (NestedNameSpecifier*) SS.getScopeRep()
4137 << cast<CXXRecordDecl>(CurContext)
4138 << SS.getRange();
4139
4140 return true;
John McCalled976492009-12-04 22:46:56 +00004141}
4142
John McCalld226f652010-08-21 09:40:31 +00004143Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004144 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004145 SourceLocation AliasLoc,
4146 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004147 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004148 SourceLocation IdentLoc,
4149 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004150
Anders Carlsson81c85c42009-03-28 23:53:49 +00004151 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004152 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4153 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004154
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004155 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004156 NamedDecl *PrevDecl
4157 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4158 ForRedeclaration);
4159 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4160 PrevDecl = 0;
4161
4162 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004163 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004164 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004165 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004166 // FIXME: At some point, we'll want to create the (redundant)
4167 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004168 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004169 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004170 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004171 }
Mike Stump1eb44332009-09-09 15:08:12 +00004172
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004173 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4174 diag::err_redefinition_different_kind;
4175 Diag(AliasLoc, DiagID) << Alias;
4176 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004177 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004178 }
4179
John McCalla24dc2e2009-11-17 02:14:36 +00004180 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004181 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004182
John McCallf36e02d2009-10-09 21:13:30 +00004183 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004184 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4185 CTC_NoKeywords, 0)) {
4186 if (R.getAsSingle<NamespaceDecl>() ||
4187 R.getAsSingle<NamespaceAliasDecl>()) {
4188 if (DeclContext *DC = computeDeclContext(SS, false))
4189 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4190 << Ident << DC << Corrected << SS.getRange()
4191 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4192 else
4193 Diag(IdentLoc, diag::err_using_directive_suggest)
4194 << Ident << Corrected
4195 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4196
4197 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4198 << Corrected;
4199
4200 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004201 } else {
4202 R.clear();
4203 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004204 }
4205 }
4206
4207 if (R.empty()) {
4208 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004209 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004210 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004211 }
Mike Stump1eb44332009-09-09 15:08:12 +00004212
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004213 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004214 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4215 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004216 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004217 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004218
John McCall3dbd3d52010-02-16 06:53:13 +00004219 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004220 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004221}
4222
Douglas Gregor39957dc2010-05-01 15:04:51 +00004223namespace {
4224 /// \brief Scoped object used to handle the state changes required in Sema
4225 /// to implicitly define the body of a C++ member function;
4226 class ImplicitlyDefinedFunctionScope {
4227 Sema &S;
4228 DeclContext *PreviousContext;
4229
4230 public:
4231 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4232 : S(S), PreviousContext(S.CurContext)
4233 {
4234 S.CurContext = Method;
4235 S.PushFunctionScope();
4236 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4237 }
4238
4239 ~ImplicitlyDefinedFunctionScope() {
4240 S.PopExpressionEvaluationContext();
4241 S.PopFunctionOrBlockScope();
4242 S.CurContext = PreviousContext;
4243 }
4244 };
4245}
4246
Sebastian Redl751025d2010-09-13 22:02:47 +00004247static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4248 CXXRecordDecl *D) {
4249 ASTContext &Context = Self.Context;
4250 QualType ClassType = Context.getTypeDeclType(D);
4251 DeclarationName ConstructorName
4252 = Context.DeclarationNames.getCXXConstructorName(
4253 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4254
4255 DeclContext::lookup_const_iterator Con, ConEnd;
4256 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4257 Con != ConEnd; ++Con) {
4258 // FIXME: In C++0x, a constructor template can be a default constructor.
4259 if (isa<FunctionTemplateDecl>(*Con))
4260 continue;
4261
4262 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4263 if (Constructor->isDefaultConstructor())
4264 return Constructor;
4265 }
4266 return 0;
4267}
4268
Douglas Gregor23c94db2010-07-02 17:43:08 +00004269CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4270 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004271 // C++ [class.ctor]p5:
4272 // A default constructor for a class X is a constructor of class X
4273 // that can be called without an argument. If there is no
4274 // user-declared constructor for class X, a default constructor is
4275 // implicitly declared. An implicitly-declared default constructor
4276 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004277 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4278 "Should not build implicit default constructor!");
4279
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004280 // C++ [except.spec]p14:
4281 // An implicitly declared special member function (Clause 12) shall have an
4282 // exception-specification. [...]
4283 ImplicitExceptionSpecification ExceptSpec(Context);
4284
4285 // Direct base-class destructors.
4286 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4287 BEnd = ClassDecl->bases_end();
4288 B != BEnd; ++B) {
4289 if (B->isVirtual()) // Handled below.
4290 continue;
4291
Douglas Gregor18274032010-07-03 00:47:00 +00004292 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4293 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4294 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4295 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004296 else if (CXXConstructorDecl *Constructor
4297 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004298 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004299 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004300 }
4301
4302 // Virtual base-class destructors.
4303 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4304 BEnd = ClassDecl->vbases_end();
4305 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004306 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4307 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4308 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4309 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4310 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004311 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004312 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004313 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004314 }
4315
4316 // Field destructors.
4317 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4318 FEnd = ClassDecl->field_end();
4319 F != FEnd; ++F) {
4320 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004321 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4322 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4323 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4324 ExceptSpec.CalledDecl(
4325 DeclareImplicitDefaultConstructor(FieldClassDecl));
4326 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004327 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004328 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004329 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004330 }
John McCalle23cf432010-12-14 08:05:40 +00004331
4332 FunctionProtoType::ExtProtoInfo EPI;
4333 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4334 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4335 EPI.NumExceptions = ExceptSpec.size();
4336 EPI.Exceptions = ExceptSpec.data();
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004337
4338 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004339 CanQualType ClassType
4340 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4341 DeclarationName Name
4342 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004343 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004344 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004345 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004346 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00004347 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004348 /*TInfo=*/0,
4349 /*isExplicit=*/false,
4350 /*isInline=*/true,
4351 /*isImplicitlyDeclared=*/true);
4352 DefaultCon->setAccess(AS_public);
4353 DefaultCon->setImplicit();
4354 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004355
4356 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00004357 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4358
Douglas Gregor23c94db2010-07-02 17:43:08 +00004359 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004360 PushOnScopeChains(DefaultCon, S, false);
4361 ClassDecl->addDecl(DefaultCon);
4362
Douglas Gregor32df23e2010-07-01 22:02:46 +00004363 return DefaultCon;
4364}
4365
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004366void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4367 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004368 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004369 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004370 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004372 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004373 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004374
Douglas Gregor39957dc2010-05-01 15:04:51 +00004375 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004376 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004377 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4378 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004379 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004380 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004381 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004382 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00004383 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004384
4385 SourceLocation Loc = Constructor->getLocation();
4386 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4387
4388 Constructor->setUsed();
4389 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004390}
4391
Douglas Gregor23c94db2010-07-02 17:43:08 +00004392CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004393 // C++ [class.dtor]p2:
4394 // If a class has no user-declared destructor, a destructor is
4395 // declared implicitly. An implicitly-declared destructor is an
4396 // inline public member of its class.
4397
4398 // C++ [except.spec]p14:
4399 // An implicitly declared special member function (Clause 12) shall have
4400 // an exception-specification.
4401 ImplicitExceptionSpecification ExceptSpec(Context);
4402
4403 // Direct base-class destructors.
4404 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4405 BEnd = ClassDecl->bases_end();
4406 B != BEnd; ++B) {
4407 if (B->isVirtual()) // Handled below.
4408 continue;
4409
4410 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4411 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004412 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004413 }
4414
4415 // Virtual base-class destructors.
4416 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4417 BEnd = ClassDecl->vbases_end();
4418 B != BEnd; ++B) {
4419 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4420 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004421 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004422 }
4423
4424 // Field destructors.
4425 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4426 FEnd = ClassDecl->field_end();
4427 F != FEnd; ++F) {
4428 if (const RecordType *RecordTy
4429 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4430 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004431 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004432 }
4433
Douglas Gregor4923aa22010-07-02 20:37:36 +00004434 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00004435 FunctionProtoType::ExtProtoInfo EPI;
4436 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4437 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4438 EPI.NumExceptions = ExceptSpec.size();
4439 EPI.Exceptions = ExceptSpec.data();
4440 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004441
4442 CanQualType ClassType
4443 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4444 DeclarationName Name
4445 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004446 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004447 CXXDestructorDecl *Destructor
Craig Silversteinb41d8992010-10-21 00:44:50 +00004448 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004449 /*isInline=*/true,
4450 /*isImplicitlyDeclared=*/true);
4451 Destructor->setAccess(AS_public);
4452 Destructor->setImplicit();
4453 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004454
4455 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00004456 ++ASTContext::NumImplicitDestructorsDeclared;
4457
4458 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004459 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004460 PushOnScopeChains(Destructor, S, false);
4461 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004462
4463 // This could be uniqued if it ever proves significant.
4464 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4465
4466 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004467
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004468 return Destructor;
4469}
4470
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004471void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004472 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004473 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004474 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004475 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004476 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004477
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004478 if (Destructor->isInvalidDecl())
4479 return;
4480
Douglas Gregor39957dc2010-05-01 15:04:51 +00004481 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004482
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004483 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00004484 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4485 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004487 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004488 Diag(CurrentLocation, diag::note_member_synthesized_at)
4489 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4490
4491 Destructor->setInvalidDecl();
4492 return;
4493 }
4494
Douglas Gregor4ada9d32010-09-20 16:48:21 +00004495 SourceLocation Loc = Destructor->getLocation();
4496 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4497
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004498 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004499 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004500}
4501
Douglas Gregor06a9f362010-05-01 20:49:11 +00004502/// \brief Builds a statement that copies the given entity from \p From to
4503/// \c To.
4504///
4505/// This routine is used to copy the members of a class with an
4506/// implicitly-declared copy assignment operator. When the entities being
4507/// copied are arrays, this routine builds for loops to copy them.
4508///
4509/// \param S The Sema object used for type-checking.
4510///
4511/// \param Loc The location where the implicit copy is being generated.
4512///
4513/// \param T The type of the expressions being copied. Both expressions must
4514/// have this type.
4515///
4516/// \param To The expression we are copying to.
4517///
4518/// \param From The expression we are copying from.
4519///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004520/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4521/// Otherwise, it's a non-static member subobject.
4522///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004523/// \param Depth Internal parameter recording the depth of the recursion.
4524///
4525/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004526static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004527BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004528 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004529 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004530 // C++0x [class.copy]p30:
4531 // Each subobject is assigned in the manner appropriate to its type:
4532 //
4533 // - if the subobject is of class type, the copy assignment operator
4534 // for the class is used (as if by explicit qualification; that is,
4535 // ignoring any possible virtual overriding functions in more derived
4536 // classes);
4537 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4538 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4539
4540 // Look for operator=.
4541 DeclarationName Name
4542 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4543 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4544 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4545
4546 // Filter out any result that isn't a copy-assignment operator.
4547 LookupResult::Filter F = OpLookup.makeFilter();
4548 while (F.hasNext()) {
4549 NamedDecl *D = F.next();
4550 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4551 if (Method->isCopyAssignmentOperator())
4552 continue;
4553
4554 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004555 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004556 F.done();
4557
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004558 // Suppress the protected check (C++ [class.protected]) for each of the
4559 // assignment operators we found. This strange dance is required when
4560 // we're assigning via a base classes's copy-assignment operator. To
4561 // ensure that we're getting the right base class subobject (without
4562 // ambiguities), we need to cast "this" to that subobject type; to
4563 // ensure that we don't go through the virtual call mechanism, we need
4564 // to qualify the operator= name with the base class (see below). However,
4565 // this means that if the base class has a protected copy assignment
4566 // operator, the protected member access check will fail. So, we
4567 // rewrite "protected" access to "public" access in this case, since we
4568 // know by construction that we're calling from a derived class.
4569 if (CopyingBaseSubobject) {
4570 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4571 L != LEnd; ++L) {
4572 if (L.getAccess() == AS_protected)
4573 L.setAccess(AS_public);
4574 }
4575 }
4576
Douglas Gregor06a9f362010-05-01 20:49:11 +00004577 // Create the nested-name-specifier that will be used to qualify the
4578 // reference to operator=; this is required to suppress the virtual
4579 // call mechanism.
4580 CXXScopeSpec SS;
4581 SS.setRange(Loc);
4582 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4583 T.getTypePtr()));
4584
4585 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004586 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004587 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004588 /*FirstQualifierInScope=*/0, OpLookup,
4589 /*TemplateArgs=*/0,
4590 /*SuppressQualifierCheck=*/true);
4591 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004592 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004593
4594 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004595
John McCall60d7b3a2010-08-24 06:29:42 +00004596 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004597 OpEqualRef.takeAs<Expr>(),
4598 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004599 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004600 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004601
4602 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004603 }
John McCallb0207482010-03-16 06:11:48 +00004604
Douglas Gregor06a9f362010-05-01 20:49:11 +00004605 // - if the subobject is of scalar type, the built-in assignment
4606 // operator is used.
4607 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4608 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004609 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004610 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004611 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004612
4613 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004614 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004615
4616 // - if the subobject is an array, each element is assigned, in the
4617 // manner appropriate to the element type;
4618
4619 // Construct a loop over the array bounds, e.g.,
4620 //
4621 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4622 //
4623 // that will copy each of the array elements.
4624 QualType SizeType = S.Context.getSizeType();
4625
4626 // Create the iteration variable.
4627 IdentifierInfo *IterationVarName = 0;
4628 {
4629 llvm::SmallString<8> Str;
4630 llvm::raw_svector_ostream OS(Str);
4631 OS << "__i" << Depth;
4632 IterationVarName = &S.Context.Idents.get(OS.str());
4633 }
4634 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4635 IterationVarName, SizeType,
4636 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004637 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004638
4639 // Initialize the iteration variable to zero.
4640 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004641 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004642
4643 // Create a reference to the iteration variable; we'll use this several
4644 // times throughout.
4645 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00004646 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004647 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4648
4649 // Create the DeclStmt that holds the iteration variable.
4650 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4651
4652 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004653 llvm::APInt Upper
4654 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004655 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00004656 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00004657 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4658 BO_NE, S.Context.BoolTy,
4659 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004660
4661 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004662 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00004663 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4664 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004665
4666 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004667 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4668 IterationVarRef, Loc));
4669 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4670 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004671
4672 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00004673 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4674 To, From, CopyingBaseSubobject,
4675 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004676 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004677 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004678
4679 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004680 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004681 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004682 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004683 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004684}
4685
Douglas Gregora376d102010-07-02 21:50:04 +00004686/// \brief Determine whether the given class has a copy assignment operator
4687/// that accepts a const-qualified argument.
4688static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4689 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4690
4691 if (!Class->hasDeclaredCopyAssignment())
4692 S.DeclareImplicitCopyAssignment(Class);
4693
4694 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4695 DeclarationName OpName
4696 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4697
4698 DeclContext::lookup_const_iterator Op, OpEnd;
4699 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4700 // C++ [class.copy]p9:
4701 // A user-declared copy assignment operator is a non-static non-template
4702 // member function of class X with exactly one parameter of type X, X&,
4703 // const X&, volatile X& or const volatile X&.
4704 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4705 if (!Method)
4706 continue;
4707
4708 if (Method->isStatic())
4709 continue;
4710 if (Method->getPrimaryTemplate())
4711 continue;
4712 const FunctionProtoType *FnType =
4713 Method->getType()->getAs<FunctionProtoType>();
4714 assert(FnType && "Overloaded operator has no prototype.");
4715 // Don't assert on this; an invalid decl might have been left in the AST.
4716 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4717 continue;
4718 bool AcceptsConst = true;
4719 QualType ArgType = FnType->getArgType(0);
4720 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4721 ArgType = Ref->getPointeeType();
4722 // Is it a non-const lvalue reference?
4723 if (!ArgType.isConstQualified())
4724 AcceptsConst = false;
4725 }
4726 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4727 continue;
4728
4729 // We have a single argument of type cv X or cv X&, i.e. we've found the
4730 // copy assignment operator. Return whether it accepts const arguments.
4731 return AcceptsConst;
4732 }
4733 assert(Class->isInvalidDecl() &&
4734 "No copy assignment operator declared in valid code.");
4735 return false;
4736}
4737
Douglas Gregor23c94db2010-07-02 17:43:08 +00004738CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004739 // Note: The following rules are largely analoguous to the copy
4740 // constructor rules. Note that virtual bases are not taken into account
4741 // for determining the argument type of the operator. Note also that
4742 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004743
4744
Douglas Gregord3c35902010-07-01 16:36:15 +00004745 // C++ [class.copy]p10:
4746 // If the class definition does not explicitly declare a copy
4747 // assignment operator, one is declared implicitly.
4748 // The implicitly-defined copy assignment operator for a class X
4749 // will have the form
4750 //
4751 // X& X::operator=(const X&)
4752 //
4753 // if
4754 bool HasConstCopyAssignment = true;
4755
4756 // -- each direct base class B of X has a copy assignment operator
4757 // whose parameter is of type const B&, const volatile B& or B,
4758 // and
4759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4760 BaseEnd = ClassDecl->bases_end();
4761 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4762 assert(!Base->getType()->isDependentType() &&
4763 "Cannot generate implicit members for class with dependent bases.");
4764 const CXXRecordDecl *BaseClassDecl
4765 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004766 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004767 }
4768
4769 // -- for all the nonstatic data members of X that are of a class
4770 // type M (or array thereof), each such class type has a copy
4771 // assignment operator whose parameter is of type const M&,
4772 // const volatile M& or M.
4773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4774 FieldEnd = ClassDecl->field_end();
4775 HasConstCopyAssignment && Field != FieldEnd;
4776 ++Field) {
4777 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4778 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4779 const CXXRecordDecl *FieldClassDecl
4780 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004781 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004782 }
4783 }
4784
4785 // Otherwise, the implicitly declared copy assignment operator will
4786 // have the form
4787 //
4788 // X& X::operator=(X&)
4789 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4790 QualType RetType = Context.getLValueReferenceType(ArgType);
4791 if (HasConstCopyAssignment)
4792 ArgType = ArgType.withConst();
4793 ArgType = Context.getLValueReferenceType(ArgType);
4794
Douglas Gregorb87786f2010-07-01 17:48:08 +00004795 // C++ [except.spec]p14:
4796 // An implicitly declared special member function (Clause 12) shall have an
4797 // exception-specification. [...]
4798 ImplicitExceptionSpecification ExceptSpec(Context);
4799 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4800 BaseEnd = ClassDecl->bases_end();
4801 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004802 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004803 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004804
4805 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4806 DeclareImplicitCopyAssignment(BaseClassDecl);
4807
Douglas Gregorb87786f2010-07-01 17:48:08 +00004808 if (CXXMethodDecl *CopyAssign
4809 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4810 ExceptSpec.CalledDecl(CopyAssign);
4811 }
4812 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4813 FieldEnd = ClassDecl->field_end();
4814 Field != FieldEnd;
4815 ++Field) {
4816 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4817 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004818 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004819 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004820
4821 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4822 DeclareImplicitCopyAssignment(FieldClassDecl);
4823
Douglas Gregorb87786f2010-07-01 17:48:08 +00004824 if (CXXMethodDecl *CopyAssign
4825 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4826 ExceptSpec.CalledDecl(CopyAssign);
4827 }
4828 }
4829
Douglas Gregord3c35902010-07-01 16:36:15 +00004830 // An implicitly-declared copy assignment operator is an inline public
4831 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00004832 FunctionProtoType::ExtProtoInfo EPI;
4833 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4834 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4835 EPI.NumExceptions = ExceptSpec.size();
4836 EPI.Exceptions = ExceptSpec.data();
Douglas Gregord3c35902010-07-01 16:36:15 +00004837 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004838 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004839 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004840 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00004841 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00004842 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004843 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004844 /*isInline=*/true);
4845 CopyAssignment->setAccess(AS_public);
4846 CopyAssignment->setImplicit();
4847 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00004848
4849 // Add the parameter to the operator.
4850 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4851 ClassDecl->getLocation(),
4852 /*Id=*/0,
4853 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004854 SC_None,
4855 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004856 CopyAssignment->setParams(&FromParam, 1);
4857
Douglas Gregora376d102010-07-02 21:50:04 +00004858 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00004859 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4860
Douglas Gregor23c94db2010-07-02 17:43:08 +00004861 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004862 PushOnScopeChains(CopyAssignment, S, false);
4863 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004864
4865 AddOverriddenMethods(ClassDecl, CopyAssignment);
4866 return CopyAssignment;
4867}
4868
Douglas Gregor06a9f362010-05-01 20:49:11 +00004869void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4870 CXXMethodDecl *CopyAssignOperator) {
4871 assert((CopyAssignOperator->isImplicit() &&
4872 CopyAssignOperator->isOverloadedOperator() &&
4873 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004874 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004875 "DefineImplicitCopyAssignment called for wrong function");
4876
4877 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4878
4879 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4880 CopyAssignOperator->setInvalidDecl();
4881 return;
4882 }
4883
4884 CopyAssignOperator->setUsed();
4885
4886 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00004887 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004888
4889 // C++0x [class.copy]p30:
4890 // The implicitly-defined or explicitly-defaulted copy assignment operator
4891 // for a non-union class X performs memberwise copy assignment of its
4892 // subobjects. The direct base classes of X are assigned first, in the
4893 // order of their declaration in the base-specifier-list, and then the
4894 // immediate non-static data members of X are assigned, in the order in
4895 // which they were declared in the class definition.
4896
4897 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004898 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004899
4900 // The parameter for the "other" object, which we are copying from.
4901 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4902 Qualifiers OtherQuals = Other->getType().getQualifiers();
4903 QualType OtherRefType = Other->getType();
4904 if (const LValueReferenceType *OtherRef
4905 = OtherRefType->getAs<LValueReferenceType>()) {
4906 OtherRefType = OtherRef->getPointeeType();
4907 OtherQuals = OtherRefType.getQualifiers();
4908 }
4909
4910 // Our location for everything implicitly-generated.
4911 SourceLocation Loc = CopyAssignOperator->getLocation();
4912
4913 // Construct a reference to the "other" object. We'll be using this
4914 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00004915 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004916 assert(OtherRef && "Reference to parameter cannot fail!");
4917
4918 // Construct the "this" pointer. We'll be using this throughout the generated
4919 // ASTs.
4920 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4921 assert(This && "Reference to this cannot fail!");
4922
4923 // Assign base classes.
4924 bool Invalid = false;
4925 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4926 E = ClassDecl->bases_end(); Base != E; ++Base) {
4927 // Form the assignment:
4928 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4929 QualType BaseType = Base->getType().getUnqualifiedType();
4930 CXXRecordDecl *BaseClassDecl = 0;
4931 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4932 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4933 else {
4934 Invalid = true;
4935 continue;
4936 }
4937
John McCallf871d0c2010-08-07 06:22:56 +00004938 CXXCastPath BasePath;
4939 BasePath.push_back(Base);
4940
Douglas Gregor06a9f362010-05-01 20:49:11 +00004941 // Construct the "from" expression, which is an implicit cast to the
4942 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00004943 Expr *From = OtherRef;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004944 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004945 CK_UncheckedDerivedToBase,
4946 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004947
4948 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004949 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004950
4951 // Implicitly cast "this" to the appropriately-qualified base type.
4952 Expr *ToE = To.takeAs<Expr>();
4953 ImpCastExprToType(ToE,
4954 Context.getCVRQualifiedType(BaseType,
4955 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004956 CK_UncheckedDerivedToBase,
4957 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004958 To = Owned(ToE);
4959
4960 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004961 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004962 To.get(), From,
4963 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004964 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004965 Diag(CurrentLocation, diag::note_member_synthesized_at)
4966 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4967 CopyAssignOperator->setInvalidDecl();
4968 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004969 }
4970
4971 // Success! Record the copy.
4972 Statements.push_back(Copy.takeAs<Expr>());
4973 }
4974
4975 // \brief Reference to the __builtin_memcpy function.
4976 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00004977 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00004978 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00004979
4980 // Assign non-static members.
4981 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4982 FieldEnd = ClassDecl->field_end();
4983 Field != FieldEnd; ++Field) {
4984 // Check for members of reference type; we can't copy those.
4985 if (Field->getType()->isReferenceType()) {
4986 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4987 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4988 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004989 Diag(CurrentLocation, diag::note_member_synthesized_at)
4990 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004991 Invalid = true;
4992 continue;
4993 }
4994
4995 // Check for members of const-qualified, non-class type.
4996 QualType BaseType = Context.getBaseElementType(Field->getType());
4997 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4998 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4999 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5000 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005001 Diag(CurrentLocation, diag::note_member_synthesized_at)
5002 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005003 Invalid = true;
5004 continue;
5005 }
5006
5007 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005008 if (FieldType->isIncompleteArrayType()) {
5009 assert(ClassDecl->hasFlexibleArrayMember() &&
5010 "Incomplete array type is not valid");
5011 continue;
5012 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005013
5014 // Build references to the field in the object we're copying from and to.
5015 CXXScopeSpec SS; // Intentionally empty
5016 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5017 LookupMemberName);
5018 MemberLookup.addDecl(*Field);
5019 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005020 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00005021 Loc, /*IsArrow=*/false,
5022 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005023 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00005024 Loc, /*IsArrow=*/true,
5025 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005026 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5027 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5028
5029 // If the field should be copied with __builtin_memcpy rather than via
5030 // explicit assignments, do so. This optimization only applies for arrays
5031 // of scalars and arrays of class type with trivial copy-assignment
5032 // operators.
5033 if (FieldType->isArrayType() &&
5034 (!BaseType->isRecordType() ||
5035 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5036 ->hasTrivialCopyAssignment())) {
5037 // Compute the size of the memory buffer to be copied.
5038 QualType SizeType = Context.getSizeType();
5039 llvm::APInt Size(Context.getTypeSize(SizeType),
5040 Context.getTypeSizeInChars(BaseType).getQuantity());
5041 for (const ConstantArrayType *Array
5042 = Context.getAsConstantArrayType(FieldType);
5043 Array;
5044 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00005045 llvm::APInt ArraySize
5046 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005047 Size *= ArraySize;
5048 }
5049
5050 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005051 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5052 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005053
5054 bool NeedsCollectableMemCpy =
5055 (BaseType->isRecordType() &&
5056 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5057
5058 if (NeedsCollectableMemCpy) {
5059 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005060 // Create a reference to the __builtin_objc_memmove_collectable function.
5061 LookupResult R(*this,
5062 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005063 Loc, LookupOrdinaryName);
5064 LookupName(R, TUScope, true);
5065
5066 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5067 if (!CollectableMemCpy) {
5068 // Something went horribly wrong earlier, and we will have
5069 // complained about it.
5070 Invalid = true;
5071 continue;
5072 }
5073
5074 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5075 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005076 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005077 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5078 }
5079 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005080 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005081 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005082 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5083 LookupOrdinaryName);
5084 LookupName(R, TUScope, true);
5085
5086 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5087 if (!BuiltinMemCpy) {
5088 // Something went horribly wrong earlier, and we will have complained
5089 // about it.
5090 Invalid = true;
5091 continue;
5092 }
5093
5094 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5095 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005096 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00005097 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5098 }
5099
John McCallca0408f2010-08-23 06:44:23 +00005100 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005101 CallArgs.push_back(To.takeAs<Expr>());
5102 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005103 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005104 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005105 if (NeedsCollectableMemCpy)
5106 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005107 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005108 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005109 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005110 else
5111 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005112 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005113 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005114 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005115
Douglas Gregor06a9f362010-05-01 20:49:11 +00005116 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5117 Statements.push_back(Call.takeAs<Expr>());
5118 continue;
5119 }
5120
5121 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005122 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005123 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005124 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005125 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005126 Diag(CurrentLocation, diag::note_member_synthesized_at)
5127 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5128 CopyAssignOperator->setInvalidDecl();
5129 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005130 }
5131
5132 // Success! Record the copy.
5133 Statements.push_back(Copy.takeAs<Stmt>());
5134 }
5135
5136 if (!Invalid) {
5137 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005138 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005139
John McCall60d7b3a2010-08-24 06:29:42 +00005140 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005141 if (Return.isInvalid())
5142 Invalid = true;
5143 else {
5144 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005145
5146 if (Trap.hasErrorOccurred()) {
5147 Diag(CurrentLocation, diag::note_member_synthesized_at)
5148 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5149 Invalid = true;
5150 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005151 }
5152 }
5153
5154 if (Invalid) {
5155 CopyAssignOperator->setInvalidDecl();
5156 return;
5157 }
5158
John McCall60d7b3a2010-08-24 06:29:42 +00005159 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005160 /*isStmtExpr=*/false);
5161 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5162 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005163}
5164
Douglas Gregor23c94db2010-07-02 17:43:08 +00005165CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5166 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005167 // C++ [class.copy]p4:
5168 // If the class definition does not explicitly declare a copy
5169 // constructor, one is declared implicitly.
5170
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005171 // C++ [class.copy]p5:
5172 // The implicitly-declared copy constructor for a class X will
5173 // have the form
5174 //
5175 // X::X(const X&)
5176 //
5177 // if
5178 bool HasConstCopyConstructor = true;
5179
5180 // -- each direct or virtual base class B of X has a copy
5181 // constructor whose first parameter is of type const B& or
5182 // const volatile B&, and
5183 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5184 BaseEnd = ClassDecl->bases_end();
5185 HasConstCopyConstructor && Base != BaseEnd;
5186 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005187 // Virtual bases are handled below.
5188 if (Base->isVirtual())
5189 continue;
5190
Douglas Gregor22584312010-07-02 23:41:54 +00005191 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005192 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005193 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5194 DeclareImplicitCopyConstructor(BaseClassDecl);
5195
Douglas Gregor598a8542010-07-01 18:27:03 +00005196 HasConstCopyConstructor
5197 = BaseClassDecl->hasConstCopyConstructor(Context);
5198 }
5199
5200 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5201 BaseEnd = ClassDecl->vbases_end();
5202 HasConstCopyConstructor && Base != BaseEnd;
5203 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005204 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005205 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005206 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5207 DeclareImplicitCopyConstructor(BaseClassDecl);
5208
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005209 HasConstCopyConstructor
5210 = BaseClassDecl->hasConstCopyConstructor(Context);
5211 }
5212
5213 // -- for all the nonstatic data members of X that are of a
5214 // class type M (or array thereof), each such class type
5215 // has a copy constructor whose first parameter is of type
5216 // const M& or const volatile M&.
5217 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5218 FieldEnd = ClassDecl->field_end();
5219 HasConstCopyConstructor && Field != FieldEnd;
5220 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005221 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005222 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005223 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005224 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005225 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5226 DeclareImplicitCopyConstructor(FieldClassDecl);
5227
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005228 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005229 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005230 }
5231 }
5232
5233 // Otherwise, the implicitly declared copy constructor will have
5234 // the form
5235 //
5236 // X::X(X&)
5237 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5238 QualType ArgType = ClassType;
5239 if (HasConstCopyConstructor)
5240 ArgType = ArgType.withConst();
5241 ArgType = Context.getLValueReferenceType(ArgType);
5242
Douglas Gregor0d405db2010-07-01 20:59:04 +00005243 // C++ [except.spec]p14:
5244 // An implicitly declared special member function (Clause 12) shall have an
5245 // exception-specification. [...]
5246 ImplicitExceptionSpecification ExceptSpec(Context);
5247 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5248 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5249 BaseEnd = ClassDecl->bases_end();
5250 Base != BaseEnd;
5251 ++Base) {
5252 // Virtual bases are handled below.
5253 if (Base->isVirtual())
5254 continue;
5255
Douglas Gregor22584312010-07-02 23:41:54 +00005256 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005257 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005258 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5259 DeclareImplicitCopyConstructor(BaseClassDecl);
5260
Douglas Gregor0d405db2010-07-01 20:59:04 +00005261 if (CXXConstructorDecl *CopyConstructor
5262 = BaseClassDecl->getCopyConstructor(Context, Quals))
5263 ExceptSpec.CalledDecl(CopyConstructor);
5264 }
5265 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5266 BaseEnd = ClassDecl->vbases_end();
5267 Base != BaseEnd;
5268 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005269 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005270 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005271 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5272 DeclareImplicitCopyConstructor(BaseClassDecl);
5273
Douglas Gregor0d405db2010-07-01 20:59:04 +00005274 if (CXXConstructorDecl *CopyConstructor
5275 = BaseClassDecl->getCopyConstructor(Context, Quals))
5276 ExceptSpec.CalledDecl(CopyConstructor);
5277 }
5278 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5279 FieldEnd = ClassDecl->field_end();
5280 Field != FieldEnd;
5281 ++Field) {
5282 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5283 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005284 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005285 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005286 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5287 DeclareImplicitCopyConstructor(FieldClassDecl);
5288
Douglas Gregor0d405db2010-07-01 20:59:04 +00005289 if (CXXConstructorDecl *CopyConstructor
5290 = FieldClassDecl->getCopyConstructor(Context, Quals))
5291 ExceptSpec.CalledDecl(CopyConstructor);
5292 }
5293 }
5294
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005295 // An implicitly-declared copy constructor is an inline public
5296 // member of its class.
John McCalle23cf432010-12-14 08:05:40 +00005297 FunctionProtoType::ExtProtoInfo EPI;
5298 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5299 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5300 EPI.NumExceptions = ExceptSpec.size();
5301 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005302 DeclarationName Name
5303 = Context.DeclarationNames.getCXXConstructorName(
5304 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005305 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005306 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005307 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005308 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005309 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005310 /*TInfo=*/0,
5311 /*isExplicit=*/false,
5312 /*isInline=*/true,
5313 /*isImplicitlyDeclared=*/true);
5314 CopyConstructor->setAccess(AS_public);
5315 CopyConstructor->setImplicit();
5316 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5317
Douglas Gregor22584312010-07-02 23:41:54 +00005318 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00005319 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5320
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005321 // Add the parameter to the constructor.
5322 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5323 ClassDecl->getLocation(),
5324 /*IdentifierInfo=*/0,
5325 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005326 SC_None,
5327 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005328 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005329 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005330 PushOnScopeChains(CopyConstructor, S, false);
5331 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005332
5333 return CopyConstructor;
5334}
5335
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005336void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5337 CXXConstructorDecl *CopyConstructor,
5338 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005339 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005340 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005341 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005342 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005343
Anders Carlsson63010a72010-04-23 16:24:12 +00005344 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005345 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005346
Douglas Gregor39957dc2010-05-01 15:04:51 +00005347 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00005348 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005349
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005350 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5351 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005352 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005353 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005354 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005355 } else {
5356 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5357 CopyConstructor->getLocation(),
5358 MultiStmtArg(*this, 0, 0),
5359 /*isStmtExpr=*/false)
5360 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005361 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005362
5363 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005364}
5365
John McCall60d7b3a2010-08-24 06:29:42 +00005366ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005367Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005368 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005369 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005370 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005371 unsigned ConstructKind,
5372 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005373 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Douglas Gregor2f599792010-04-02 18:24:57 +00005375 // C++0x [class.copy]p34:
5376 // When certain criteria are met, an implementation is allowed to
5377 // omit the copy/move construction of a class object, even if the
5378 // copy/move constructor and/or destructor for the object have
5379 // side effects. [...]
5380 // - when a temporary class object that has not been bound to a
5381 // reference (12.2) would be copied/moved to a class object
5382 // with the same cv-unqualified type, the copy/move operation
5383 // can be omitted by constructing the temporary object
5384 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00005385 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5386 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00005387 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00005388 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005389 }
Mike Stump1eb44332009-09-09 15:08:12 +00005390
5391 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005392 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005393 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005394}
5395
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005396/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5397/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005398ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005399Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5400 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005401 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005402 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005403 unsigned ConstructKind,
5404 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005405 unsigned NumExprs = ExprArgs.size();
5406 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005407
Douglas Gregor7edfb692009-11-23 12:27:39 +00005408 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005409 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005410 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005411 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005412 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5413 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005414}
5415
Mike Stump1eb44332009-09-09 15:08:12 +00005416bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005417 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005418 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00005419 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00005420 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005421 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005422 move(Exprs), false, CXXConstructExpr::CK_Complete,
5423 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00005424 if (TempResult.isInvalid())
5425 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005426
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005427 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00005428 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005429 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00005430 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005431 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Anders Carlssonfe2de492009-08-25 05:18:00 +00005433 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005434}
5435
John McCall68c6c9a2010-02-02 09:10:11 +00005436void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005438 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005439 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005440 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005441 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005442 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005443 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005444 << VD->getDeclName()
5445 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005446
John McCallae792222010-09-18 05:25:11 +00005447 // TODO: this should be re-enabled for static locals by !CXAAtExit
5448 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall626e96e2010-08-01 20:20:59 +00005449 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005450 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005451}
5452
Mike Stump1eb44332009-09-09 15:08:12 +00005453/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005454/// ActOnDeclarator, when a C++ direct initializer is present.
5455/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005456void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005457 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005458 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005459 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005460 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005461
5462 // If there is no declaration, there was an error parsing it. Just ignore
5463 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005464 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005465 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005467 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5468 if (!VDecl) {
5469 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5470 RealDecl->setInvalidDecl();
5471 return;
5472 }
5473
Douglas Gregor83ddad32009-08-26 21:14:46 +00005474 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005475 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005476 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5477 //
5478 // Clients that want to distinguish between the two forms, can check for
5479 // direct initializer using VarDecl::hasCXXDirectInitializer().
5480 // A major benefit is that clients that don't particularly care about which
5481 // exactly form was it (like the CodeGen) can handle both cases without
5482 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005483
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005484 // C++ 8.5p11:
5485 // The form of initialization (using parentheses or '=') is generally
5486 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005487 // class type.
5488
Douglas Gregor4dffad62010-02-11 22:55:30 +00005489 if (!VDecl->getType()->isDependentType() &&
5490 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005491 diag::err_typecheck_decl_incomplete_type)) {
5492 VDecl->setInvalidDecl();
5493 return;
5494 }
5495
Douglas Gregor90f93822009-12-22 22:17:25 +00005496 // The variable can not have an abstract class type.
5497 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5498 diag::err_abstract_type_in_decl,
5499 AbstractVariableType))
5500 VDecl->setInvalidDecl();
5501
Sebastian Redl31310a22010-02-01 20:16:42 +00005502 const VarDecl *Def;
5503 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005504 Diag(VDecl->getLocation(), diag::err_redefinition)
5505 << VDecl->getDeclName();
5506 Diag(Def->getLocation(), diag::note_previous_definition);
5507 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005508 return;
5509 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005510
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005511 // C++ [class.static.data]p4
5512 // If a static data member is of const integral or const
5513 // enumeration type, its declaration in the class definition can
5514 // specify a constant-initializer which shall be an integral
5515 // constant expression (5.19). In that case, the member can appear
5516 // in integral constant expressions. The member shall still be
5517 // defined in a namespace scope if it is used in the program and the
5518 // namespace scope definition shall not contain an initializer.
5519 //
5520 // We already performed a redefinition check above, but for static
5521 // data members we also need to check whether there was an in-class
5522 // declaration with an initializer.
5523 const VarDecl* PrevInit = 0;
5524 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5525 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5526 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5527 return;
5528 }
5529
Douglas Gregora31040f2010-12-16 01:31:22 +00005530 bool IsDependent = false;
5531 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5532 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5533 VDecl->setInvalidDecl();
5534 return;
5535 }
5536
5537 if (Exprs.get()[I]->isTypeDependent())
5538 IsDependent = true;
5539 }
5540
Douglas Gregor4dffad62010-02-11 22:55:30 +00005541 // If either the declaration has a dependent type or if any of the
5542 // expressions is type-dependent, we represent the initialization
5543 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00005544 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00005545 // Let clients know that initialization was done with a direct initializer.
5546 VDecl->setCXXDirectInitializer(true);
5547
5548 // Store the initialization expressions as a ParenListExpr.
5549 unsigned NumExprs = Exprs.size();
5550 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5551 (Expr **)Exprs.release(),
5552 NumExprs, RParenLoc));
5553 return;
5554 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005555
5556 // Capture the variable that is being initialized and the style of
5557 // initialization.
5558 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5559
5560 // FIXME: Poor source location information.
5561 InitializationKind Kind
5562 = InitializationKind::CreateDirect(VDecl->getLocation(),
5563 LParenLoc, RParenLoc);
5564
5565 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005566 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005567 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005568 if (Result.isInvalid()) {
5569 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005570 return;
5571 }
John McCallb4eb64d2010-10-08 02:01:28 +00005572
5573 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00005574
Douglas Gregor53c374f2010-12-07 00:41:46 +00005575 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00005576 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005577 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005578
John McCall4204f072010-08-02 21:13:48 +00005579 if (!VDecl->isInvalidDecl() &&
5580 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005581 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005582 !VDecl->getInit()->isConstantInitializer(Context,
5583 VDecl->getType()->isReferenceType()))
5584 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5585 << VDecl->getInit()->getSourceRange();
5586
John McCall68c6c9a2010-02-02 09:10:11 +00005587 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5588 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005589}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005590
Douglas Gregor39da0b82009-09-09 23:08:42 +00005591/// \brief Given a constructor and the set of arguments provided for the
5592/// constructor, convert the arguments and add any required default arguments
5593/// to form a proper call to this constructor.
5594///
5595/// \returns true if an error occurred, false otherwise.
5596bool
5597Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5598 MultiExprArg ArgsPtr,
5599 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005600 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005601 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5602 unsigned NumArgs = ArgsPtr.size();
5603 Expr **Args = (Expr **)ArgsPtr.get();
5604
5605 const FunctionProtoType *Proto
5606 = Constructor->getType()->getAs<FunctionProtoType>();
5607 assert(Proto && "Constructor without a prototype?");
5608 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005609
5610 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005611 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005612 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005613 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005614 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005615
5616 VariadicCallType CallType =
5617 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5618 llvm::SmallVector<Expr *, 8> AllArgs;
5619 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5620 Proto, 0, Args, NumArgs, AllArgs,
5621 CallType);
5622 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5623 ConvertedArgs.push_back(AllArgs[i]);
5624 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005625}
5626
Anders Carlsson20d45d22009-12-12 00:32:00 +00005627static inline bool
5628CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5629 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005630 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005631 if (isa<NamespaceDecl>(DC)) {
5632 return SemaRef.Diag(FnDecl->getLocation(),
5633 diag::err_operator_new_delete_declared_in_namespace)
5634 << FnDecl->getDeclName();
5635 }
5636
5637 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005638 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005639 return SemaRef.Diag(FnDecl->getLocation(),
5640 diag::err_operator_new_delete_declared_static)
5641 << FnDecl->getDeclName();
5642 }
5643
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005644 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005645}
5646
Anders Carlsson156c78e2009-12-13 17:53:43 +00005647static inline bool
5648CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5649 CanQualType ExpectedResultType,
5650 CanQualType ExpectedFirstParamType,
5651 unsigned DependentParamTypeDiag,
5652 unsigned InvalidParamTypeDiag) {
5653 QualType ResultType =
5654 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5655
5656 // Check that the result type is not dependent.
5657 if (ResultType->isDependentType())
5658 return SemaRef.Diag(FnDecl->getLocation(),
5659 diag::err_operator_new_delete_dependent_result_type)
5660 << FnDecl->getDeclName() << ExpectedResultType;
5661
5662 // Check that the result type is what we expect.
5663 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5664 return SemaRef.Diag(FnDecl->getLocation(),
5665 diag::err_operator_new_delete_invalid_result_type)
5666 << FnDecl->getDeclName() << ExpectedResultType;
5667
5668 // A function template must have at least 2 parameters.
5669 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5670 return SemaRef.Diag(FnDecl->getLocation(),
5671 diag::err_operator_new_delete_template_too_few_parameters)
5672 << FnDecl->getDeclName();
5673
5674 // The function decl must have at least 1 parameter.
5675 if (FnDecl->getNumParams() == 0)
5676 return SemaRef.Diag(FnDecl->getLocation(),
5677 diag::err_operator_new_delete_too_few_parameters)
5678 << FnDecl->getDeclName();
5679
5680 // Check the the first parameter type is not dependent.
5681 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5682 if (FirstParamType->isDependentType())
5683 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5684 << FnDecl->getDeclName() << ExpectedFirstParamType;
5685
5686 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005687 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005688 ExpectedFirstParamType)
5689 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5690 << FnDecl->getDeclName() << ExpectedFirstParamType;
5691
5692 return false;
5693}
5694
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005695static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005696CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005697 // C++ [basic.stc.dynamic.allocation]p1:
5698 // A program is ill-formed if an allocation function is declared in a
5699 // namespace scope other than global scope or declared static in global
5700 // scope.
5701 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5702 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005703
5704 CanQualType SizeTy =
5705 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5706
5707 // C++ [basic.stc.dynamic.allocation]p1:
5708 // The return type shall be void*. The first parameter shall have type
5709 // std::size_t.
5710 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5711 SizeTy,
5712 diag::err_operator_new_dependent_param_type,
5713 diag::err_operator_new_param_type))
5714 return true;
5715
5716 // C++ [basic.stc.dynamic.allocation]p1:
5717 // The first parameter shall not have an associated default argument.
5718 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005719 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005720 diag::err_operator_new_default_arg)
5721 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5722
5723 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005724}
5725
5726static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005727CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5728 // C++ [basic.stc.dynamic.deallocation]p1:
5729 // A program is ill-formed if deallocation functions are declared in a
5730 // namespace scope other than global scope or declared static in global
5731 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005732 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5733 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005734
5735 // C++ [basic.stc.dynamic.deallocation]p2:
5736 // Each deallocation function shall return void and its first parameter
5737 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005738 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5739 SemaRef.Context.VoidPtrTy,
5740 diag::err_operator_delete_dependent_param_type,
5741 diag::err_operator_delete_param_type))
5742 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005743
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005744 return false;
5745}
5746
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005747/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5748/// of this overloaded operator is well-formed. If so, returns false;
5749/// otherwise, emits appropriate diagnostics and returns true.
5750bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005751 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005752 "Expected an overloaded operator declaration");
5753
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005754 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5755
Mike Stump1eb44332009-09-09 15:08:12 +00005756 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005757 // The allocation and deallocation functions, operator new,
5758 // operator new[], operator delete and operator delete[], are
5759 // described completely in 3.7.3. The attributes and restrictions
5760 // found in the rest of this subclause do not apply to them unless
5761 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005762 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005763 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005764
Anders Carlssona3ccda52009-12-12 00:26:23 +00005765 if (Op == OO_New || Op == OO_Array_New)
5766 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005767
5768 // C++ [over.oper]p6:
5769 // An operator function shall either be a non-static member
5770 // function or be a non-member function and have at least one
5771 // parameter whose type is a class, a reference to a class, an
5772 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005773 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5774 if (MethodDecl->isStatic())
5775 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005776 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005777 } else {
5778 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005779 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5780 ParamEnd = FnDecl->param_end();
5781 Param != ParamEnd; ++Param) {
5782 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005783 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5784 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005785 ClassOrEnumParam = true;
5786 break;
5787 }
5788 }
5789
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005790 if (!ClassOrEnumParam)
5791 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005792 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005793 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005794 }
5795
5796 // C++ [over.oper]p8:
5797 // An operator function cannot have default arguments (8.3.6),
5798 // except where explicitly stated below.
5799 //
Mike Stump1eb44332009-09-09 15:08:12 +00005800 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005801 // (C++ [over.call]p1).
5802 if (Op != OO_Call) {
5803 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5804 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005805 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005806 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005807 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005808 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005809 }
5810 }
5811
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005812 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5813 { false, false, false }
5814#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5815 , { Unary, Binary, MemberOnly }
5816#include "clang/Basic/OperatorKinds.def"
5817 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005818
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005819 bool CanBeUnaryOperator = OperatorUses[Op][0];
5820 bool CanBeBinaryOperator = OperatorUses[Op][1];
5821 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005822
5823 // C++ [over.oper]p8:
5824 // [...] Operator functions cannot have more or fewer parameters
5825 // than the number required for the corresponding operator, as
5826 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005827 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005828 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005829 if (Op != OO_Call &&
5830 ((NumParams == 1 && !CanBeUnaryOperator) ||
5831 (NumParams == 2 && !CanBeBinaryOperator) ||
5832 (NumParams < 1) || (NumParams > 2))) {
5833 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005834 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005835 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005836 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005837 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005838 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005839 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005840 assert(CanBeBinaryOperator &&
5841 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005842 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005843 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005844
Chris Lattner416e46f2008-11-21 07:57:12 +00005845 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005846 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005847 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005848
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005849 // Overloaded operators other than operator() cannot be variadic.
5850 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005851 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005852 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005853 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005854 }
5855
5856 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005857 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5858 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005859 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005860 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005861 }
5862
5863 // C++ [over.inc]p1:
5864 // The user-defined function called operator++ implements the
5865 // prefix and postfix ++ operator. If this function is a member
5866 // function with no parameters, or a non-member function with one
5867 // parameter of class or enumeration type, it defines the prefix
5868 // increment operator ++ for objects of that type. If the function
5869 // is a member function with one parameter (which shall be of type
5870 // int) or a non-member function with two parameters (the second
5871 // of which shall be of type int), it defines the postfix
5872 // increment operator ++ for objects of that type.
5873 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5874 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5875 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005876 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005877 ParamIsInt = BT->getKind() == BuiltinType::Int;
5878
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005879 if (!ParamIsInt)
5880 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005881 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005882 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005883 }
5884
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005885 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005886}
Chris Lattner5a003a42008-12-17 07:09:26 +00005887
Sean Hunta6c058d2010-01-13 09:01:02 +00005888/// CheckLiteralOperatorDeclaration - Check whether the declaration
5889/// of this literal operator function is well-formed. If so, returns
5890/// false; otherwise, emits appropriate diagnostics and returns true.
5891bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5892 DeclContext *DC = FnDecl->getDeclContext();
5893 Decl::Kind Kind = DC->getDeclKind();
5894 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5895 Kind != Decl::LinkageSpec) {
5896 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5897 << FnDecl->getDeclName();
5898 return true;
5899 }
5900
5901 bool Valid = false;
5902
Sean Hunt216c2782010-04-07 23:11:06 +00005903 // template <char...> type operator "" name() is the only valid template
5904 // signature, and the only valid signature with no parameters.
5905 if (FnDecl->param_size() == 0) {
5906 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5907 // Must have only one template parameter
5908 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5909 if (Params->size() == 1) {
5910 NonTypeTemplateParmDecl *PmDecl =
5911 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005912
Sean Hunt216c2782010-04-07 23:11:06 +00005913 // The template parameter must be a char parameter pack.
5914 // FIXME: This test will always fail because non-type parameter packs
5915 // have not been implemented.
5916 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5917 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5918 Valid = true;
5919 }
5920 }
5921 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005922 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005923 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5924
Sean Hunta6c058d2010-01-13 09:01:02 +00005925 QualType T = (*Param)->getType();
5926
Sean Hunt30019c02010-04-07 22:57:35 +00005927 // unsigned long long int, long double, and any character type are allowed
5928 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005929 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5930 Context.hasSameType(T, Context.LongDoubleTy) ||
5931 Context.hasSameType(T, Context.CharTy) ||
5932 Context.hasSameType(T, Context.WCharTy) ||
5933 Context.hasSameType(T, Context.Char16Ty) ||
5934 Context.hasSameType(T, Context.Char32Ty)) {
5935 if (++Param == FnDecl->param_end())
5936 Valid = true;
5937 goto FinishedParams;
5938 }
5939
Sean Hunt30019c02010-04-07 22:57:35 +00005940 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005941 const PointerType *PT = T->getAs<PointerType>();
5942 if (!PT)
5943 goto FinishedParams;
5944 T = PT->getPointeeType();
5945 if (!T.isConstQualified())
5946 goto FinishedParams;
5947 T = T.getUnqualifiedType();
5948
5949 // Move on to the second parameter;
5950 ++Param;
5951
5952 // If there is no second parameter, the first must be a const char *
5953 if (Param == FnDecl->param_end()) {
5954 if (Context.hasSameType(T, Context.CharTy))
5955 Valid = true;
5956 goto FinishedParams;
5957 }
5958
5959 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5960 // are allowed as the first parameter to a two-parameter function
5961 if (!(Context.hasSameType(T, Context.CharTy) ||
5962 Context.hasSameType(T, Context.WCharTy) ||
5963 Context.hasSameType(T, Context.Char16Ty) ||
5964 Context.hasSameType(T, Context.Char32Ty)))
5965 goto FinishedParams;
5966
5967 // The second and final parameter must be an std::size_t
5968 T = (*Param)->getType().getUnqualifiedType();
5969 if (Context.hasSameType(T, Context.getSizeType()) &&
5970 ++Param == FnDecl->param_end())
5971 Valid = true;
5972 }
5973
5974 // FIXME: This diagnostic is absolutely terrible.
5975FinishedParams:
5976 if (!Valid) {
5977 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5978 << FnDecl->getDeclName();
5979 return true;
5980 }
5981
5982 return false;
5983}
5984
Douglas Gregor074149e2009-01-05 19:45:36 +00005985/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5986/// linkage specification, including the language and (if present)
5987/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5988/// the location of the language string literal, which is provided
5989/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5990/// the '{' brace. Otherwise, this linkage specification does not
5991/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00005992Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5993 SourceLocation LangLoc,
5994 llvm::StringRef Lang,
5995 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005996 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005997 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005998 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005999 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006000 Language = LinkageSpecDecl::lang_cxx;
6001 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006002 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006003 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006004 }
Mike Stump1eb44332009-09-09 15:08:12 +00006005
Chris Lattnercc98eac2008-12-17 07:13:27 +00006006 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006007
Douglas Gregor074149e2009-01-05 19:45:36 +00006008 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006009 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006010 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006011 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006012 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006013 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006014}
6015
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006016/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006017/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6018/// valid, it's the position of the closing '}' brace in a linkage
6019/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006020Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6021 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006022 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006023 if (LinkageSpec)
6024 PopDeclContext();
6025 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006026}
6027
Douglas Gregord308e622009-05-18 20:51:54 +00006028/// \brief Perform semantic analysis for the variable declaration that
6029/// occurs within a C++ catch clause, returning the newly-created
6030/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006031VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006032 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006033 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006034 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006035 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006036 QualType ExDeclType = TInfo->getType();
6037
Sebastian Redl4b07b292008-12-22 19:15:10 +00006038 // Arrays and functions decay.
6039 if (ExDeclType->isArrayType())
6040 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6041 else if (ExDeclType->isFunctionType())
6042 ExDeclType = Context.getPointerType(ExDeclType);
6043
6044 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6045 // The exception-declaration shall not denote a pointer or reference to an
6046 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006047 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006048 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006049 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006050 Invalid = true;
6051 }
Douglas Gregord308e622009-05-18 20:51:54 +00006052
Douglas Gregora2762912010-03-08 01:47:36 +00006053 // GCC allows catching pointers and references to incomplete types
6054 // as an extension; so do we, but we warn by default.
6055
Sebastian Redl4b07b292008-12-22 19:15:10 +00006056 QualType BaseType = ExDeclType;
6057 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006058 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006059 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006060 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006061 BaseType = Ptr->getPointeeType();
6062 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006063 DK = diag::ext_catch_incomplete_ptr;
6064 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006065 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006066 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006067 BaseType = Ref->getPointeeType();
6068 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006069 DK = diag::ext_catch_incomplete_ref;
6070 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006071 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006072 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006073 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6074 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006075 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006076
Mike Stump1eb44332009-09-09 15:08:12 +00006077 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006078 RequireNonAbstractType(Loc, ExDeclType,
6079 diag::err_abstract_type_in_decl,
6080 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006081 Invalid = true;
6082
John McCall5a180392010-07-24 00:37:23 +00006083 // Only the non-fragile NeXT runtime currently supports C++ catches
6084 // of ObjC types, and no runtime supports catching ObjC types by value.
6085 if (!Invalid && getLangOptions().ObjC1) {
6086 QualType T = ExDeclType;
6087 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6088 T = RT->getPointeeType();
6089
6090 if (T->isObjCObjectType()) {
6091 Diag(Loc, diag::err_objc_object_catch);
6092 Invalid = true;
6093 } else if (T->isObjCObjectPointerType()) {
6094 if (!getLangOptions().NeXTRuntime) {
6095 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6096 Invalid = true;
6097 } else if (!getLangOptions().ObjCNonFragileABI) {
6098 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6099 Invalid = true;
6100 }
6101 }
6102 }
6103
Mike Stump1eb44332009-09-09 15:08:12 +00006104 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006105 Name, ExDeclType, TInfo, SC_None,
6106 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006107 ExDecl->setExceptionVariable(true);
6108
Douglas Gregor6d182892010-03-05 23:38:39 +00006109 if (!Invalid) {
6110 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6111 // C++ [except.handle]p16:
6112 // The object declared in an exception-declaration or, if the
6113 // exception-declaration does not specify a name, a temporary (12.2) is
6114 // copy-initialized (8.5) from the exception object. [...]
6115 // The object is destroyed when the handler exits, after the destruction
6116 // of any automatic objects initialized within the handler.
6117 //
6118 // We just pretend to initialize the object with itself, then make sure
6119 // it can be destroyed later.
6120 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6121 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCallf89e55a2010-11-18 06:31:45 +00006122 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6d182892010-03-05 23:38:39 +00006123 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6124 SourceLocation());
6125 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006126 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006127 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006128 if (Result.isInvalid())
6129 Invalid = true;
6130 else
6131 FinalizeVarWithDestructor(ExDecl, RecordTy);
6132 }
6133 }
6134
Douglas Gregord308e622009-05-18 20:51:54 +00006135 if (Invalid)
6136 ExDecl->setInvalidDecl();
6137
6138 return ExDecl;
6139}
6140
6141/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6142/// handler.
John McCalld226f652010-08-21 09:40:31 +00006143Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006144 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00006145 bool Invalid = D.isInvalidType();
6146
6147 // Check for unexpanded parameter packs.
6148 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6149 UPPC_ExceptionType)) {
6150 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6151 D.getIdentifierLoc());
6152 Invalid = true;
6153 }
6154
John McCallbf1a0282010-06-04 23:28:52 +00006155 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006156
Sebastian Redl4b07b292008-12-22 19:15:10 +00006157 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006158 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006159 LookupOrdinaryName,
6160 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006161 // The scope should be freshly made just for us. There is just no way
6162 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006163 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006164 if (PrevDecl->isTemplateParameter()) {
6165 // Maybe we will complain about the shadowed template parameter.
6166 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006167 }
6168 }
6169
Chris Lattnereaaebc72009-04-25 08:06:05 +00006170 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006171 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6172 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006173 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006174 }
6175
Douglas Gregor83cb9422010-09-09 17:09:21 +00006176 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006177 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006178 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006179
Chris Lattnereaaebc72009-04-25 08:06:05 +00006180 if (Invalid)
6181 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006182
Sebastian Redl4b07b292008-12-22 19:15:10 +00006183 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006184 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006185 PushOnScopeChains(ExDecl, S);
6186 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006187 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006188
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006189 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006190 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006191}
Anders Carlssonfb311762009-03-14 00:25:26 +00006192
John McCalld226f652010-08-21 09:40:31 +00006193Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006194 Expr *AssertExpr,
6195 Expr *AssertMessageExpr_) {
6196 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006197
Anders Carlssonc3082412009-03-14 00:33:21 +00006198 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6199 llvm::APSInt Value(32);
6200 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6201 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6202 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006203 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006204 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006205
Anders Carlssonc3082412009-03-14 00:33:21 +00006206 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006207 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006208 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006209 }
6210 }
Mike Stump1eb44332009-09-09 15:08:12 +00006211
Douglas Gregor399ad972010-12-15 23:55:21 +00006212 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6213 return 0;
6214
Mike Stump1eb44332009-09-09 15:08:12 +00006215 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006216 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006217
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006218 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006219 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006220}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006221
Douglas Gregor1d869352010-04-07 16:53:43 +00006222/// \brief Perform semantic analysis of the given friend type declaration.
6223///
6224/// \returns A friend declaration that.
6225FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6226 TypeSourceInfo *TSInfo) {
6227 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6228
6229 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006230 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006231
Douglas Gregor06245bf2010-04-07 17:57:12 +00006232 if (!getLangOptions().CPlusPlus0x) {
6233 // C++03 [class.friend]p2:
6234 // An elaborated-type-specifier shall be used in a friend declaration
6235 // for a class.*
6236 //
6237 // * The class-key of the elaborated-type-specifier is required.
6238 if (!ActiveTemplateInstantiations.empty()) {
6239 // Do not complain about the form of friend template types during
6240 // template instantiation; we will already have complained when the
6241 // template was declared.
6242 } else if (!T->isElaboratedTypeSpecifier()) {
6243 // If we evaluated the type to a record type, suggest putting
6244 // a tag in front.
6245 if (const RecordType *RT = T->getAs<RecordType>()) {
6246 RecordDecl *RD = RT->getDecl();
6247
6248 std::string InsertionText = std::string(" ") + RD->getKindName();
6249
6250 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6251 << (unsigned) RD->getTagKind()
6252 << T
6253 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6254 InsertionText);
6255 } else {
6256 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6257 << T
6258 << SourceRange(FriendLoc, TypeRange.getEnd());
6259 }
6260 } else if (T->getAs<EnumType>()) {
6261 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006262 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006263 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006264 }
6265 }
6266
Douglas Gregor06245bf2010-04-07 17:57:12 +00006267 // C++0x [class.friend]p3:
6268 // If the type specifier in a friend declaration designates a (possibly
6269 // cv-qualified) class type, that class is declared as a friend; otherwise,
6270 // the friend declaration is ignored.
6271
6272 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6273 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006274
6275 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6276}
6277
John McCall9a34edb2010-10-19 01:40:49 +00006278/// Handle a friend tag declaration where the scope specifier was
6279/// templated.
6280Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6281 unsigned TagSpec, SourceLocation TagLoc,
6282 CXXScopeSpec &SS,
6283 IdentifierInfo *Name, SourceLocation NameLoc,
6284 AttributeList *Attr,
6285 MultiTemplateParamsArg TempParamLists) {
6286 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6287
6288 bool isExplicitSpecialization = false;
6289 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6290 bool Invalid = false;
6291
6292 if (TemplateParameterList *TemplateParams
6293 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6294 TempParamLists.get(),
6295 TempParamLists.size(),
6296 /*friend*/ true,
6297 isExplicitSpecialization,
6298 Invalid)) {
6299 --NumMatchedTemplateParamLists;
6300
6301 if (TemplateParams->size() > 0) {
6302 // This is a declaration of a class template.
6303 if (Invalid)
6304 return 0;
6305
6306 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6307 SS, Name, NameLoc, Attr,
6308 TemplateParams, AS_public).take();
6309 } else {
6310 // The "template<>" header is extraneous.
6311 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6312 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6313 isExplicitSpecialization = true;
6314 }
6315 }
6316
6317 if (Invalid) return 0;
6318
6319 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6320
6321 bool isAllExplicitSpecializations = true;
6322 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6323 if (TempParamLists.get()[I]->size()) {
6324 isAllExplicitSpecializations = false;
6325 break;
6326 }
6327 }
6328
6329 // FIXME: don't ignore attributes.
6330
6331 // If it's explicit specializations all the way down, just forget
6332 // about the template header and build an appropriate non-templated
6333 // friend. TODO: for source fidelity, remember the headers.
6334 if (isAllExplicitSpecializations) {
6335 ElaboratedTypeKeyword Keyword
6336 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6337 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6338 TagLoc, SS.getRange(), NameLoc);
6339 if (T.isNull())
6340 return 0;
6341
6342 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6343 if (isa<DependentNameType>(T)) {
6344 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6345 TL.setKeywordLoc(TagLoc);
6346 TL.setQualifierRange(SS.getRange());
6347 TL.setNameLoc(NameLoc);
6348 } else {
6349 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6350 TL.setKeywordLoc(TagLoc);
6351 TL.setQualifierRange(SS.getRange());
6352 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6353 }
6354
6355 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6356 TSI, FriendLoc);
6357 Friend->setAccess(AS_public);
6358 CurContext->addDecl(Friend);
6359 return Friend;
6360 }
6361
6362 // Handle the case of a templated-scope friend class. e.g.
6363 // template <class T> class A<T>::B;
6364 // FIXME: we don't support these right now.
6365 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6366 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6367 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6368 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6369 TL.setKeywordLoc(TagLoc);
6370 TL.setQualifierRange(SS.getRange());
6371 TL.setNameLoc(NameLoc);
6372
6373 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6374 TSI, FriendLoc);
6375 Friend->setAccess(AS_public);
6376 Friend->setUnsupportedFriend(true);
6377 CurContext->addDecl(Friend);
6378 return Friend;
6379}
6380
6381
John McCalldd4a3b02009-09-16 22:47:08 +00006382/// Handle a friend type declaration. This works in tandem with
6383/// ActOnTag.
6384///
6385/// Notes on friend class templates:
6386///
6387/// We generally treat friend class declarations as if they were
6388/// declaring a class. So, for example, the elaborated type specifier
6389/// in a friend declaration is required to obey the restrictions of a
6390/// class-head (i.e. no typedefs in the scope chain), template
6391/// parameters are required to match up with simple template-ids, &c.
6392/// However, unlike when declaring a template specialization, it's
6393/// okay to refer to a template specialization without an empty
6394/// template parameter declaration, e.g.
6395/// friend class A<T>::B<unsigned>;
6396/// We permit this as a special case; if there are any template
6397/// parameters present at all, require proper matching, i.e.
6398/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006399Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00006400 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006401 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006402
6403 assert(DS.isFriendSpecified());
6404 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6405
John McCalldd4a3b02009-09-16 22:47:08 +00006406 // Try to convert the decl specifier to a type. This works for
6407 // friend templates because ActOnTag never produces a ClassTemplateDecl
6408 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006409 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006410 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6411 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006412 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006413 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006414
Douglas Gregor6ccab972010-12-16 01:14:37 +00006415 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6416 return 0;
6417
John McCalldd4a3b02009-09-16 22:47:08 +00006418 // This is definitely an error in C++98. It's probably meant to
6419 // be forbidden in C++0x, too, but the specification is just
6420 // poorly written.
6421 //
6422 // The problem is with declarations like the following:
6423 // template <T> friend A<T>::foo;
6424 // where deciding whether a class C is a friend or not now hinges
6425 // on whether there exists an instantiation of A that causes
6426 // 'foo' to equal C. There are restrictions on class-heads
6427 // (which we declare (by fiat) elaborated friend declarations to
6428 // be) that makes this tractable.
6429 //
6430 // FIXME: handle "template <> friend class A<T>;", which
6431 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006432 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006433 Diag(Loc, diag::err_tagless_friend_type_template)
6434 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006435 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006436 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006437
John McCall02cace72009-08-28 07:59:38 +00006438 // C++98 [class.friend]p1: A friend of a class is a function
6439 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006440 // This is fixed in DR77, which just barely didn't make the C++03
6441 // deadline. It's also a very silly restriction that seriously
6442 // affects inner classes and which nobody else seems to implement;
6443 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006444 //
6445 // But note that we could warn about it: it's always useless to
6446 // friend one of your own members (it's not, however, worthless to
6447 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006448
John McCalldd4a3b02009-09-16 22:47:08 +00006449 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006450 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006451 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006452 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00006453 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006454 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006455 DS.getFriendSpecLoc());
6456 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006457 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6458
6459 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006460 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006461
John McCalldd4a3b02009-09-16 22:47:08 +00006462 D->setAccess(AS_public);
6463 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006464
John McCalld226f652010-08-21 09:40:31 +00006465 return D;
John McCall02cace72009-08-28 07:59:38 +00006466}
6467
John McCall337ec3d2010-10-12 23:13:28 +00006468Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6469 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006470 const DeclSpec &DS = D.getDeclSpec();
6471
6472 assert(DS.isFriendSpecified());
6473 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6474
6475 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006476 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6477 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006478
6479 // C++ [class.friend]p1
6480 // A friend of a class is a function or class....
6481 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006482 // It *doesn't* see through dependent types, which is correct
6483 // according to [temp.arg.type]p3:
6484 // If a declaration acquires a function type through a
6485 // type dependent on a template-parameter and this causes
6486 // a declaration that does not use the syntactic form of a
6487 // function declarator to have a function type, the program
6488 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006489 if (!T->isFunctionType()) {
6490 Diag(Loc, diag::err_unexpected_friend);
6491
6492 // It might be worthwhile to try to recover by creating an
6493 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006494 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006495 }
6496
6497 // C++ [namespace.memdef]p3
6498 // - If a friend declaration in a non-local class first declares a
6499 // class or function, the friend class or function is a member
6500 // of the innermost enclosing namespace.
6501 // - The name of the friend is not found by simple name lookup
6502 // until a matching declaration is provided in that namespace
6503 // scope (either before or after the class declaration granting
6504 // friendship).
6505 // - If a friend function is called, its name may be found by the
6506 // name lookup that considers functions from namespaces and
6507 // classes associated with the types of the function arguments.
6508 // - When looking for a prior declaration of a class or a function
6509 // declared as a friend, scopes outside the innermost enclosing
6510 // namespace scope are not considered.
6511
John McCall337ec3d2010-10-12 23:13:28 +00006512 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006513 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6514 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006515 assert(Name);
6516
Douglas Gregor6ccab972010-12-16 01:14:37 +00006517 // Check for unexpanded parameter packs.
6518 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6519 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6520 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6521 return 0;
6522
John McCall67d1a672009-08-06 02:15:43 +00006523 // The context we found the declaration in, or in which we should
6524 // create the declaration.
6525 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00006526 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00006527 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006528 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006529
John McCall337ec3d2010-10-12 23:13:28 +00006530 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00006531
John McCall337ec3d2010-10-12 23:13:28 +00006532 // There are four cases here.
6533 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00006534 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00006535 // there as appropriate.
6536 // Recover from invalid scope qualifiers as if they just weren't there.
6537 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00006538 // C++0x [namespace.memdef]p3:
6539 // If the name in a friend declaration is neither qualified nor
6540 // a template-id and the declaration is a function or an
6541 // elaborated-type-specifier, the lookup to determine whether
6542 // the entity has been previously declared shall not consider
6543 // any scopes outside the innermost enclosing namespace.
6544 // C++0x [class.friend]p11:
6545 // If a friend declaration appears in a local class and the name
6546 // specified is an unqualified name, a prior declaration is
6547 // looked up without considering scopes that are outside the
6548 // innermost enclosing non-class scope. For a friend function
6549 // declaration, if there is no prior declaration, the program is
6550 // ill-formed.
6551 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00006552 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00006553
John McCall29ae6e52010-10-13 05:45:15 +00006554 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00006555 DC = CurContext;
6556 while (true) {
6557 // Skip class contexts. If someone can cite chapter and verse
6558 // for this behavior, that would be nice --- it's what GCC and
6559 // EDG do, and it seems like a reasonable intent, but the spec
6560 // really only says that checks for unqualified existing
6561 // declarations should stop at the nearest enclosing namespace,
6562 // not that they should only consider the nearest enclosing
6563 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006564 while (DC->isRecord())
6565 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006566
John McCall68263142009-11-18 22:49:29 +00006567 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006568
6569 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00006570 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006571 break;
John McCall29ae6e52010-10-13 05:45:15 +00006572
John McCall8a407372010-10-14 22:22:28 +00006573 if (isTemplateId) {
6574 if (isa<TranslationUnitDecl>(DC)) break;
6575 } else {
6576 if (DC->isFileContext()) break;
6577 }
John McCall67d1a672009-08-06 02:15:43 +00006578 DC = DC->getParent();
6579 }
6580
6581 // C++ [class.friend]p1: A friend of a class is a function or
6582 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006583 // C++0x changes this for both friend types and functions.
6584 // Most C++ 98 compilers do seem to give an error here, so
6585 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006586 if (!Previous.empty() && DC->Equals(CurContext)
6587 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006588 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00006589
John McCall380aaa42010-10-13 06:22:15 +00006590 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00006591
John McCall337ec3d2010-10-12 23:13:28 +00006592 // - There's a non-dependent scope specifier, in which case we
6593 // compute it and do a previous lookup there for a function
6594 // or function template.
6595 } else if (!SS.getScopeRep()->isDependent()) {
6596 DC = computeDeclContext(SS);
6597 if (!DC) return 0;
6598
6599 if (RequireCompleteDeclContext(SS, DC)) return 0;
6600
6601 LookupQualifiedName(Previous, DC);
6602
6603 // Ignore things found implicitly in the wrong scope.
6604 // TODO: better diagnostics for this case. Suggesting the right
6605 // qualified scope would be nice...
6606 LookupResult::Filter F = Previous.makeFilter();
6607 while (F.hasNext()) {
6608 NamedDecl *D = F.next();
6609 if (!DC->InEnclosingNamespaceSetOf(
6610 D->getDeclContext()->getRedeclContext()))
6611 F.erase();
6612 }
6613 F.done();
6614
6615 if (Previous.empty()) {
6616 D.setInvalidType();
6617 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6618 return 0;
6619 }
6620
6621 // C++ [class.friend]p1: A friend of a class is a function or
6622 // class that is not a member of the class . . .
6623 if (DC->Equals(CurContext))
6624 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6625
6626 // - There's a scope specifier that does not match any template
6627 // parameter lists, in which case we use some arbitrary context,
6628 // create a method or method template, and wait for instantiation.
6629 // - There's a scope specifier that does match some template
6630 // parameter lists, which we don't handle right now.
6631 } else {
6632 DC = CurContext;
6633 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00006634 }
6635
John McCall29ae6e52010-10-13 05:45:15 +00006636 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00006637 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006638 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6639 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6640 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006641 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006642 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6643 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006644 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006645 }
John McCall67d1a672009-08-06 02:15:43 +00006646 }
6647
Douglas Gregor182ddf02009-09-28 00:08:27 +00006648 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00006649 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006650 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006651 IsDefinition,
6652 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006653 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006654
Douglas Gregor182ddf02009-09-28 00:08:27 +00006655 assert(ND->getDeclContext() == DC);
6656 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006657
John McCallab88d972009-08-31 22:39:49 +00006658 // Add the function declaration to the appropriate lookup tables,
6659 // adjusting the redeclarations list as necessary. We don't
6660 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006661 //
John McCallab88d972009-08-31 22:39:49 +00006662 // Also update the scope-based lookup if the target context's
6663 // lookup context is in lexical scope.
6664 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006665 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006666 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006667 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006668 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006669 }
John McCall02cace72009-08-28 07:59:38 +00006670
6671 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006672 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006673 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006674 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006675 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006676
John McCall337ec3d2010-10-12 23:13:28 +00006677 if (ND->isInvalidDecl())
6678 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00006679 else {
6680 FunctionDecl *FD;
6681 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6682 FD = FTD->getTemplatedDecl();
6683 else
6684 FD = cast<FunctionDecl>(ND);
6685
6686 // Mark templated-scope function declarations as unsupported.
6687 if (FD->getNumTemplateParameterLists())
6688 FrD->setUnsupportedFriend(true);
6689 }
John McCall337ec3d2010-10-12 23:13:28 +00006690
John McCalld226f652010-08-21 09:40:31 +00006691 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006692}
6693
John McCalld226f652010-08-21 09:40:31 +00006694void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6695 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006696
Sebastian Redl50de12f2009-03-24 22:27:57 +00006697 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6698 if (!Fn) {
6699 Diag(DelLoc, diag::err_deleted_non_function);
6700 return;
6701 }
6702 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6703 Diag(DelLoc, diag::err_deleted_decl_not_first);
6704 Diag(Prev->getLocation(), diag::note_previous_declaration);
6705 // If the declaration wasn't the first, we delete the function anyway for
6706 // recovery.
6707 }
6708 Fn->setDeleted();
6709}
Sebastian Redl13e88542009-04-27 21:33:24 +00006710
6711static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6712 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6713 ++CI) {
6714 Stmt *SubStmt = *CI;
6715 if (!SubStmt)
6716 continue;
6717 if (isa<ReturnStmt>(SubStmt))
6718 Self.Diag(SubStmt->getSourceRange().getBegin(),
6719 diag::err_return_in_constructor_handler);
6720 if (!isa<Expr>(SubStmt))
6721 SearchForReturnInStmt(Self, SubStmt);
6722 }
6723}
6724
6725void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6726 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6727 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6728 SearchForReturnInStmt(*this, Handler);
6729 }
6730}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006731
Mike Stump1eb44332009-09-09 15:08:12 +00006732bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006733 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006734 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6735 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006736
Chandler Carruth73857792010-02-15 11:53:20 +00006737 if (Context.hasSameType(NewTy, OldTy) ||
6738 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006740
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006741 // Check if the return types are covariant
6742 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006743
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006744 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006745 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6746 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006747 NewClassTy = NewPT->getPointeeType();
6748 OldClassTy = OldPT->getPointeeType();
6749 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006750 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6751 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6752 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6753 NewClassTy = NewRT->getPointeeType();
6754 OldClassTy = OldRT->getPointeeType();
6755 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006756 }
6757 }
Mike Stump1eb44332009-09-09 15:08:12 +00006758
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006759 // The return types aren't either both pointers or references to a class type.
6760 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006761 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006762 diag::err_different_return_type_for_overriding_virtual_function)
6763 << New->getDeclName() << NewTy << OldTy;
6764 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006765
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006766 return true;
6767 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006768
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006769 // C++ [class.virtual]p6:
6770 // If the return type of D::f differs from the return type of B::f, the
6771 // class type in the return type of D::f shall be complete at the point of
6772 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006773 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6774 if (!RT->isBeingDefined() &&
6775 RequireCompleteType(New->getLocation(), NewClassTy,
6776 PDiag(diag::err_covariant_return_incomplete)
6777 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006778 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006779 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006780
Douglas Gregora4923eb2009-11-16 21:35:15 +00006781 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006782 // Check if the new class derives from the old class.
6783 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6784 Diag(New->getLocation(),
6785 diag::err_covariant_return_not_derived)
6786 << New->getDeclName() << NewTy << OldTy;
6787 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6788 return true;
6789 }
Mike Stump1eb44332009-09-09 15:08:12 +00006790
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006791 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006792 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006793 diag::err_covariant_return_inaccessible_base,
6794 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6795 // FIXME: Should this point to the return type?
6796 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006797 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6798 return true;
6799 }
6800 }
Mike Stump1eb44332009-09-09 15:08:12 +00006801
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006802 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006803 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006804 Diag(New->getLocation(),
6805 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006806 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006807 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6808 return true;
6809 };
Mike Stump1eb44332009-09-09 15:08:12 +00006810
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006811
6812 // The new class type must have the same or less qualifiers as the old type.
6813 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6814 Diag(New->getLocation(),
6815 diag::err_covariant_return_type_class_type_more_qualified)
6816 << New->getDeclName() << NewTy << OldTy;
6817 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6818 return true;
6819 };
Mike Stump1eb44332009-09-09 15:08:12 +00006820
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006821 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006822}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006823
Sean Huntbbd37c62009-11-21 08:43:09 +00006824bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6825 const CXXMethodDecl *Old)
6826{
6827 if (Old->hasAttr<FinalAttr>()) {
6828 Diag(New->getLocation(), diag::err_final_function_overridden)
6829 << New->getDeclName();
6830 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6831 return true;
6832 }
6833
6834 return false;
6835}
6836
Douglas Gregor4ba31362009-12-01 17:24:26 +00006837/// \brief Mark the given method pure.
6838///
6839/// \param Method the method to be marked pure.
6840///
6841/// \param InitRange the source range that covers the "0" initializer.
6842bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6843 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6844 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00006845 return false;
6846 }
6847
6848 if (!Method->isInvalidDecl())
6849 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6850 << Method->getDeclName() << InitRange;
6851 return true;
6852}
6853
John McCall731ad842009-12-19 09:28:58 +00006854/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6855/// an initializer for the out-of-line declaration 'Dcl'. The scope
6856/// is a fresh scope pushed for just this purpose.
6857///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006858/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6859/// static data member of class X, names should be looked up in the scope of
6860/// class X.
John McCalld226f652010-08-21 09:40:31 +00006861void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006862 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006863 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006864
John McCall731ad842009-12-19 09:28:58 +00006865 // We should only get called for declarations with scope specifiers, like:
6866 // int foo::bar;
6867 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006868 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006869}
6870
6871/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006872/// initializer for the out-of-line declaration 'D'.
6873void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006874 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006875 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006876
John McCall731ad842009-12-19 09:28:58 +00006877 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006878 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006879}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006880
6881/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6882/// C++ if/switch/while/for statement.
6883/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006884DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006885 // C++ 6.4p2:
6886 // The declarator shall not specify a function or an array.
6887 // The type-specifier-seq shall not contain typedef and shall not declare a
6888 // new class or enumeration.
6889 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6890 "Parser allowed 'typedef' as storage class of condition decl.");
6891
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006892 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006893 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6894 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006895
6896 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6897 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6898 // would be created and CXXConditionDeclExpr wants a VarDecl.
6899 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6900 << D.getSourceRange();
6901 return DeclResult();
6902 } else if (OwnedTag && OwnedTag->isDefinition()) {
6903 // The type-specifier-seq shall not declare a new class or enumeration.
6904 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6905 }
6906
John McCalld226f652010-08-21 09:40:31 +00006907 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006908 if (!Dcl)
6909 return DeclResult();
6910
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006911 return Dcl;
6912}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006913
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006914void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6915 bool DefinitionRequired) {
6916 // Ignore any vtable uses in unevaluated operands or for classes that do
6917 // not have a vtable.
6918 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6919 CurContext->isDependentContext() ||
6920 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006921 return;
6922
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006923 // Try to insert this class into the map.
6924 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6925 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6926 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6927 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006928 // If we already had an entry, check to see if we are promoting this vtable
6929 // to required a definition. If so, we need to reappend to the VTableUses
6930 // list, since we may have already processed the first entry.
6931 if (DefinitionRequired && !Pos.first->second) {
6932 Pos.first->second = true;
6933 } else {
6934 // Otherwise, we can early exit.
6935 return;
6936 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006937 }
6938
6939 // Local classes need to have their virtual members marked
6940 // immediately. For all other classes, we mark their virtual members
6941 // at the end of the translation unit.
6942 if (Class->isLocalClass())
6943 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006944 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006945 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006946}
6947
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006948bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006949 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006950 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00006951
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006952 // Note: The VTableUses vector could grow as a result of marking
6953 // the members of a class as "used", so we check the size each
6954 // time through the loop and prefer indices (with are stable) to
6955 // iterators (which are not).
6956 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006957 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006958 if (!Class)
6959 continue;
6960
6961 SourceLocation Loc = VTableUses[I].second;
6962
6963 // If this class has a key function, but that key function is
6964 // defined in another translation unit, we don't need to emit the
6965 // vtable even though we're using it.
6966 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006967 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006968 switch (KeyFunction->getTemplateSpecializationKind()) {
6969 case TSK_Undeclared:
6970 case TSK_ExplicitSpecialization:
6971 case TSK_ExplicitInstantiationDeclaration:
6972 // The key function is in another translation unit.
6973 continue;
6974
6975 case TSK_ExplicitInstantiationDefinition:
6976 case TSK_ImplicitInstantiation:
6977 // We will be instantiating the key function.
6978 break;
6979 }
6980 } else if (!KeyFunction) {
6981 // If we have a class with no key function that is the subject
6982 // of an explicit instantiation declaration, suppress the
6983 // vtable; it will live with the explicit instantiation
6984 // definition.
6985 bool IsExplicitInstantiationDeclaration
6986 = Class->getTemplateSpecializationKind()
6987 == TSK_ExplicitInstantiationDeclaration;
6988 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6989 REnd = Class->redecls_end();
6990 R != REnd; ++R) {
6991 TemplateSpecializationKind TSK
6992 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6993 if (TSK == TSK_ExplicitInstantiationDeclaration)
6994 IsExplicitInstantiationDeclaration = true;
6995 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6996 IsExplicitInstantiationDeclaration = false;
6997 break;
6998 }
6999 }
7000
7001 if (IsExplicitInstantiationDeclaration)
7002 continue;
7003 }
7004
7005 // Mark all of the virtual members of this class as referenced, so
7006 // that we can build a vtable. Then, tell the AST consumer that a
7007 // vtable for this class is required.
7008 MarkVirtualMembersReferenced(Loc, Class);
7009 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7010 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7011
7012 // Optionally warn if we're emitting a weak vtable.
7013 if (Class->getLinkage() == ExternalLinkage &&
7014 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00007015 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007016 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7017 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007018 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007019 VTableUses.clear();
7020
Anders Carlssond6a637f2009-12-07 08:24:59 +00007021 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00007022}
Anders Carlssond6a637f2009-12-07 08:24:59 +00007023
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007024void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7025 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00007026 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7027 e = RD->method_end(); i != e; ++i) {
7028 CXXMethodDecl *MD = *i;
7029
7030 // C++ [basic.def.odr]p2:
7031 // [...] A virtual member function is used if it is not pure. [...]
7032 if (MD->isVirtual() && !MD->isPure())
7033 MarkDeclarationReferenced(Loc, MD);
7034 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007035
7036 // Only classes that have virtual bases need a VTT.
7037 if (RD->getNumVBases() == 0)
7038 return;
7039
7040 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7041 e = RD->bases_end(); i != e; ++i) {
7042 const CXXRecordDecl *Base =
7043 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00007044 if (Base->getNumVBases() == 0)
7045 continue;
7046 MarkVirtualMembersReferenced(Loc, Base);
7047 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007048}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007049
7050/// SetIvarInitializers - This routine builds initialization ASTs for the
7051/// Objective-C implementation whose ivars need be initialized.
7052void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7053 if (!getLangOptions().CPlusPlus)
7054 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00007055 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007056 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7057 CollectIvarsToConstructOrDestruct(OID, ivars);
7058 if (ivars.empty())
7059 return;
7060 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7061 for (unsigned i = 0; i < ivars.size(); i++) {
7062 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007063 if (Field->isInvalidDecl())
7064 continue;
7065
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007066 CXXBaseOrMemberInitializer *Member;
7067 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7068 InitializationKind InitKind =
7069 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7070
7071 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007072 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00007073 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00007074 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007075 // Note, MemberInit could actually come back empty if no initialization
7076 // is required (e.g., because it would call a trivial default constructor)
7077 if (!MemberInit.get() || MemberInit.isInvalid())
7078 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00007079
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007080 Member =
7081 new (Context) CXXBaseOrMemberInitializer(Context,
7082 Field, SourceLocation(),
7083 SourceLocation(),
7084 MemberInit.takeAs<Expr>(),
7085 SourceLocation());
7086 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007087
7088 // Be sure that the destructor is accessible and is marked as referenced.
7089 if (const RecordType *RecordTy
7090 = Context.getBaseElementType(Field->getType())
7091 ->getAs<RecordType>()) {
7092 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007093 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007094 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7095 CheckDestructorAccess(Field->getLocation(), Destructor,
7096 PDiag(diag::err_access_dtor_ivar)
7097 << Context.getBaseElementType(Field->getType()));
7098 }
7099 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007100 }
7101 ObjCImplementation->setIvarInitializers(Context,
7102 AllToInit.data(), AllToInit.size());
7103 }
7104}