blob: 674a4bd9560d38ccbb8c6450a7db0487c900cab9 [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
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000112 QualType ParamType = Param->getType();
113
Anders Carlsson5653ca52009-08-25 13:46:13 +0000114 if (RequireCompleteType(Param->getLocation(), Param->getType(),
115 diag::err_typecheck_decl_incomplete_type)) {
116 Param->setInvalidDecl();
117 return true;
118 }
119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000121
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).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
131 if (CheckInitializerTypes(Arg, ParamType, Entity, Kind))
Anders Carlsson9351c172009-08-25 03:18:48 +0000132 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000133
Anders Carlsson0ece4912009-12-15 20:51:39 +0000134 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlssoned961f92009-08-25 02:29:20 +0000136 // Okay: add the default argument to the parameter
137 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Anders Carlssoned961f92009-08-25 02:29:20 +0000139 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlsson9351c172009-08-25 03:18:48 +0000141 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000142}
143
Chris Lattner8123a952008-04-10 02:22:51 +0000144/// ActOnParamDefaultArgument - Check whether the default argument
145/// provided for a function parameter is well-formed. If so, attach it
146/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000147void
Mike Stump1eb44332009-09-09 15:08:12 +0000148Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000149 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000150 if (!param || !defarg.get())
151 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Chris Lattnerb28317a2009-03-28 19:18:32 +0000153 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000154 UnparsedDefaultArgLocs.erase(Param);
155
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000156 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000157 QualType ParamType = Param->getType();
158
159 // Default arguments are only permitted in C++
160 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000161 Diag(EqualLoc, diag::err_param_default_argument)
162 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000163 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000164 return;
165 }
166
Anders Carlsson66e30672009-08-25 01:02:06 +0000167 // Check that the default argument is well-formed
168 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
169 if (DefaultArgChecker.Visit(DefaultArg.get())) {
170 Param->setInvalidDecl();
171 return;
172 }
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Anders Carlssoned961f92009-08-25 02:29:20 +0000174 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000175}
176
Douglas Gregor61366e92008-12-24 00:01:03 +0000177/// ActOnParamUnparsedDefaultArgument - We've seen a default
178/// argument for a function parameter, but we can't parse it yet
179/// because we're inside a class definition. Note that this default
180/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000181void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000182 SourceLocation EqualLoc,
183 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000184 if (!param)
185 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattnerb28317a2009-03-28 19:18:32 +0000187 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000188 if (Param)
189 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Anders Carlsson5e300d12009-06-12 16:51:40 +0000191 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000192}
193
Douglas Gregor72b505b2008-12-16 21:30:33 +0000194/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
195/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000196void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlsson5e300d12009-06-12 16:51:40 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlsson5e300d12009-06-12 16:51:40 +0000202 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000205}
206
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000207/// CheckExtraCXXDefaultArguments - Check for any extra default
208/// arguments in the declarator, which is not a function declaration
209/// or definition and therefore is not permitted to have default
210/// arguments. This routine should be invoked for every declarator
211/// that is not a function declaration or definition.
212void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
213 // C++ [dcl.fct.default]p3
214 // A default argument expression shall be specified only in the
215 // parameter-declaration-clause of a function declaration or in a
216 // template-parameter (14.1). It shall not be specified for a
217 // parameter pack. If it is specified in a
218 // parameter-declaration-clause, it shall not occur within a
219 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000220 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000221 DeclaratorChunk &chunk = D.getTypeObject(i);
222 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000223 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
224 ParmVarDecl *Param =
225 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000226 if (Param->hasUnparsedDefaultArg()) {
227 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
230 delete Toks;
231 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000232 } else if (Param->getDefaultArg()) {
233 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
234 << Param->getDefaultArg()->getSourceRange();
235 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000236 }
237 }
238 }
239 }
240}
241
Chris Lattner3d1cee32008-04-08 05:04:30 +0000242// MergeCXXFunctionDecl - Merge two declarations of the same C++
243// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000244// type. Subroutine of MergeFunctionDecl. Returns true if there was an
245// error, false otherwise.
246bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
247 bool Invalid = false;
248
Chris Lattner3d1cee32008-04-08 05:04:30 +0000249 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // For non-template functions, default arguments can be added in
251 // later declarations of a function in the same
252 // scope. Declarations in different scopes have completely
253 // distinct sets of default arguments. That is, declarations in
254 // inner scopes do not acquire default arguments from
255 // declarations in outer scopes, and vice versa. In a given
256 // function declaration, all parameters subsequent to a
257 // parameter with a default argument shall have default
258 // arguments supplied in this or previous declarations. A
259 // default argument shall not be redefined by a later
260 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000261 //
262 // C++ [dcl.fct.default]p6:
263 // Except for member functions of class templates, the default arguments
264 // in a member function definition that appears outside of the class
265 // definition are added to the set of default arguments provided by the
266 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000267 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
268 ParmVarDecl *OldParam = Old->getParamDecl(p);
269 ParmVarDecl *NewParam = New->getParamDecl(p);
270
Douglas Gregor6cc15182009-09-11 18:44:32 +0000271 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000272 // FIXME: If the parameter doesn't have an identifier then the location
273 // points to the '=' which means that the fixit hint won't remove any
274 // extra spaces between the type and the '='.
275 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000276 if (NewParam->getIdentifier())
277 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000278
Mike Stump1eb44332009-09-09 15:08:12 +0000279 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000280 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000281 << NewParam->getDefaultArgRange()
282 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
283 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000284
285 // Look for the function declaration where the default argument was
286 // actually written, which may be a declaration prior to Old.
287 for (FunctionDecl *Older = Old->getPreviousDeclaration();
288 Older; Older = Older->getPreviousDeclaration()) {
289 if (!Older->getParamDecl(p)->hasDefaultArg())
290 break;
291
292 OldParam = Older->getParamDecl(p);
293 }
294
295 Diag(OldParam->getLocation(), diag::note_previous_definition)
296 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000297 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000298 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000299 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000300 if (OldParam->hasUninstantiatedDefaultArg())
301 NewParam->setUninstantiatedDefaultArg(
302 OldParam->getUninstantiatedDefaultArg());
303 else
304 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000305 } else if (NewParam->hasDefaultArg()) {
306 if (New->getDescribedFunctionTemplate()) {
307 // Paragraph 4, quoted above, only applies to non-template functions.
308 Diag(NewParam->getLocation(),
309 diag::err_param_default_argument_template_redecl)
310 << NewParam->getDefaultArgRange();
311 Diag(Old->getLocation(), diag::note_template_prev_declaration)
312 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000313 } else if (New->getTemplateSpecializationKind()
314 != TSK_ImplicitInstantiation &&
315 New->getTemplateSpecializationKind() != TSK_Undeclared) {
316 // C++ [temp.expr.spec]p21:
317 // Default function arguments shall not be specified in a declaration
318 // or a definition for one of the following explicit specializations:
319 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000320 // - the explicit specialization of a member function template;
321 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000322 // template where the class template specialization to which the
323 // member function specialization belongs is implicitly
324 // instantiated.
325 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
326 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
327 << New->getDeclName()
328 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000329 } else if (New->getDeclContext()->isDependentContext()) {
330 // C++ [dcl.fct.default]p6 (DR217):
331 // Default arguments for a member function of a class template shall
332 // be specified on the initial declaration of the member function
333 // within the class template.
334 //
335 // Reading the tea leaves a bit in DR217 and its reference to DR205
336 // leads me to the conclusion that one cannot add default function
337 // arguments for an out-of-line definition of a member function of a
338 // dependent type.
339 int WhichKind = 2;
340 if (CXXRecordDecl *Record
341 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
342 if (Record->getDescribedClassTemplate())
343 WhichKind = 0;
344 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
345 WhichKind = 1;
346 else
347 WhichKind = 2;
348 }
349
350 Diag(NewParam->getLocation(),
351 diag::err_param_default_argument_member_template_redecl)
352 << WhichKind
353 << NewParam->getDefaultArgRange();
354 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000355 }
356 }
357
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000358 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000359 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000360 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362
Douglas Gregorcda9c672009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 else
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000412 if (!Param->hasUnparsedDefaultArg())
413 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 Param->setDefaultArg(0);
415 }
416 }
417 }
418}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000419
Douglas Gregorb48fe382008-10-31 09:07:45 +0000420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000426 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000427 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000428 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
430 } else
431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
432
433 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000434 return &II == CurDecl->getIdentifier();
435 else
436 return false;
437}
438
Mike Stump1eb44332009-09-09 15:08:12 +0000439/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000440///
441/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
442/// and returns NULL otherwise.
443CXXBaseSpecifier *
444Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
445 SourceRange SpecifierRange,
446 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000447 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000448 SourceLocation BaseLoc) {
449 // C++ [class.union]p1:
450 // A union shall not have base classes.
451 if (Class->isUnion()) {
452 Diag(Class->getLocation(), diag::err_base_clause_on_union)
453 << SpecifierRange;
454 return 0;
455 }
456
457 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000458 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000459 Class->getTagKind() == RecordDecl::TK_class,
460 Access, BaseType);
461
462 // Base specifiers must be record types.
463 if (!BaseType->isRecordType()) {
464 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
465 return 0;
466 }
467
468 // C++ [class.union]p1:
469 // A union shall not be used as a base class.
470 if (BaseType->isUnionType()) {
471 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
472 return 0;
473 }
474
475 // C++ [class.derived]p2:
476 // The class-name in a base-specifier shall not be an incompletely
477 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000478 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000479 PDiag(diag::err_incomplete_base_class)
480 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000481 return 0;
482
Eli Friedman1d954f62009-08-15 21:55:26 +0000483 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000484 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000485 assert(BaseDecl && "Record type has no declaration");
486 BaseDecl = BaseDecl->getDefinition(Context);
487 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000488 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
489 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000490
Sean Huntbbd37c62009-11-21 08:43:09 +0000491 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
492 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
493 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000494 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
495 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000496 return 0;
497 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000498
Eli Friedmand0137332009-12-05 23:03:49 +0000499 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000500
501 // Create the base specifier.
502 // FIXME: Allocate via ASTContext?
503 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
504 Class->getTagKind() == RecordDecl::TK_class,
505 Access, BaseType);
506}
507
508void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
509 const CXXRecordDecl *BaseClass,
510 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000511 // A class with a non-empty base class is not empty.
512 // FIXME: Standard ref?
513 if (!BaseClass->isEmpty())
514 Class->setEmpty(false);
515
516 // C++ [class.virtual]p1:
517 // A class that [...] inherits a virtual function is called a polymorphic
518 // class.
519 if (BaseClass->isPolymorphic())
520 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000521
Douglas Gregor2943aed2009-03-03 04:44:36 +0000522 // C++ [dcl.init.aggr]p1:
523 // An aggregate is [...] a class with [...] no base classes [...].
524 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000525
526 // C++ [class]p4:
527 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000528 Class->setPOD(false);
529
Anders Carlsson51f94042009-12-03 17:49:57 +0000530 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000531 // C++ [class.ctor]p5:
532 // A constructor is trivial if its class has no virtual base classes.
533 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000534
535 // C++ [class.copy]p6:
536 // A copy constructor is trivial if its class has no virtual base classes.
537 Class->setHasTrivialCopyConstructor(false);
538
539 // C++ [class.copy]p11:
540 // A copy assignment operator is trivial if its class has no virtual
541 // base classes.
542 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000543
544 // C++0x [meta.unary.prop] is_empty:
545 // T is a class type, but not a union type, with ... no virtual base
546 // classes
547 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000548 } else {
549 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000550 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000551 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000552 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000553 Class->setHasTrivialConstructor(false);
554
555 // C++ [class.copy]p6:
556 // A copy constructor is trivial if all the direct base classes of its
557 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000558 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000559 Class->setHasTrivialCopyConstructor(false);
560
561 // C++ [class.copy]p11:
562 // A copy assignment operator is trivial if all the direct base classes
563 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000564 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000565 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000566 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000567
568 // C++ [class.ctor]p3:
569 // A destructor is trivial if all the direct base classes of its class
570 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000571 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000572 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573}
574
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000575/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
576/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000577/// example:
578/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000579/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000580Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000581Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000582 bool Virtual, AccessSpecifier Access,
583 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000584 if (!classdecl)
585 return true;
586
Douglas Gregor40808ce2009-03-09 23:48:35 +0000587 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000588 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000589 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000590 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
591 Virtual, Access,
592 BaseType, BaseLoc))
593 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000596}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000597
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598/// \brief Performs the actual work of attaching the given base class
599/// specifiers to a C++ class.
600bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
601 unsigned NumBases) {
602 if (NumBases == 0)
603 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000604
605 // Used to keep track of which base types we have already seen, so
606 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000607 // that the key is always the unqualified canonical type of the base
608 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
610
611 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000612 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000613 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000614 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000615 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000617 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000618
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000619 if (KnownBaseTypes[NewBaseType]) {
620 // C++ [class.mi]p3:
621 // A class shall not be specified as a direct base class of a
622 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000623 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000624 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000625 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000627
628 // Delete the duplicate base class specifier; we're going to
629 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000630 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631
632 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000633 } else {
634 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635 KnownBaseTypes[NewBaseType] = Bases[idx];
636 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000637 }
638 }
639
640 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000641 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000642
643 // Delete the remaining (good) base class specifiers, since their
644 // data has been copied into the CXXRecordDecl.
645 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000646 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000647
648 return Invalid;
649}
650
651/// ActOnBaseSpecifiers - Attach the given base specifiers to the
652/// class, after checking whether there are any duplicate base
653/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000654void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000655 unsigned NumBases) {
656 if (!ClassDecl || !Bases || !NumBases)
657 return;
658
659 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000660 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000661 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000662}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000663
Douglas Gregora8f32e02009-10-06 17:59:45 +0000664/// \brief Determine whether the type \p Derived is a C++ class that is
665/// derived from the type \p Base.
666bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
667 if (!getLangOptions().CPlusPlus)
668 return false;
669
670 const RecordType *DerivedRT = Derived->getAs<RecordType>();
671 if (!DerivedRT)
672 return false;
673
674 const RecordType *BaseRT = Base->getAs<RecordType>();
675 if (!BaseRT)
676 return false;
677
678 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
679 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
680 return DerivedRD->isDerivedFrom(BaseRD);
681}
682
683/// \brief Determine whether the type \p Derived is a C++ class that is
684/// derived from the type \p Base.
685bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
686 if (!getLangOptions().CPlusPlus)
687 return false;
688
689 const RecordType *DerivedRT = Derived->getAs<RecordType>();
690 if (!DerivedRT)
691 return false;
692
693 const RecordType *BaseRT = Base->getAs<RecordType>();
694 if (!BaseRT)
695 return false;
696
697 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
698 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
699 return DerivedRD->isDerivedFrom(BaseRD, Paths);
700}
701
702/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
703/// conversion (where Derived and Base are class types) is
704/// well-formed, meaning that the conversion is unambiguous (and
705/// that all of the base classes are accessible). Returns true
706/// and emits a diagnostic if the code is ill-formed, returns false
707/// otherwise. Loc is the location where this routine should point to
708/// if there is an error, and Range is the source range to highlight
709/// if there is an error.
710bool
711Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
712 unsigned InaccessibleBaseID,
713 unsigned AmbigiousBaseConvID,
714 SourceLocation Loc, SourceRange Range,
715 DeclarationName Name) {
716 // First, determine whether the path from Derived to Base is
717 // ambiguous. This is slightly more expensive than checking whether
718 // the Derived to Base conversion exists, because here we need to
719 // explore multiple paths to determine if there is an ambiguity.
720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
721 /*DetectVirtual=*/false);
722 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
723 assert(DerivationOkay &&
724 "Can only be used with a derived-to-base conversion");
725 (void)DerivationOkay;
726
727 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000728 if (InaccessibleBaseID == 0)
729 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000730 // Check that the base class can be accessed.
731 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
732 Name);
733 }
734
735 // We know that the derived-to-base conversion is ambiguous, and
736 // we're going to produce a diagnostic. Perform the derived-to-base
737 // search just one more time to compute all of the possible paths so
738 // that we can print them out. This is more expensive than any of
739 // the previous derived-to-base checks we've done, but at this point
740 // performance isn't as much of an issue.
741 Paths.clear();
742 Paths.setRecordingPaths(true);
743 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
744 assert(StillOkay && "Can only be used with a derived-to-base conversion");
745 (void)StillOkay;
746
747 // Build up a textual representation of the ambiguous paths, e.g.,
748 // D -> B -> A, that will be used to illustrate the ambiguous
749 // conversions in the diagnostic. We only print one of the paths
750 // to each base class subobject.
751 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
752
753 Diag(Loc, AmbigiousBaseConvID)
754 << Derived << Base << PathDisplayStr << Range << Name;
755 return true;
756}
757
758bool
759Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000760 SourceLocation Loc, SourceRange Range,
761 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000762 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000763 IgnoreAccess ? 0 :
764 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000765 diag::err_ambiguous_derived_to_base_conv,
766 Loc, Range, DeclarationName());
767}
768
769
770/// @brief Builds a string representing ambiguous paths from a
771/// specific derived class to different subobjects of the same base
772/// class.
773///
774/// This function builds a string that can be used in error messages
775/// to show the different paths that one can take through the
776/// inheritance hierarchy to go from the derived class to different
777/// subobjects of a base class. The result looks something like this:
778/// @code
779/// struct D -> struct B -> struct A
780/// struct D -> struct C -> struct A
781/// @endcode
782std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
783 std::string PathDisplayStr;
784 std::set<unsigned> DisplayedPaths;
785 for (CXXBasePaths::paths_iterator Path = Paths.begin();
786 Path != Paths.end(); ++Path) {
787 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
788 // We haven't displayed a path to this particular base
789 // class subobject yet.
790 PathDisplayStr += "\n ";
791 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
792 for (CXXBasePath::const_iterator Element = Path->begin();
793 Element != Path->end(); ++Element)
794 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
795 }
796 }
797
798 return PathDisplayStr;
799}
800
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000801//===----------------------------------------------------------------------===//
802// C++ class member Handling
803//===----------------------------------------------------------------------===//
804
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000805/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
806/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
807/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000808/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000809Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000810Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000811 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000812 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
813 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000814 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000815 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000816 Expr *BitWidth = static_cast<Expr*>(BW);
817 Expr *Init = static_cast<Expr*>(InitExpr);
818 SourceLocation Loc = D.getIdentifierLoc();
819
Sebastian Redl669d5d72008-11-14 23:42:31 +0000820 bool isFunc = D.isFunctionDeclarator();
821
John McCall67d1a672009-08-06 02:15:43 +0000822 assert(!DS.isFriendSpecified());
823
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000824 // C++ 9.2p6: A member shall not be declared to have automatic storage
825 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000826 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
827 // data members and cannot be applied to names declared const or static,
828 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829 switch (DS.getStorageClassSpec()) {
830 case DeclSpec::SCS_unspecified:
831 case DeclSpec::SCS_typedef:
832 case DeclSpec::SCS_static:
833 // FALL THROUGH.
834 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000835 case DeclSpec::SCS_mutable:
836 if (isFunc) {
837 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000838 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000839 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000840 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Sebastian Redla11f42f2008-11-17 23:24:37 +0000842 // FIXME: It would be nicer if the keyword was ignored only for this
843 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000844 D.getMutableDeclSpec().ClearStorageClassSpecs();
845 } else {
846 QualType T = GetTypeForDeclarator(D, S);
847 diag::kind err = static_cast<diag::kind>(0);
848 if (T->isReferenceType())
849 err = diag::err_mutable_reference;
850 else if (T.isConstQualified())
851 err = diag::err_mutable_const;
852 if (err != 0) {
853 if (DS.getStorageClassSpecLoc().isValid())
854 Diag(DS.getStorageClassSpecLoc(), err);
855 else
856 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000857 // FIXME: It would be nicer if the keyword was ignored only for this
858 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000859 D.getMutableDeclSpec().ClearStorageClassSpecs();
860 }
861 }
862 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000863 default:
864 if (DS.getStorageClassSpecLoc().isValid())
865 Diag(DS.getStorageClassSpecLoc(),
866 diag::err_storageclass_invalid_for_member);
867 else
868 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
869 D.getMutableDeclSpec().ClearStorageClassSpecs();
870 }
871
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000872 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000873 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000874 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000875 // Check also for this case:
876 //
877 // typedef int f();
878 // f a;
879 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000880 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000881 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000882 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000883
Sebastian Redl669d5d72008-11-14 23:42:31 +0000884 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
885 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000886 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000887
888 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000889 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000890 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000891 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
892 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000893 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000894 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000895 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000896 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000897 if (!Member) {
898 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000899 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000900 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000901
902 // Non-instance-fields can't have a bitfield.
903 if (BitWidth) {
904 if (Member->isInvalidDecl()) {
905 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000906 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000907 // C++ 9.6p3: A bit-field shall not be a static member.
908 // "static member 'A' cannot be a bit-field"
909 Diag(Loc, diag::err_static_not_bitfield)
910 << Name << BitWidth->getSourceRange();
911 } else if (isa<TypedefDecl>(Member)) {
912 // "typedef member 'x' cannot be a bit-field"
913 Diag(Loc, diag::err_typedef_not_bitfield)
914 << Name << BitWidth->getSourceRange();
915 } else {
916 // A function typedef ("typedef int f(); f a;").
917 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
918 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000919 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000920 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Chris Lattner8b963ef2009-03-05 23:01:03 +0000923 DeleteExpr(BitWidth);
924 BitWidth = 0;
925 Member->setInvalidDecl();
926 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000927
928 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregor37b372b2009-08-20 22:52:58 +0000930 // If we have declared a member function template, set the access of the
931 // templated declaration as well.
932 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
933 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000934 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000935
Douglas Gregor10bd3682008-11-17 22:58:34 +0000936 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000937
Douglas Gregor021c3b32009-03-11 23:00:04 +0000938 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000939 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000940 if (Deleted) // FIXME: Source location is not very good.
941 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000942
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000943 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000944 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000945 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000946 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000947 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000948}
949
Douglas Gregor7ad83902008-11-05 04:29:56 +0000950/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000951Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000952Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000953 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000954 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000955 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000956 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000957 SourceLocation IdLoc,
958 SourceLocation LParenLoc,
959 ExprTy **Args, unsigned NumArgs,
960 SourceLocation *CommaLocs,
961 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000962 if (!ConstructorD)
963 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000965 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000966
967 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000968 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000969 if (!Constructor) {
970 // The user wrote a constructor initializer on a function that is
971 // not a C++ constructor. Ignore the error for now, because we may
972 // have more member initializers coming; we'll diagnose it just
973 // once in ActOnMemInitializers.
974 return true;
975 }
976
977 CXXRecordDecl *ClassDecl = Constructor->getParent();
978
979 // C++ [class.base.init]p2:
980 // Names in a mem-initializer-id are looked up in the scope of the
981 // constructor’s class and, if not found in that scope, are looked
982 // up in the scope containing the constructor’s
983 // definition. [Note: if the constructor’s class contains a member
984 // with the same name as a direct or virtual base class of the
985 // class, a mem-initializer-id naming the member or base class and
986 // composed of a single identifier refers to the class member. A
987 // mem-initializer-id for the hidden base class may be specified
988 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000989 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000990 // Look for a member, first.
991 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000992 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000993 = ClassDecl->lookup(MemberOrBase);
994 if (Result.first != Result.second)
995 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000996
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000997 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000998
Eli Friedman59c04372009-07-29 19:44:27 +0000999 if (Member)
1000 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001001 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001002 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001003 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001004 QualType BaseType;
1005
John McCalla93c9342009-12-07 02:54:59 +00001006 TypeSourceInfo *TInfo = 0;
Douglas Gregor802ab452009-12-02 22:36:29 +00001007 if (TemplateTypeTy)
John McCalla93c9342009-12-07 02:54:59 +00001008 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
Douglas Gregor802ab452009-12-02 22:36:29 +00001009 else
1010 BaseType = QualType::getFromOpaquePtr(getTypeName(*MemberOrBase, IdLoc,
1011 S, &SS));
1012 if (BaseType.isNull())
Chris Lattner3c73c412008-11-19 08:23:25 +00001013 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1014 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001015
John McCalla93c9342009-12-07 02:54:59 +00001016 if (!TInfo)
1017 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001018
John McCalla93c9342009-12-07 02:54:59 +00001019 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001020 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001021}
1022
John McCallb4190042009-11-04 23:02:40 +00001023/// Checks an initializer expression for use of uninitialized fields, such as
1024/// containing the field that is being initialized. Returns true if there is an
1025/// uninitialized field was used an updates the SourceLocation parameter; false
1026/// otherwise.
1027static bool InitExprContainsUninitializedFields(const Stmt* S,
1028 const FieldDecl* LhsField,
1029 SourceLocation* L) {
1030 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1031 if (ME) {
1032 const NamedDecl* RhsField = ME->getMemberDecl();
1033 if (RhsField == LhsField) {
1034 // Initializing a field with itself. Throw a warning.
1035 // But wait; there are exceptions!
1036 // Exception #1: The field may not belong to this record.
1037 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1038 const Expr* base = ME->getBase();
1039 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1040 // Even though the field matches, it does not belong to this record.
1041 return false;
1042 }
1043 // None of the exceptions triggered; return true to indicate an
1044 // uninitialized field was used.
1045 *L = ME->getMemberLoc();
1046 return true;
1047 }
1048 }
1049 bool found = false;
1050 for (Stmt::const_child_iterator it = S->child_begin();
1051 it != S->child_end() && found == false;
1052 ++it) {
1053 if (isa<CallExpr>(S)) {
1054 // Do not descend into function calls or constructors, as the use
1055 // of an uninitialized field may be valid. One would have to inspect
1056 // the contents of the function/ctor to determine if it is safe or not.
1057 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1058 // may be safe, depending on what the function/ctor does.
1059 continue;
1060 }
1061 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1062 }
1063 return found;
1064}
1065
Eli Friedman59c04372009-07-29 19:44:27 +00001066Sema::MemInitResult
1067Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1068 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001069 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001070 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001071 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1072 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1073 ExprTemporaries.clear();
1074
John McCallb4190042009-11-04 23:02:40 +00001075 // Diagnose value-uses of fields to initialize themselves, e.g.
1076 // foo(foo)
1077 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001078 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001079 for (unsigned i = 0; i < NumArgs; ++i) {
1080 SourceLocation L;
1081 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1082 // FIXME: Return true in the case when other fields are used before being
1083 // uninitialized. For example, let this field be the i'th field. When
1084 // initializing the i'th field, throw a warning if any of the >= i'th
1085 // fields are used, as they are not yet initialized.
1086 // Right now we are only handling the case where the i'th field uses
1087 // itself in its initializer.
1088 Diag(L, diag::warn_field_is_uninit);
1089 }
1090 }
1091
Eli Friedman59c04372009-07-29 19:44:27 +00001092 bool HasDependentArg = false;
1093 for (unsigned i = 0; i < NumArgs; i++)
1094 HasDependentArg |= Args[i]->isTypeDependent();
1095
1096 CXXConstructorDecl *C = 0;
1097 QualType FieldType = Member->getType();
1098 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1099 FieldType = Array->getElementType();
1100 if (FieldType->isDependentType()) {
1101 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001102 } else if (FieldType->isRecordType()) {
1103 // Member is a record (struct/union/class), so pass the initializer
1104 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001105 if (!HasDependentArg) {
1106 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1107
1108 C = PerformInitializationByConstructor(FieldType,
1109 MultiExprArg(*this,
1110 (void**)Args,
1111 NumArgs),
1112 IdLoc,
1113 SourceRange(IdLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001114 Member->getDeclName(),
1115 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001116 ConstructorArgs);
1117
1118 if (C) {
1119 // Take over the constructor arguments as our own.
1120 NumArgs = ConstructorArgs.size();
1121 Args = (Expr **)ConstructorArgs.take();
1122 }
1123 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001124 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001125 // The member type is not a record type (or an array of record
1126 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001127 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001128 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1129 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001130 Expr *NewExp;
1131 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001132 if (FieldType->isReferenceType()) {
1133 Diag(IdLoc, diag::err_null_intialized_reference_member)
1134 << Member->getDeclName();
1135 return Diag(Member->getLocation(), diag::note_declared_at);
1136 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001137 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1138 NumArgs = 1;
1139 }
1140 else
1141 NewExp = (Expr*)Args[0];
Douglas Gregor68647482009-12-16 03:45:30 +00001142 if (PerformCopyInitialization(NewExp, FieldType, AA_Passing))
Eli Friedman59c04372009-07-29 19:44:27 +00001143 return true;
1144 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001145 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001146
1147 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1148 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1149 ExprTemporaries.clear();
1150
Eli Friedman59c04372009-07-29 19:44:27 +00001151 // FIXME: Perform direct initialization of the member.
Douglas Gregor802ab452009-12-02 22:36:29 +00001152 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1153 C, LParenLoc, (Expr **)Args,
1154 NumArgs, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001155}
1156
1157Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001158Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001159 Expr **Args, unsigned NumArgs,
1160 SourceLocation LParenLoc, SourceLocation RParenLoc,
1161 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001162 bool HasDependentArg = false;
1163 for (unsigned i = 0; i < NumArgs; i++)
1164 HasDependentArg |= Args[i]->isTypeDependent();
1165
John McCalla93c9342009-12-07 02:54:59 +00001166 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman59c04372009-07-29 19:44:27 +00001167 if (!BaseType->isDependentType()) {
1168 if (!BaseType->isRecordType())
Douglas Gregor802ab452009-12-02 22:36:29 +00001169 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCalla93c9342009-12-07 02:54:59 +00001170 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001171
1172 // C++ [class.base.init]p2:
1173 // [...] Unless the mem-initializer-id names a nonstatic data
1174 // member of the constructor’s class or a direct or virtual base
1175 // of that class, the mem-initializer is ill-formed. A
1176 // mem-initializer-list can initialize a base class using any
1177 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Eli Friedman59c04372009-07-29 19:44:27 +00001179 // First, check for a direct base class.
1180 const CXXBaseSpecifier *DirectBaseSpec = 0;
1181 for (CXXRecordDecl::base_class_const_iterator Base =
1182 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001183 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001184 // We found a direct base of this type. That's what we're
1185 // initializing.
1186 DirectBaseSpec = &*Base;
1187 break;
1188 }
1189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Eli Friedman59c04372009-07-29 19:44:27 +00001191 // Check for a virtual base class.
1192 // FIXME: We might be able to short-circuit this if we know in advance that
1193 // there are no virtual bases.
1194 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1195 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1196 // We haven't found a base yet; search the class hierarchy for a
1197 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001198 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1199 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001200 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001201 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001202 Path != Paths.end(); ++Path) {
1203 if (Path->back().Base->isVirtual()) {
1204 VirtualBaseSpec = Path->back().Base;
1205 break;
1206 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001207 }
1208 }
1209 }
Eli Friedman59c04372009-07-29 19:44:27 +00001210
1211 // C++ [base.class.init]p2:
1212 // If a mem-initializer-id is ambiguous because it designates both
1213 // a direct non-virtual base class and an inherited virtual base
1214 // class, the mem-initializer is ill-formed.
1215 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001216 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCalla93c9342009-12-07 02:54:59 +00001217 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001218 // C++ [base.class.init]p2:
1219 // Unless the mem-initializer-id names a nonstatic data membeer of the
1220 // constructor's class ot a direst or virtual base of that class, the
1221 // mem-initializer is ill-formed.
1222 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001223 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1224 << BaseType << ClassDecl->getNameAsCString()
John McCalla93c9342009-12-07 02:54:59 +00001225 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregor7ad83902008-11-05 04:29:56 +00001226 }
1227
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001228 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001229 if (!BaseType->isDependentType() && !HasDependentArg) {
1230 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001231 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001232 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1233
1234 C = PerformInitializationByConstructor(BaseType,
1235 MultiExprArg(*this,
1236 (void**)Args, NumArgs),
Douglas Gregor802ab452009-12-02 22:36:29 +00001237 BaseLoc,
1238 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001239 Name,
1240 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001241 ConstructorArgs);
1242 if (C) {
1243 // Take over the constructor arguments as our own.
1244 NumArgs = ConstructorArgs.size();
1245 Args = (Expr **)ConstructorArgs.take();
1246 }
Eli Friedman59c04372009-07-29 19:44:27 +00001247 }
1248
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001249 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1250 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1251 ExprTemporaries.clear();
1252
John McCalla93c9342009-12-07 02:54:59 +00001253 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregor802ab452009-12-02 22:36:29 +00001254 LParenLoc, (Expr **)Args,
1255 NumArgs, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001256}
1257
Eli Friedman80c30da2009-11-09 19:20:36 +00001258bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001259Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001260 CXXBaseOrMemberInitializer **Initializers,
1261 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001262 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001263 // We need to build the initializer AST according to order of construction
1264 // and not what user specified in the Initializers list.
1265 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1266 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1267 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1268 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001269 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001271 for (unsigned i = 0; i < NumInitializers; i++) {
1272 CXXBaseOrMemberInitializer *Member = Initializers[i];
1273 if (Member->isBaseInitializer()) {
1274 if (Member->getBaseClass()->isDependentType())
1275 HasDependentBaseInit = true;
1276 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1277 } else {
1278 AllBaseFields[Member->getMember()] = Member;
1279 }
1280 }
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001282 if (HasDependentBaseInit) {
1283 // FIXME. This does not preserve the ordering of the initializers.
1284 // Try (with -Wreorder)
1285 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001286 // template<class X> struct B : A<X> {
1287 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001288 // int x1;
1289 // };
1290 // B<int> x;
1291 // On seeing one dependent type, we should essentially exit this routine
1292 // while preserving user-declared initializer list. When this routine is
1293 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001294 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001296 // If we have a dependent base initialization, we can't determine the
1297 // association between initializers and bases; just dump the known
1298 // initializers into the list, and don't try to deal with other bases.
1299 for (unsigned i = 0; i < NumInitializers; i++) {
1300 CXXBaseOrMemberInitializer *Member = Initializers[i];
1301 if (Member->isBaseInitializer())
1302 AllToInit.push_back(Member);
1303 }
1304 } else {
1305 // Push virtual bases before others.
1306 for (CXXRecordDecl::base_class_iterator VBase =
1307 ClassDecl->vbases_begin(),
1308 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1309 if (VBase->getType()->isDependentType())
1310 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001311 if (CXXBaseOrMemberInitializer *Value
1312 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001313 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001314 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001315 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001316 CXXRecordDecl *VBaseDecl =
Douglas Gregor802ab452009-12-02 22:36:29 +00001317 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001318 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001319 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001320 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001321 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1322 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1323 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001324 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001325 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001326 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001327 continue;
1328 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001329
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001330 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1331 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1332 Constructor->getLocation(), CtorArgs))
1333 continue;
1334
1335 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1336
Anders Carlsson8db68da2009-11-13 20:11:49 +00001337 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001338 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1339 // necessary.
1340 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001341 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001342 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001343 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001344 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001345 SourceLocation()),
1346 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001347 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001348 CtorArgs.takeAs<Expr>(),
1349 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001350 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001351 AllToInit.push_back(Member);
1352 }
1353 }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001355 for (CXXRecordDecl::base_class_iterator Base =
1356 ClassDecl->bases_begin(),
1357 E = ClassDecl->bases_end(); Base != E; ++Base) {
1358 // Virtuals are in the virtual base list and already constructed.
1359 if (Base->isVirtual())
1360 continue;
1361 // Skip dependent types.
1362 if (Base->getType()->isDependentType())
1363 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001364 if (CXXBaseOrMemberInitializer *Value
1365 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001366 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001367 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001368 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001369 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001370 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001371 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001372 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001373 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001374 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1375 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1376 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001377 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001378 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001379 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001380 continue;
1381 }
1382
1383 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1384 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1385 Constructor->getLocation(), CtorArgs))
1386 continue;
1387
1388 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001389
Anders Carlsson8db68da2009-11-13 20:11:49 +00001390 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001391 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1392 // necessary.
1393 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001394 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001395 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001396 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001397 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001398 SourceLocation()),
1399 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001400 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001401 CtorArgs.takeAs<Expr>(),
1402 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001403 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001404 AllToInit.push_back(Member);
1405 }
1406 }
1407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001409 // non-static data members.
1410 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1411 E = ClassDecl->field_end(); Field != E; ++Field) {
1412 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001413 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001414 Field->getType()->getAs<RecordType>()) {
1415 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001416 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001417 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001418 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1419 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1420 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1421 // set to the anonymous union data member used in the initializer
1422 // list.
1423 Value->setMember(*Field);
1424 Value->setAnonUnionMember(*FA);
1425 AllToInit.push_back(Value);
1426 break;
1427 }
1428 }
1429 }
1430 continue;
1431 }
1432 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1433 AllToInit.push_back(Value);
1434 continue;
1435 }
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Eli Friedman49c16da2009-11-09 01:05:47 +00001437 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001438 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001439
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001440 QualType FT = Context.getBaseElementType((*Field)->getType());
1441 if (const RecordType* RT = FT->getAs<RecordType>()) {
1442 CXXConstructorDecl *Ctor =
1443 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001444 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001445 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1446 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1447 << 1 << (*Field)->getDeclName();
1448 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001449 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001450 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001451 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001452 continue;
1453 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001454
1455 if (FT.isConstQualified() && Ctor->isTrivial()) {
1456 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1457 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1458 << 1 << (*Field)->getDeclName();
1459 Diag((*Field)->getLocation(), diag::note_declared_at);
1460 HadError = true;
1461 }
1462
1463 // Don't create initializers for trivial constructors, since they don't
1464 // actually need to be run.
1465 if (Ctor->isTrivial())
1466 continue;
1467
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001468 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1469 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1470 Constructor->getLocation(), CtorArgs))
1471 continue;
1472
Anders Carlsson8db68da2009-11-13 20:11:49 +00001473 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1474 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1475 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001476 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001477 new (Context) CXXBaseOrMemberInitializer(Context,
1478 *Field, SourceLocation(),
1479 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001480 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001481 CtorArgs.takeAs<Expr>(),
1482 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001483 SourceLocation());
1484
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001485 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001486 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001487 }
1488 else if (FT->isReferenceType()) {
1489 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001490 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1491 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001492 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001493 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001494 }
1495 else if (FT.isConstQualified()) {
1496 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001497 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1498 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001499 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001500 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001501 }
1502 }
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001504 NumInitializers = AllToInit.size();
1505 if (NumInitializers > 0) {
1506 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1507 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1508 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001510 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1511 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1512 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1513 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001514
1515 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001516}
1517
Eli Friedman6347f422009-07-21 19:28:10 +00001518static void *GetKeyForTopLevelField(FieldDecl *Field) {
1519 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001520 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001521 if (RT->getDecl()->isAnonymousStructOrUnion())
1522 return static_cast<void *>(RT->getDecl());
1523 }
1524 return static_cast<void *>(Field);
1525}
1526
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001527static void *GetKeyForBase(QualType BaseType) {
1528 if (const RecordType *RT = BaseType->getAs<RecordType>())
1529 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001531 assert(0 && "Unexpected base type!");
1532 return 0;
1533}
1534
Mike Stump1eb44332009-09-09 15:08:12 +00001535static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001536 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001537 // For fields injected into the class via declaration of an anonymous union,
1538 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001539 if (Member->isMemberInitializer()) {
1540 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Eli Friedman49c16da2009-11-09 01:05:47 +00001542 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001543 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001544 // in AnonUnionMember field.
1545 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1546 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001547 if (Field->getDeclContext()->isRecord()) {
1548 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1549 if (RD->isAnonymousStructOrUnion())
1550 return static_cast<void *>(RD);
1551 }
1552 return static_cast<void *>(Field);
1553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001555 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001556}
1557
John McCall6aee6212009-11-04 23:13:52 +00001558/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001559void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001560 SourceLocation ColonLoc,
1561 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001562 if (!ConstructorDecl)
1563 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001564
1565 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
1567 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001568 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Anders Carlssona7b35212009-03-25 02:58:17 +00001570 if (!Constructor) {
1571 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1572 return;
1573 }
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001575 if (!Constructor->isDependentContext()) {
1576 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1577 bool err = false;
1578 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001579 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001580 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1581 void *KeyToMember = GetKeyForMember(Member);
1582 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1583 if (!PrevMember) {
1584 PrevMember = Member;
1585 continue;
1586 }
1587 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001588 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001589 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001590 << Field->getNameAsString()
1591 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001592 else {
1593 Type *BaseClass = Member->getBaseClass();
1594 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001595 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001596 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001597 << QualType(BaseClass, 0)
1598 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001599 }
1600 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1601 << 0;
1602 err = true;
1603 }
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001605 if (err)
1606 return;
1607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Eli Friedman49c16da2009-11-09 01:05:47 +00001609 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001610 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001611 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001613 if (Constructor->isDependentContext())
1614 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001615
1616 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001617 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001618 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001619 Diagnostic::Ignored)
1620 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001622 // Also issue warning if order of ctor-initializer list does not match order
1623 // of 1) base class declarations and 2) order of non-static data members.
1624 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001626 CXXRecordDecl *ClassDecl
1627 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1628 // Push virtual bases before others.
1629 for (CXXRecordDecl::base_class_iterator VBase =
1630 ClassDecl->vbases_begin(),
1631 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001632 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001634 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1635 E = ClassDecl->bases_end(); Base != E; ++Base) {
1636 // Virtuals are alread in the virtual base list and are constructed
1637 // first.
1638 if (Base->isVirtual())
1639 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001640 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001641 }
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001643 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1644 E = ClassDecl->field_end(); Field != E; ++Field)
1645 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001647 int Last = AllBaseOrMembers.size();
1648 int curIndex = 0;
1649 CXXBaseOrMemberInitializer *PrevMember = 0;
1650 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001651 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001652 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1653 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001654
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001655 for (; curIndex < Last; curIndex++)
1656 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1657 break;
1658 if (curIndex == Last) {
1659 assert(PrevMember && "Member not in member list?!");
1660 // Initializer as specified in ctor-initializer list is out of order.
1661 // Issue a warning diagnostic.
1662 if (PrevMember->isBaseInitializer()) {
1663 // Diagnostics is for an initialized base class.
1664 Type *BaseClass = PrevMember->getBaseClass();
1665 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001666 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001667 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001668 } else {
1669 FieldDecl *Field = PrevMember->getMember();
1670 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001671 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001672 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001673 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001674 // Also the note!
1675 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001676 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001677 diag::note_fieldorbase_initialized_here) << 0
1678 << Field->getNameAsString();
1679 else {
1680 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001681 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001682 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001683 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001684 }
1685 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001686 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001687 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001688 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001689 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001690 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001691}
1692
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001693void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001694Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1695 // Ignore dependent destructors.
1696 if (Destructor->isDependentContext())
1697 return;
1698
1699 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Anders Carlsson9f853df2009-11-17 04:44:12 +00001701 // Non-static data members.
1702 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1703 E = ClassDecl->field_end(); I != E; ++I) {
1704 FieldDecl *Field = *I;
1705
1706 QualType FieldType = Context.getBaseElementType(Field->getType());
1707
1708 const RecordType* RT = FieldType->getAs<RecordType>();
1709 if (!RT)
1710 continue;
1711
1712 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1713 if (FieldClassDecl->hasTrivialDestructor())
1714 continue;
1715
1716 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1717 MarkDeclarationReferenced(Destructor->getLocation(),
1718 const_cast<CXXDestructorDecl*>(Dtor));
1719 }
1720
1721 // Bases.
1722 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1723 E = ClassDecl->bases_end(); Base != E; ++Base) {
1724 // Ignore virtual bases.
1725 if (Base->isVirtual())
1726 continue;
1727
1728 // Ignore trivial destructors.
1729 CXXRecordDecl *BaseClassDecl
1730 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1731 if (BaseClassDecl->hasTrivialDestructor())
1732 continue;
1733
1734 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1735 MarkDeclarationReferenced(Destructor->getLocation(),
1736 const_cast<CXXDestructorDecl*>(Dtor));
1737 }
1738
1739 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001740 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1741 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001742 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001743 CXXRecordDecl *BaseClassDecl
1744 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1745 if (BaseClassDecl->hasTrivialDestructor())
1746 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001747
1748 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1749 MarkDeclarationReferenced(Destructor->getLocation(),
1750 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001751 }
1752}
1753
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001754void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001755 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001756 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001758 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001759
1760 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001761 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001762 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001763}
1764
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001765namespace {
1766 /// PureVirtualMethodCollector - traverses a class and its superclasses
1767 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001768 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001769 ASTContext &Context;
1770
Sebastian Redldfe292d2009-03-22 21:28:55 +00001771 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001772 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001773
1774 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001775 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001777 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001779 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001780 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001781 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001783 MethodList List;
1784 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001786 // Copy the temporary list to methods, and make sure to ignore any
1787 // null entries.
1788 for (size_t i = 0, e = List.size(); i != e; ++i) {
1789 if (List[i])
1790 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001791 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001792 }
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001794 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001796 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1797 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001798 };
Mike Stump1eb44332009-09-09 15:08:12 +00001799
1800 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001801 MethodList& Methods) {
1802 // First, collect the pure virtual methods for the base classes.
1803 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1804 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001805 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001806 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001807 if (BaseDecl && BaseDecl->isAbstract())
1808 Collect(BaseDecl, Methods);
1809 }
1810 }
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001812 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001813 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001815 MethodSetTy OverriddenMethods;
1816 size_t MethodsSize = Methods.size();
1817
Mike Stump1eb44332009-09-09 15:08:12 +00001818 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001819 i != e; ++i) {
1820 // Traverse the record, looking for methods.
1821 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001822 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001823 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001824 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Anders Carlsson27823022009-10-18 19:34:08 +00001826 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001827 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1828 E = MD->end_overridden_methods(); I != E; ++I) {
1829 // Keep track of the overridden methods.
1830 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001831 }
1832 }
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
1835 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001836 // overridden.
1837 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1838 if (OverriddenMethods.count(Methods[i]))
1839 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001842 }
1843}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001844
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001845
Mike Stump1eb44332009-09-09 15:08:12 +00001846bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001847 unsigned DiagID, AbstractDiagSelID SelID,
1848 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001849 if (SelID == -1)
1850 return RequireNonAbstractType(Loc, T,
1851 PDiag(DiagID), CurrentRD);
1852 else
1853 return RequireNonAbstractType(Loc, T,
1854 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001855}
1856
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001857bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1858 const PartialDiagnostic &PD,
1859 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001860 if (!getLangOptions().CPlusPlus)
1861 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Anders Carlsson11f21a02009-03-23 19:10:31 +00001863 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001864 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001865 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Ted Kremenek6217b802009-07-29 21:53:49 +00001867 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001868 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001869 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001870 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001872 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001873 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001874 }
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Ted Kremenek6217b802009-07-29 21:53:49 +00001876 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001877 if (!RT)
1878 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001880 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1881 if (!RD)
1882 return false;
1883
Anders Carlssone65a3c82009-03-24 17:23:42 +00001884 if (CurrentRD && CurrentRD != RD)
1885 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001887 if (!RD->isAbstract())
1888 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001890 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001892 // Check if we've already emitted the list of pure virtual functions for this
1893 // class.
1894 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1895 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001897 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
1899 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001900 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1901 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001902
1903 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001904 MD->getDeclName();
1905 }
1906
1907 if (!PureVirtualClassDiagSet)
1908 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1909 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001911 return true;
1912}
1913
Anders Carlsson8211eff2009-03-24 01:19:16 +00001914namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001915 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001916 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1917 Sema &SemaRef;
1918 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Anders Carlssone65a3c82009-03-24 17:23:42 +00001920 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001921 bool Invalid = false;
1922
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001923 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1924 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001925 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001926
Anders Carlsson8211eff2009-03-24 01:19:16 +00001927 return Invalid;
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Anders Carlssone65a3c82009-03-24 17:23:42 +00001930 public:
1931 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1932 : SemaRef(SemaRef), AbstractClass(ac) {
1933 Visit(SemaRef.Context.getTranslationUnitDecl());
1934 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001935
Anders Carlssone65a3c82009-03-24 17:23:42 +00001936 bool VisitFunctionDecl(const FunctionDecl *FD) {
1937 if (FD->isThisDeclarationADefinition()) {
1938 // No need to do the check if we're in a definition, because it requires
1939 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001940 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001941 return VisitDeclContext(FD);
1942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Anders Carlssone65a3c82009-03-24 17:23:42 +00001944 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001945 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001946 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001947 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1948 diag::err_abstract_type_in_decl,
1949 Sema::AbstractReturnType,
1950 AbstractClass);
1951
Mike Stump1eb44332009-09-09 15:08:12 +00001952 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001953 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001954 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001955 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001956 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001957 VD->getOriginalType(),
1958 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001959 Sema::AbstractParamType,
1960 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001961 }
1962
1963 return Invalid;
1964 }
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Anders Carlssone65a3c82009-03-24 17:23:42 +00001966 bool VisitDecl(const Decl* D) {
1967 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1968 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Anders Carlssone65a3c82009-03-24 17:23:42 +00001970 return false;
1971 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001972 };
1973}
1974
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001975/// \brief Perform semantic checks on a class definition that has been
1976/// completing, introducing implicitly-declared members, checking for
1977/// abstract types, etc.
1978void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1979 if (!Record || Record->isInvalidDecl())
1980 return;
1981
Eli Friedmanff2d8782009-12-16 20:00:27 +00001982 if (!Record->isDependentType())
1983 AddImplicitlyDeclaredMembersToClass(Record);
1984
1985 if (Record->isInvalidDecl())
1986 return;
1987
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001988 if (!Record->isAbstract()) {
1989 // Collect all the pure virtual methods and see if this is an abstract
1990 // class after all.
1991 PureVirtualMethodCollector Collector(Context, Record);
1992 if (!Collector.empty())
1993 Record->setAbstract(true);
1994 }
1995
1996 if (Record->isAbstract())
1997 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001998}
1999
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002000void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002001 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002002 SourceLocation LBrac,
2003 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002004 if (!TagDecl)
2005 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Douglas Gregor42af25f2009-05-11 19:58:34 +00002007 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002008
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002009 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002010 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002011 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002012
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002013 CheckCompletedCXXClass(
2014 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002015}
2016
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002017/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2018/// special functions, such as the default constructor, copy
2019/// constructor, or destructor, to the given C++ class (C++
2020/// [special]p1). This routine can only be executed just before the
2021/// definition of the class is complete.
2022void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002023 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002024 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002025
Sebastian Redl465226e2009-05-27 22:11:52 +00002026 // FIXME: Implicit declarations have exception specifications, which are
2027 // the union of the specifications of the implicitly called functions.
2028
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002029 if (!ClassDecl->hasUserDeclaredConstructor()) {
2030 // C++ [class.ctor]p5:
2031 // A default constructor for a class X is a constructor of class X
2032 // that can be called without an argument. If there is no
2033 // user-declared constructor for class X, a default constructor is
2034 // implicitly declared. An implicitly-declared default constructor
2035 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002036 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002037 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002038 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002039 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002040 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002041 Context.getFunctionType(Context.VoidTy,
2042 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002043 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002044 /*isExplicit=*/false,
2045 /*isInline=*/true,
2046 /*isImplicitlyDeclared=*/true);
2047 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002048 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002049 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002050 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002051 }
2052
2053 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2054 // C++ [class.copy]p4:
2055 // If the class definition does not explicitly declare a copy
2056 // constructor, one is declared implicitly.
2057
2058 // C++ [class.copy]p5:
2059 // The implicitly-declared copy constructor for a class X will
2060 // have the form
2061 //
2062 // X::X(const X&)
2063 //
2064 // if
2065 bool HasConstCopyConstructor = true;
2066
2067 // -- each direct or virtual base class B of X has a copy
2068 // constructor whose first parameter is of type const B& or
2069 // const volatile B&, and
2070 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2071 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2072 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002073 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002074 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002075 = BaseClassDecl->hasConstCopyConstructor(Context);
2076 }
2077
2078 // -- for all the nonstatic data members of X that are of a
2079 // class type M (or array thereof), each such class type
2080 // has a copy constructor whose first parameter is of type
2081 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2083 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002084 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002085 QualType FieldType = (*Field)->getType();
2086 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2087 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002088 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002089 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002090 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002091 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002092 = FieldClassDecl->hasConstCopyConstructor(Context);
2093 }
2094 }
2095
Sebastian Redl64b45f72009-01-05 20:52:13 +00002096 // Otherwise, the implicitly declared copy constructor will have
2097 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002098 //
2099 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002100 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002101 if (HasConstCopyConstructor)
2102 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002103 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002104
Sebastian Redl64b45f72009-01-05 20:52:13 +00002105 // An implicitly-declared copy constructor is an inline public
2106 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002107 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002108 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002109 CXXConstructorDecl *CopyConstructor
2110 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002111 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002112 Context.getFunctionType(Context.VoidTy,
2113 &ArgType, 1,
2114 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002115 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002116 /*isExplicit=*/false,
2117 /*isInline=*/true,
2118 /*isImplicitlyDeclared=*/true);
2119 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002120 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002121 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002122
2123 // Add the parameter to the constructor.
2124 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2125 ClassDecl->getLocation(),
2126 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002127 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002128 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002129 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002130 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002131 }
2132
Sebastian Redl64b45f72009-01-05 20:52:13 +00002133 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2134 // Note: The following rules are largely analoguous to the copy
2135 // constructor rules. Note that virtual bases are not taken into account
2136 // for determining the argument type of the operator. Note also that
2137 // operators taking an object instead of a reference are allowed.
2138 //
2139 // C++ [class.copy]p10:
2140 // If the class definition does not explicitly declare a copy
2141 // assignment operator, one is declared implicitly.
2142 // The implicitly-defined copy assignment operator for a class X
2143 // will have the form
2144 //
2145 // X& X::operator=(const X&)
2146 //
2147 // if
2148 bool HasConstCopyAssignment = true;
2149
2150 // -- each direct base class B of X has a copy assignment operator
2151 // whose parameter is of type const B&, const volatile B& or B,
2152 // and
2153 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2154 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002155 assert(!Base->getType()->isDependentType() &&
2156 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002157 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002158 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002159 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002160 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002161 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002162 }
2163
2164 // -- for all the nonstatic data members of X that are of a class
2165 // type M (or array thereof), each such class type has a copy
2166 // assignment operator whose parameter is of type const M&,
2167 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002168 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2169 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002170 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002171 QualType FieldType = (*Field)->getType();
2172 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2173 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002174 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002175 const CXXRecordDecl *FieldClassDecl
2176 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002177 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002178 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002179 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002180 }
2181 }
2182
2183 // Otherwise, the implicitly declared copy assignment operator will
2184 // have the form
2185 //
2186 // X& X::operator=(X&)
2187 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002188 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002189 if (HasConstCopyAssignment)
2190 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002191 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002192
2193 // An implicitly-declared copy assignment operator is an inline public
2194 // member of its class.
2195 DeclarationName Name =
2196 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2197 CXXMethodDecl *CopyAssignment =
2198 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2199 Context.getFunctionType(RetType, &ArgType, 1,
2200 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002201 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002202 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002203 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002204 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002205 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002206
2207 // Add the parameter to the operator.
2208 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2209 ClassDecl->getLocation(),
2210 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002211 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002212 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002213 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002214
2215 // Don't call addedAssignmentOperator. There is no way to distinguish an
2216 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002217 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002218 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002219 }
2220
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002221 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002222 // C++ [class.dtor]p2:
2223 // If a class has no user-declared destructor, a destructor is
2224 // declared implicitly. An implicitly-declared destructor is an
2225 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002226 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002227 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002228 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002229 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002230 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002231 Context.getFunctionType(Context.VoidTy,
2232 0, 0, false, 0),
2233 /*isInline=*/true,
2234 /*isImplicitlyDeclared=*/true);
2235 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002236 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002237 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002238 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002239
2240 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002241 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002242}
2243
Douglas Gregor6569d682009-05-27 23:11:45 +00002244void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002245 Decl *D = TemplateD.getAs<Decl>();
2246 if (!D)
2247 return;
2248
2249 TemplateParameterList *Params = 0;
2250 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2251 Params = Template->getTemplateParameters();
2252 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2253 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2254 Params = PartialSpec->getTemplateParameters();
2255 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002256 return;
2257
Douglas Gregor6569d682009-05-27 23:11:45 +00002258 for (TemplateParameterList::iterator Param = Params->begin(),
2259 ParamEnd = Params->end();
2260 Param != ParamEnd; ++Param) {
2261 NamedDecl *Named = cast<NamedDecl>(*Param);
2262 if (Named->getDeclName()) {
2263 S->AddDecl(DeclPtrTy::make(Named));
2264 IdResolver.AddDecl(Named);
2265 }
2266 }
2267}
2268
John McCall7a1dc562009-12-19 10:49:29 +00002269void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2270 if (!RecordD) return;
2271 AdjustDeclIfTemplate(RecordD);
2272 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2273 PushDeclContext(S, Record);
2274}
2275
2276void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2277 if (!RecordD) return;
2278 PopDeclContext();
2279}
2280
Douglas Gregor72b505b2008-12-16 21:30:33 +00002281/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2282/// parsing a top-level (non-nested) C++ class, and we are now
2283/// parsing those parts of the given Method declaration that could
2284/// not be parsed earlier (C++ [class.mem]p2), such as default
2285/// arguments. This action should enter the scope of the given
2286/// Method declaration as if we had just parsed the qualified method
2287/// name. However, it should not bring the parameters into scope;
2288/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002289void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002290}
2291
2292/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2293/// C++ method declaration. We're (re-)introducing the given
2294/// function parameter into scope for use in parsing later parts of
2295/// the method declaration. For example, we could see an
2296/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002297void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002298 if (!ParamD)
2299 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Chris Lattnerb28317a2009-03-28 19:18:32 +00002301 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002302
2303 // If this parameter has an unparsed default argument, clear it out
2304 // to make way for the parsed default argument.
2305 if (Param->hasUnparsedDefaultArg())
2306 Param->setDefaultArg(0);
2307
Chris Lattnerb28317a2009-03-28 19:18:32 +00002308 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002309 if (Param->getDeclName())
2310 IdResolver.AddDecl(Param);
2311}
2312
2313/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2314/// processing the delayed method declaration for Method. The method
2315/// declaration is now considered finished. There may be a separate
2316/// ActOnStartOfFunctionDef action later (not necessarily
2317/// immediately!) for this method, if it was also defined inside the
2318/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002319void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002320 if (!MethodD)
2321 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002322
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002323 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Chris Lattnerb28317a2009-03-28 19:18:32 +00002325 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002326
2327 // Now that we have our default arguments, check the constructor
2328 // again. It could produce additional diagnostics or affect whether
2329 // the class has implicitly-declared destructors, among other
2330 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002331 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2332 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002333
2334 // Check the default arguments, which we may have added.
2335 if (!Method->isInvalidDecl())
2336 CheckCXXDefaultArguments(Method);
2337}
2338
Douglas Gregor42a552f2008-11-05 20:51:48 +00002339/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002340/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002341/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002342/// emit diagnostics and set the invalid bit to true. In any case, the type
2343/// will be updated to reflect a well-formed type for the constructor and
2344/// returned.
2345QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2346 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002347 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002348
2349 // C++ [class.ctor]p3:
2350 // A constructor shall not be virtual (10.3) or static (9.4). A
2351 // constructor can be invoked for a const, volatile or const
2352 // volatile object. A constructor shall not be declared const,
2353 // volatile, or const volatile (9.3.2).
2354 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002355 if (!D.isInvalidType())
2356 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2357 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2358 << SourceRange(D.getIdentifierLoc());
2359 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002360 }
2361 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002362 if (!D.isInvalidType())
2363 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2364 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2365 << SourceRange(D.getIdentifierLoc());
2366 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002367 SC = FunctionDecl::None;
2368 }
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Chris Lattner65401802009-04-25 08:28:21 +00002370 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2371 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002372 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002373 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2374 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002375 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002376 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2377 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002378 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002379 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2380 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002381 }
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Douglas Gregor42a552f2008-11-05 20:51:48 +00002383 // Rebuild the function type "R" without any type qualifiers (in
2384 // case any of the errors above fired) and with "void" as the
2385 // return type, since constructors don't have return types. We
2386 // *always* have to do this, because GetTypeForDeclarator will
2387 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002388 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002389 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2390 Proto->getNumArgs(),
2391 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002392}
2393
Douglas Gregor72b505b2008-12-16 21:30:33 +00002394/// CheckConstructor - Checks a fully-formed constructor for
2395/// well-formedness, issuing any diagnostics required. Returns true if
2396/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002397void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002398 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002399 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2400 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002401 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002402
2403 // C++ [class.copy]p3:
2404 // A declaration of a constructor for a class X is ill-formed if
2405 // its first parameter is of type (optionally cv-qualified) X and
2406 // either there are no other parameters or else all other
2407 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002408 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002409 ((Constructor->getNumParams() == 1) ||
2410 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002411 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2412 Constructor->getTemplateSpecializationKind()
2413 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002414 QualType ParamType = Constructor->getParamDecl(0)->getType();
2415 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2416 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002417 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2418 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002419 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002420
2421 // FIXME: Rather that making the constructor invalid, we should endeavor
2422 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002423 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002424 }
2425 }
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Douglas Gregor72b505b2008-12-16 21:30:33 +00002427 // Notify the class that we've added a constructor.
2428 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002429}
2430
Anders Carlsson37909802009-11-30 21:24:50 +00002431/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2432/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002433bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002434 CXXRecordDecl *RD = Destructor->getParent();
2435
2436 if (Destructor->isVirtual()) {
2437 SourceLocation Loc;
2438
2439 if (!Destructor->isImplicit())
2440 Loc = Destructor->getLocation();
2441 else
2442 Loc = RD->getLocation();
2443
2444 // If we have a virtual destructor, look up the deallocation function
2445 FunctionDecl *OperatorDelete = 0;
2446 DeclarationName Name =
2447 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002448 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002449 return true;
2450
2451 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002452 }
Anders Carlsson37909802009-11-30 21:24:50 +00002453
2454 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002455}
2456
Mike Stump1eb44332009-09-09 15:08:12 +00002457static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002458FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2459 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2460 FTI.ArgInfo[0].Param &&
2461 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2462}
2463
Douglas Gregor42a552f2008-11-05 20:51:48 +00002464/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2465/// the well-formednes of the destructor declarator @p D with type @p
2466/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002467/// emit diagnostics and set the declarator to invalid. Even if this happens,
2468/// will be updated to reflect a well-formed type for the destructor and
2469/// returned.
2470QualType Sema::CheckDestructorDeclarator(Declarator &D,
2471 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002472 // C++ [class.dtor]p1:
2473 // [...] A typedef-name that names a class is a class-name
2474 // (7.1.3); however, a typedef-name that names a class shall not
2475 // be used as the identifier in the declarator for a destructor
2476 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002477 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002478 if (isa<TypedefType>(DeclaratorType)) {
2479 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002480 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002481 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002482 }
2483
2484 // C++ [class.dtor]p2:
2485 // A destructor is used to destroy objects of its class type. A
2486 // destructor takes no parameters, and no return type can be
2487 // specified for it (not even void). The address of a destructor
2488 // shall not be taken. A destructor shall not be static. A
2489 // destructor can be invoked for a const, volatile or const
2490 // volatile object. A destructor shall not be declared const,
2491 // volatile or const volatile (9.3.2).
2492 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002493 if (!D.isInvalidType())
2494 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2495 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2496 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002497 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002498 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002499 }
Chris Lattner65401802009-04-25 08:28:21 +00002500 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002501 // Destructors don't have return types, but the parser will
2502 // happily parse something like:
2503 //
2504 // class X {
2505 // float ~X();
2506 // };
2507 //
2508 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002509 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2510 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2511 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002512 }
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Chris Lattner65401802009-04-25 08:28:21 +00002514 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2515 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002516 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002517 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2518 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002519 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002520 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2521 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002522 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002523 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2524 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002525 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002526 }
2527
2528 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002529 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002530 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2531
2532 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002533 FTI.freeArgs();
2534 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002535 }
2536
Mike Stump1eb44332009-09-09 15:08:12 +00002537 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002538 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002539 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002540 D.setInvalidType();
2541 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002542
2543 // Rebuild the function type "R" without any type qualifiers or
2544 // parameters (in case any of the errors above fired) and with
2545 // "void" as the return type, since destructors don't have return
2546 // types. We *always* have to do this, because GetTypeForDeclarator
2547 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002548 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002549}
2550
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002551/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2552/// well-formednes of the conversion function declarator @p D with
2553/// type @p R. If there are any errors in the declarator, this routine
2554/// will emit diagnostics and return true. Otherwise, it will return
2555/// false. Either way, the type @p R will be updated to reflect a
2556/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002557void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002558 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002559 // C++ [class.conv.fct]p1:
2560 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002561 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002562 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002563 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002564 if (!D.isInvalidType())
2565 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2566 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2567 << SourceRange(D.getIdentifierLoc());
2568 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002569 SC = FunctionDecl::None;
2570 }
Chris Lattner6e475012009-04-25 08:35:12 +00002571 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002572 // Conversion functions don't have return types, but the parser will
2573 // happily parse something like:
2574 //
2575 // class X {
2576 // float operator bool();
2577 // };
2578 //
2579 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002580 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2581 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2582 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002583 }
2584
2585 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002586 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002587 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2588
2589 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002590 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002591 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002592 }
2593
Mike Stump1eb44332009-09-09 15:08:12 +00002594 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002595 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002596 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002597 D.setInvalidType();
2598 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002599
2600 // C++ [class.conv.fct]p4:
2601 // The conversion-type-id shall not represent a function type nor
2602 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002603 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002604 if (ConvType->isArrayType()) {
2605 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2606 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002607 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002608 } else if (ConvType->isFunctionType()) {
2609 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2610 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002611 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002612 }
2613
2614 // Rebuild the function type "R" without any parameters (in case any
2615 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002616 // return type.
2617 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002618 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002619
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002620 // C++0x explicit conversion operators.
2621 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002622 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002623 diag::warn_explicit_conversion_functions)
2624 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002625}
2626
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002627/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2628/// the declaration of the given C++ conversion function. This routine
2629/// is responsible for recording the conversion function in the C++
2630/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002631Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002632 assert(Conversion && "Expected to receive a conversion function declaration");
2633
Douglas Gregor9d350972008-12-12 08:25:50 +00002634 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002635
2636 // Make sure we aren't redeclaring the conversion function.
2637 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002638
2639 // C++ [class.conv.fct]p1:
2640 // [...] A conversion function is never used to convert a
2641 // (possibly cv-qualified) object to the (possibly cv-qualified)
2642 // same object type (or a reference to it), to a (possibly
2643 // cv-qualified) base class of that type (or a reference to it),
2644 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002645 // FIXME: Suppress this warning if the conversion function ends up being a
2646 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002647 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002648 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002649 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002650 ConvType = ConvTypeRef->getPointeeType();
2651 if (ConvType->isRecordType()) {
2652 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2653 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002654 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002655 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002656 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002657 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002658 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002659 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002660 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002661 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002662 }
2663
Douglas Gregor70316a02008-12-26 15:00:45 +00002664 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002665 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002666 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002667 = Conversion->getDescribedFunctionTemplate())
2668 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002669 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2670 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002671 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002672 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002673 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002674 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002675 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002676 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002677
Chris Lattnerb28317a2009-03-28 19:18:32 +00002678 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002679}
2680
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002681//===----------------------------------------------------------------------===//
2682// Namespace Handling
2683//===----------------------------------------------------------------------===//
2684
2685/// ActOnStartNamespaceDef - This is called at the start of a namespace
2686/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002687Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2688 SourceLocation IdentLoc,
2689 IdentifierInfo *II,
2690 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002691 NamespaceDecl *Namespc =
2692 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2693 Namespc->setLBracLoc(LBrace);
2694
2695 Scope *DeclRegionScope = NamespcScope->getParent();
2696
2697 if (II) {
2698 // C++ [namespace.def]p2:
2699 // The identifier in an original-namespace-definition shall not have been
2700 // previously defined in the declarative region in which the
2701 // original-namespace-definition appears. The identifier in an
2702 // original-namespace-definition is the name of the namespace. Subsequently
2703 // in that declarative region, it is treated as an original-namespace-name.
2704
John McCallf36e02d2009-10-09 21:13:30 +00002705 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002706 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002707 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002708
Douglas Gregor44b43212008-12-11 16:49:14 +00002709 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2710 // This is an extended namespace definition.
2711 // Attach this namespace decl to the chain of extended namespace
2712 // definitions.
2713 OrigNS->setNextNamespace(Namespc);
2714 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002715
Mike Stump1eb44332009-09-09 15:08:12 +00002716 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002717 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002718 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002719 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002720 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002721 } else if (PrevDecl) {
2722 // This is an invalid name redefinition.
2723 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2724 << Namespc->getDeclName();
2725 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2726 Namespc->setInvalidDecl();
2727 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002728 } else if (II->isStr("std") &&
2729 CurContext->getLookupContext()->isTranslationUnit()) {
2730 // This is the first "real" definition of the namespace "std", so update
2731 // our cache of the "std" namespace to point at this definition.
2732 if (StdNamespace) {
2733 // We had already defined a dummy namespace "std". Link this new
2734 // namespace definition to the dummy namespace "std".
2735 StdNamespace->setNextNamespace(Namespc);
2736 StdNamespace->setLocation(IdentLoc);
2737 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2738 }
2739
2740 // Make our StdNamespace cache point at the first real definition of the
2741 // "std" namespace.
2742 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002743 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002744
2745 PushOnScopeChains(Namespc, DeclRegionScope);
2746 } else {
John McCall9aeed322009-10-01 00:25:31 +00002747 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002748 assert(Namespc->isAnonymousNamespace());
2749 CurContext->addDecl(Namespc);
2750
2751 // Link the anonymous namespace into its parent.
2752 NamespaceDecl *PrevDecl;
2753 DeclContext *Parent = CurContext->getLookupContext();
2754 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2755 PrevDecl = TU->getAnonymousNamespace();
2756 TU->setAnonymousNamespace(Namespc);
2757 } else {
2758 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2759 PrevDecl = ND->getAnonymousNamespace();
2760 ND->setAnonymousNamespace(Namespc);
2761 }
2762
2763 // Link the anonymous namespace with its previous declaration.
2764 if (PrevDecl) {
2765 assert(PrevDecl->isAnonymousNamespace());
2766 assert(!PrevDecl->getNextNamespace());
2767 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2768 PrevDecl->setNextNamespace(Namespc);
2769 }
John McCall9aeed322009-10-01 00:25:31 +00002770
2771 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2772 // behaves as if it were replaced by
2773 // namespace unique { /* empty body */ }
2774 // using namespace unique;
2775 // namespace unique { namespace-body }
2776 // where all occurrences of 'unique' in a translation unit are
2777 // replaced by the same identifier and this identifier differs
2778 // from all other identifiers in the entire program.
2779
2780 // We just create the namespace with an empty name and then add an
2781 // implicit using declaration, just like the standard suggests.
2782 //
2783 // CodeGen enforces the "universally unique" aspect by giving all
2784 // declarations semantically contained within an anonymous
2785 // namespace internal linkage.
2786
John McCall5fdd7642009-12-16 02:06:49 +00002787 if (!PrevDecl) {
2788 UsingDirectiveDecl* UD
2789 = UsingDirectiveDecl::Create(Context, CurContext,
2790 /* 'using' */ LBrace,
2791 /* 'namespace' */ SourceLocation(),
2792 /* qualifier */ SourceRange(),
2793 /* NNS */ NULL,
2794 /* identifier */ SourceLocation(),
2795 Namespc,
2796 /* Ancestor */ CurContext);
2797 UD->setImplicit();
2798 CurContext->addDecl(UD);
2799 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002800 }
2801
2802 // Although we could have an invalid decl (i.e. the namespace name is a
2803 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002804 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2805 // for the namespace has the declarations that showed up in that particular
2806 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002807 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002808 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002809}
2810
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002811/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2812/// is a namespace alias, returns the namespace it points to.
2813static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2814 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2815 return AD->getNamespace();
2816 return dyn_cast_or_null<NamespaceDecl>(D);
2817}
2818
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002819/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2820/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002821void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2822 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002823 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2824 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2825 Namespc->setRBracLoc(RBrace);
2826 PopDeclContext();
2827}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002828
Chris Lattnerb28317a2009-03-28 19:18:32 +00002829Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2830 SourceLocation UsingLoc,
2831 SourceLocation NamespcLoc,
2832 const CXXScopeSpec &SS,
2833 SourceLocation IdentLoc,
2834 IdentifierInfo *NamespcName,
2835 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002836 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2837 assert(NamespcName && "Invalid NamespcName.");
2838 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002839 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002840
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002841 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002842
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002843 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002844 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2845 LookupParsedName(R, S, &SS);
2846 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002847 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002848
John McCallf36e02d2009-10-09 21:13:30 +00002849 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002850 NamedDecl *Named = R.getFoundDecl();
2851 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2852 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002853 // C++ [namespace.udir]p1:
2854 // A using-directive specifies that the names in the nominated
2855 // namespace can be used in the scope in which the
2856 // using-directive appears after the using-directive. During
2857 // unqualified name lookup (3.4.1), the names appear as if they
2858 // were declared in the nearest enclosing namespace which
2859 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002860 // namespace. [Note: in this context, "contains" means "contains
2861 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002862
2863 // Find enclosing context containing both using-directive and
2864 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002865 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002866 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2867 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2868 CommonAncestor = CommonAncestor->getParent();
2869
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002870 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002871 SS.getRange(),
2872 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002873 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002874 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002875 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002876 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002877 }
2878
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002879 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002880 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002881 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002882}
2883
2884void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2885 // If scope has associated entity, then using directive is at namespace
2886 // or translation unit scope. We add UsingDirectiveDecls, into
2887 // it's lookup structure.
2888 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002889 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002890 else
2891 // Otherwise it is block-sope. using-directives will affect lookup
2892 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002893 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002894}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002895
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002896
2897Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002898 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00002899 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002900 SourceLocation UsingLoc,
2901 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002902 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002903 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002904 bool IsTypeName,
2905 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002906 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Douglas Gregor12c118a2009-11-04 16:30:06 +00002908 switch (Name.getKind()) {
2909 case UnqualifiedId::IK_Identifier:
2910 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002911 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002912 case UnqualifiedId::IK_ConversionFunctionId:
2913 break;
2914
2915 case UnqualifiedId::IK_ConstructorName:
John McCall604e7f12009-12-08 07:46:18 +00002916 // C++0x inherited constructors.
2917 if (getLangOptions().CPlusPlus0x) break;
2918
Douglas Gregor12c118a2009-11-04 16:30:06 +00002919 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2920 << SS.getRange();
2921 return DeclPtrTy();
2922
2923 case UnqualifiedId::IK_DestructorName:
2924 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2925 << SS.getRange();
2926 return DeclPtrTy();
2927
2928 case UnqualifiedId::IK_TemplateId:
2929 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2930 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2931 return DeclPtrTy();
2932 }
2933
2934 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00002935 if (!TargetName)
2936 return DeclPtrTy();
2937
John McCall60fa3cf2009-12-11 02:10:03 +00002938 // Warn about using declarations.
2939 // TODO: store that the declaration was written without 'using' and
2940 // talk about access decls instead of using decls in the
2941 // diagnostics.
2942 if (!HasUsingKeyword) {
2943 UsingLoc = Name.getSourceRange().getBegin();
2944
2945 Diag(UsingLoc, diag::warn_access_decl_deprecated)
2946 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
2947 "using ");
2948 }
2949
John McCall9488ea12009-11-17 05:59:44 +00002950 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002951 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002952 TargetName, AttrList,
2953 /* IsInstantiation */ false,
2954 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00002955 if (UD)
2956 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Anders Carlssonc72160b2009-08-28 05:40:36 +00002958 return DeclPtrTy::make(UD);
2959}
2960
John McCall9f54ad42009-12-10 09:41:52 +00002961/// Determines whether to create a using shadow decl for a particular
2962/// decl, given the set of decls existing prior to this using lookup.
2963bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2964 const LookupResult &Previous) {
2965 // Diagnose finding a decl which is not from a base class of the
2966 // current class. We do this now because there are cases where this
2967 // function will silently decide not to build a shadow decl, which
2968 // will pre-empt further diagnostics.
2969 //
2970 // We don't need to do this in C++0x because we do the check once on
2971 // the qualifier.
2972 //
2973 // FIXME: diagnose the following if we care enough:
2974 // struct A { int foo; };
2975 // struct B : A { using A::foo; };
2976 // template <class T> struct C : A {};
2977 // template <class T> struct D : C<T> { using B::foo; } // <---
2978 // This is invalid (during instantiation) in C++03 because B::foo
2979 // resolves to the using decl in B, which is not a base class of D<T>.
2980 // We can't diagnose it immediately because C<T> is an unknown
2981 // specialization. The UsingShadowDecl in D<T> then points directly
2982 // to A::foo, which will look well-formed when we instantiate.
2983 // The right solution is to not collapse the shadow-decl chain.
2984 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
2985 DeclContext *OrigDC = Orig->getDeclContext();
2986
2987 // Handle enums and anonymous structs.
2988 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
2989 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
2990 while (OrigRec->isAnonymousStructOrUnion())
2991 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
2992
2993 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
2994 if (OrigDC == CurContext) {
2995 Diag(Using->getLocation(),
2996 diag::err_using_decl_nested_name_specifier_is_current_class)
2997 << Using->getNestedNameRange();
2998 Diag(Orig->getLocation(), diag::note_using_decl_target);
2999 return true;
3000 }
3001
3002 Diag(Using->getNestedNameRange().getBegin(),
3003 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3004 << Using->getTargetNestedNameDecl()
3005 << cast<CXXRecordDecl>(CurContext)
3006 << Using->getNestedNameRange();
3007 Diag(Orig->getLocation(), diag::note_using_decl_target);
3008 return true;
3009 }
3010 }
3011
3012 if (Previous.empty()) return false;
3013
3014 NamedDecl *Target = Orig;
3015 if (isa<UsingShadowDecl>(Target))
3016 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3017
John McCalld7533ec2009-12-11 02:33:26 +00003018 // If the target happens to be one of the previous declarations, we
3019 // don't have a conflict.
3020 //
3021 // FIXME: but we might be increasing its access, in which case we
3022 // should redeclare it.
3023 NamedDecl *NonTag = 0, *Tag = 0;
3024 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3025 I != E; ++I) {
3026 NamedDecl *D = (*I)->getUnderlyingDecl();
3027 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3028 return false;
3029
3030 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3031 }
3032
John McCall9f54ad42009-12-10 09:41:52 +00003033 if (Target->isFunctionOrFunctionTemplate()) {
3034 FunctionDecl *FD;
3035 if (isa<FunctionTemplateDecl>(Target))
3036 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3037 else
3038 FD = cast<FunctionDecl>(Target);
3039
3040 NamedDecl *OldDecl = 0;
3041 switch (CheckOverload(FD, Previous, OldDecl)) {
3042 case Ovl_Overload:
3043 return false;
3044
3045 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003046 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003047 break;
3048
3049 // We found a decl with the exact signature.
3050 case Ovl_Match:
3051 if (isa<UsingShadowDecl>(OldDecl)) {
3052 // Silently ignore the possible conflict.
3053 return false;
3054 }
3055
3056 // If we're in a record, we want to hide the target, so we
3057 // return true (without a diagnostic) to tell the caller not to
3058 // build a shadow decl.
3059 if (CurContext->isRecord())
3060 return true;
3061
3062 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003063 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003064 break;
3065 }
3066
3067 Diag(Target->getLocation(), diag::note_using_decl_target);
3068 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3069 return true;
3070 }
3071
3072 // Target is not a function.
3073
John McCall9f54ad42009-12-10 09:41:52 +00003074 if (isa<TagDecl>(Target)) {
3075 // No conflict between a tag and a non-tag.
3076 if (!Tag) return false;
3077
John McCall41ce66f2009-12-10 19:51:03 +00003078 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003079 Diag(Target->getLocation(), diag::note_using_decl_target);
3080 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3081 return true;
3082 }
3083
3084 // No conflict between a tag and a non-tag.
3085 if (!NonTag) return false;
3086
John McCall41ce66f2009-12-10 19:51:03 +00003087 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003088 Diag(Target->getLocation(), diag::note_using_decl_target);
3089 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3090 return true;
3091}
3092
John McCall9488ea12009-11-17 05:59:44 +00003093/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003094UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003095 UsingDecl *UD,
3096 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003097
3098 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003099 NamedDecl *Target = Orig;
3100 if (isa<UsingShadowDecl>(Target)) {
3101 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3102 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003103 }
3104
3105 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003106 = UsingShadowDecl::Create(Context, CurContext,
3107 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003108 UD->addShadowDecl(Shadow);
3109
3110 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003111 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003112 else
John McCall604e7f12009-12-08 07:46:18 +00003113 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003114 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003115
John McCall604e7f12009-12-08 07:46:18 +00003116 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3117 Shadow->setInvalidDecl();
3118
John McCall9f54ad42009-12-10 09:41:52 +00003119 return Shadow;
3120}
John McCall604e7f12009-12-08 07:46:18 +00003121
John McCall9f54ad42009-12-10 09:41:52 +00003122/// Hides a using shadow declaration. This is required by the current
3123/// using-decl implementation when a resolvable using declaration in a
3124/// class is followed by a declaration which would hide or override
3125/// one or more of the using decl's targets; for example:
3126///
3127/// struct Base { void foo(int); };
3128/// struct Derived : Base {
3129/// using Base::foo;
3130/// void foo(int);
3131/// };
3132///
3133/// The governing language is C++03 [namespace.udecl]p12:
3134///
3135/// When a using-declaration brings names from a base class into a
3136/// derived class scope, member functions in the derived class
3137/// override and/or hide member functions with the same name and
3138/// parameter types in a base class (rather than conflicting).
3139///
3140/// There are two ways to implement this:
3141/// (1) optimistically create shadow decls when they're not hidden
3142/// by existing declarations, or
3143/// (2) don't create any shadow decls (or at least don't make them
3144/// visible) until we've fully parsed/instantiated the class.
3145/// The problem with (1) is that we might have to retroactively remove
3146/// a shadow decl, which requires several O(n) operations because the
3147/// decl structures are (very reasonably) not designed for removal.
3148/// (2) avoids this but is very fiddly and phase-dependent.
3149void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3150 // Remove it from the DeclContext...
3151 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003152
John McCall9f54ad42009-12-10 09:41:52 +00003153 // ...and the scope, if applicable...
3154 if (S) {
3155 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3156 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003157 }
3158
John McCall9f54ad42009-12-10 09:41:52 +00003159 // ...and the using decl.
3160 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3161
3162 // TODO: complain somehow if Shadow was used. It shouldn't
3163 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003164}
3165
John McCall7ba107a2009-11-18 02:36:19 +00003166/// Builds a using declaration.
3167///
3168/// \param IsInstantiation - Whether this call arises from an
3169/// instantiation of an unresolved using declaration. We treat
3170/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003171NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3172 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003173 const CXXScopeSpec &SS,
3174 SourceLocation IdentLoc,
3175 DeclarationName Name,
3176 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003177 bool IsInstantiation,
3178 bool IsTypeName,
3179 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003180 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3181 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003182
Anders Carlsson550b14b2009-08-28 05:49:21 +00003183 // FIXME: We ignore attributes for now.
3184 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003186 if (SS.isEmpty()) {
3187 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003188 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003189 }
Mike Stump1eb44332009-09-09 15:08:12 +00003190
John McCall9f54ad42009-12-10 09:41:52 +00003191 // Do the redeclaration lookup in the current scope.
3192 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3193 ForRedeclaration);
3194 Previous.setHideTags(false);
3195 if (S) {
3196 LookupName(Previous, S);
3197
3198 // It is really dumb that we have to do this.
3199 LookupResult::Filter F = Previous.makeFilter();
3200 while (F.hasNext()) {
3201 NamedDecl *D = F.next();
3202 if (!isDeclInScope(D, CurContext, S))
3203 F.erase();
3204 }
3205 F.done();
3206 } else {
3207 assert(IsInstantiation && "no scope in non-instantiation");
3208 assert(CurContext->isRecord() && "scope not record in instantiation");
3209 LookupQualifiedName(Previous, CurContext);
3210 }
3211
Mike Stump1eb44332009-09-09 15:08:12 +00003212 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003213 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3214
John McCall9f54ad42009-12-10 09:41:52 +00003215 // Check for invalid redeclarations.
3216 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3217 return 0;
3218
3219 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003220 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3221 return 0;
3222
John McCallaf8e6ed2009-11-12 03:15:40 +00003223 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003224 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003225 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003226 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003227 // FIXME: not all declaration name kinds are legal here
3228 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3229 UsingLoc, TypenameLoc,
3230 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003231 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003232 } else {
3233 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3234 UsingLoc, SS.getRange(), NNS,
3235 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003236 }
John McCalled976492009-12-04 22:46:56 +00003237 } else {
3238 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3239 SS.getRange(), UsingLoc, NNS, Name,
3240 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003241 }
John McCalled976492009-12-04 22:46:56 +00003242 D->setAccess(AS);
3243 CurContext->addDecl(D);
3244
3245 if (!LookupContext) return D;
3246 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003247
John McCall604e7f12009-12-08 07:46:18 +00003248 if (RequireCompleteDeclContext(SS)) {
3249 UD->setInvalidDecl();
3250 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003251 }
3252
John McCall604e7f12009-12-08 07:46:18 +00003253 // Look up the target name.
3254
John McCalla24dc2e2009-11-17 02:14:36 +00003255 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003256
John McCall604e7f12009-12-08 07:46:18 +00003257 // Unlike most lookups, we don't always want to hide tag
3258 // declarations: tag names are visible through the using declaration
3259 // even if hidden by ordinary names, *except* in a dependent context
3260 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003261 if (!IsInstantiation)
3262 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003263
John McCalla24dc2e2009-11-17 02:14:36 +00003264 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003265
John McCallf36e02d2009-10-09 21:13:30 +00003266 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003267 Diag(IdentLoc, diag::err_no_member)
3268 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003269 UD->setInvalidDecl();
3270 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003271 }
3272
John McCalled976492009-12-04 22:46:56 +00003273 if (R.isAmbiguous()) {
3274 UD->setInvalidDecl();
3275 return UD;
3276 }
Mike Stump1eb44332009-09-09 15:08:12 +00003277
John McCall7ba107a2009-11-18 02:36:19 +00003278 if (IsTypeName) {
3279 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003280 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003281 Diag(IdentLoc, diag::err_using_typename_non_type);
3282 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3283 Diag((*I)->getUnderlyingDecl()->getLocation(),
3284 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003285 UD->setInvalidDecl();
3286 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003287 }
3288 } else {
3289 // If we asked for a non-typename and we got a type, error out,
3290 // but only if this is an instantiation of an unresolved using
3291 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003292 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003293 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3294 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003295 UD->setInvalidDecl();
3296 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003297 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003298 }
3299
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003300 // C++0x N2914 [namespace.udecl]p6:
3301 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003302 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003303 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3304 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003305 UD->setInvalidDecl();
3306 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003307 }
Mike Stump1eb44332009-09-09 15:08:12 +00003308
John McCall9f54ad42009-12-10 09:41:52 +00003309 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3310 if (!CheckUsingShadowDecl(UD, *I, Previous))
3311 BuildUsingShadowDecl(S, UD, *I);
3312 }
John McCall9488ea12009-11-17 05:59:44 +00003313
3314 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003315}
3316
John McCall9f54ad42009-12-10 09:41:52 +00003317/// Checks that the given using declaration is not an invalid
3318/// redeclaration. Note that this is checking only for the using decl
3319/// itself, not for any ill-formedness among the UsingShadowDecls.
3320bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3321 bool isTypeName,
3322 const CXXScopeSpec &SS,
3323 SourceLocation NameLoc,
3324 const LookupResult &Prev) {
3325 // C++03 [namespace.udecl]p8:
3326 // C++0x [namespace.udecl]p10:
3327 // A using-declaration is a declaration and can therefore be used
3328 // repeatedly where (and only where) multiple declarations are
3329 // allowed.
3330 // That's only in file contexts.
3331 if (CurContext->getLookupContext()->isFileContext())
3332 return false;
3333
3334 NestedNameSpecifier *Qual
3335 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3336
3337 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3338 NamedDecl *D = *I;
3339
3340 bool DTypename;
3341 NestedNameSpecifier *DQual;
3342 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3343 DTypename = UD->isTypeName();
3344 DQual = UD->getTargetNestedNameDecl();
3345 } else if (UnresolvedUsingValueDecl *UD
3346 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3347 DTypename = false;
3348 DQual = UD->getTargetNestedNameSpecifier();
3349 } else if (UnresolvedUsingTypenameDecl *UD
3350 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3351 DTypename = true;
3352 DQual = UD->getTargetNestedNameSpecifier();
3353 } else continue;
3354
3355 // using decls differ if one says 'typename' and the other doesn't.
3356 // FIXME: non-dependent using decls?
3357 if (isTypeName != DTypename) continue;
3358
3359 // using decls differ if they name different scopes (but note that
3360 // template instantiation can cause this check to trigger when it
3361 // didn't before instantiation).
3362 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3363 Context.getCanonicalNestedNameSpecifier(DQual))
3364 continue;
3365
3366 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003367 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003368 return true;
3369 }
3370
3371 return false;
3372}
3373
John McCall604e7f12009-12-08 07:46:18 +00003374
John McCalled976492009-12-04 22:46:56 +00003375/// Checks that the given nested-name qualifier used in a using decl
3376/// in the current context is appropriately related to the current
3377/// scope. If an error is found, diagnoses it and returns true.
3378bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3379 const CXXScopeSpec &SS,
3380 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003381 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003382
John McCall604e7f12009-12-08 07:46:18 +00003383 if (!CurContext->isRecord()) {
3384 // C++03 [namespace.udecl]p3:
3385 // C++0x [namespace.udecl]p8:
3386 // A using-declaration for a class member shall be a member-declaration.
3387
3388 // If we weren't able to compute a valid scope, it must be a
3389 // dependent class scope.
3390 if (!NamedContext || NamedContext->isRecord()) {
3391 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3392 << SS.getRange();
3393 return true;
3394 }
3395
3396 // Otherwise, everything is known to be fine.
3397 return false;
3398 }
3399
3400 // The current scope is a record.
3401
3402 // If the named context is dependent, we can't decide much.
3403 if (!NamedContext) {
3404 // FIXME: in C++0x, we can diagnose if we can prove that the
3405 // nested-name-specifier does not refer to a base class, which is
3406 // still possible in some cases.
3407
3408 // Otherwise we have to conservatively report that things might be
3409 // okay.
3410 return false;
3411 }
3412
3413 if (!NamedContext->isRecord()) {
3414 // Ideally this would point at the last name in the specifier,
3415 // but we don't have that level of source info.
3416 Diag(SS.getRange().getBegin(),
3417 diag::err_using_decl_nested_name_specifier_is_not_class)
3418 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3419 return true;
3420 }
3421
3422 if (getLangOptions().CPlusPlus0x) {
3423 // C++0x [namespace.udecl]p3:
3424 // In a using-declaration used as a member-declaration, the
3425 // nested-name-specifier shall name a base class of the class
3426 // being defined.
3427
3428 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3429 cast<CXXRecordDecl>(NamedContext))) {
3430 if (CurContext == NamedContext) {
3431 Diag(NameLoc,
3432 diag::err_using_decl_nested_name_specifier_is_current_class)
3433 << SS.getRange();
3434 return true;
3435 }
3436
3437 Diag(SS.getRange().getBegin(),
3438 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3439 << (NestedNameSpecifier*) SS.getScopeRep()
3440 << cast<CXXRecordDecl>(CurContext)
3441 << SS.getRange();
3442 return true;
3443 }
3444
3445 return false;
3446 }
3447
3448 // C++03 [namespace.udecl]p4:
3449 // A using-declaration used as a member-declaration shall refer
3450 // to a member of a base class of the class being defined [etc.].
3451
3452 // Salient point: SS doesn't have to name a base class as long as
3453 // lookup only finds members from base classes. Therefore we can
3454 // diagnose here only if we can prove that that can't happen,
3455 // i.e. if the class hierarchies provably don't intersect.
3456
3457 // TODO: it would be nice if "definitely valid" results were cached
3458 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3459 // need to be repeated.
3460
3461 struct UserData {
3462 llvm::DenseSet<const CXXRecordDecl*> Bases;
3463
3464 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3465 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3466 Data->Bases.insert(Base);
3467 return true;
3468 }
3469
3470 bool hasDependentBases(const CXXRecordDecl *Class) {
3471 return !Class->forallBases(collect, this);
3472 }
3473
3474 /// Returns true if the base is dependent or is one of the
3475 /// accumulated base classes.
3476 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3477 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3478 return !Data->Bases.count(Base);
3479 }
3480
3481 bool mightShareBases(const CXXRecordDecl *Class) {
3482 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3483 }
3484 };
3485
3486 UserData Data;
3487
3488 // Returns false if we find a dependent base.
3489 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3490 return false;
3491
3492 // Returns false if the class has a dependent base or if it or one
3493 // of its bases is present in the base set of the current context.
3494 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3495 return false;
3496
3497 Diag(SS.getRange().getBegin(),
3498 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3499 << (NestedNameSpecifier*) SS.getScopeRep()
3500 << cast<CXXRecordDecl>(CurContext)
3501 << SS.getRange();
3502
3503 return true;
John McCalled976492009-12-04 22:46:56 +00003504}
3505
Mike Stump1eb44332009-09-09 15:08:12 +00003506Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003507 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003508 SourceLocation AliasLoc,
3509 IdentifierInfo *Alias,
3510 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003511 SourceLocation IdentLoc,
3512 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Anders Carlsson81c85c42009-03-28 23:53:49 +00003514 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003515 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3516 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003517
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003518 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003519 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003520 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003521 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003522 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003523 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003524 if (!R.isAmbiguous() && !R.empty() &&
3525 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003526 return DeclPtrTy();
3527 }
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003529 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3530 diag::err_redefinition_different_kind;
3531 Diag(AliasLoc, DiagID) << Alias;
3532 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003533 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003534 }
3535
John McCalla24dc2e2009-11-17 02:14:36 +00003536 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003537 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003538
John McCallf36e02d2009-10-09 21:13:30 +00003539 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003540 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003541 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003542 }
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003544 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003545 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3546 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003547 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003548 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003549
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003550 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003551 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003552}
3553
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003554void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3555 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003556 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3557 !Constructor->isUsed()) &&
3558 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003559
Eli Friedman80c30da2009-11-09 19:20:36 +00003560 CXXRecordDecl *ClassDecl
3561 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3562 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003563
Eli Friedman80c30da2009-11-09 19:20:36 +00003564 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003565 Diag(CurrentLocation, diag::note_member_synthesized_at)
3566 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003567 Constructor->setInvalidDecl();
3568 } else {
3569 Constructor->setUsed();
3570 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003571}
3572
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003573void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003574 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003575 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3576 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003577 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003578 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3579 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003580 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003581 // implicitly defined, all the implicitly-declared default destructors
3582 // for its base class and its non-static data members shall have been
3583 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003584 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3585 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003586 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003587 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003588 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003589 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003590 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3591 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3592 else
Mike Stump1eb44332009-09-09 15:08:12 +00003593 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003594 "DefineImplicitDestructor - missing dtor in a base class");
3595 }
3596 }
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003598 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3599 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003600 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3601 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3602 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003603 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003604 CXXRecordDecl *FieldClassDecl
3605 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3606 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003607 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003608 const_cast<CXXDestructorDecl*>(
3609 FieldClassDecl->getDestructor(Context)))
3610 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3611 else
Mike Stump1eb44332009-09-09 15:08:12 +00003612 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003613 "DefineImplicitDestructor - missing dtor in class of a data member");
3614 }
3615 }
3616 }
Anders Carlsson37909802009-11-30 21:24:50 +00003617
3618 // FIXME: If CheckDestructor fails, we should emit a note about where the
3619 // implicit destructor was needed.
3620 if (CheckDestructor(Destructor)) {
3621 Diag(CurrentLocation, diag::note_member_synthesized_at)
3622 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3623
3624 Destructor->setInvalidDecl();
3625 return;
3626 }
3627
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003628 Destructor->setUsed();
3629}
3630
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003631void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3632 CXXMethodDecl *MethodDecl) {
3633 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3634 MethodDecl->getOverloadedOperator() == OO_Equal &&
3635 !MethodDecl->isUsed()) &&
3636 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003637
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003638 CXXRecordDecl *ClassDecl
3639 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003641 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003642 // Before the implicitly-declared copy assignment operator for a class is
3643 // implicitly defined, all implicitly-declared copy assignment operators
3644 // for its direct base classes and its nonstatic data members shall have
3645 // been implicitly defined.
3646 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003647 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3648 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003649 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003650 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003651 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003652 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3653 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003654 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3655 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003656 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3657 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003658 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3659 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3660 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003661 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003662 CXXRecordDecl *FieldClassDecl
3663 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003664 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003665 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3666 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003667 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003668 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003669 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003670 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3671 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003672 Diag(CurrentLocation, diag::note_first_required_here);
3673 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003674 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003675 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003676 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3677 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003678 Diag(CurrentLocation, diag::note_first_required_here);
3679 err = true;
3680 }
3681 }
3682 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003683 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003684}
3685
3686CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003687Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3688 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003689 CXXRecordDecl *ClassDecl) {
3690 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3691 QualType RHSType(LHSType);
3692 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003693 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003694 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003695 RHSType = Context.getCVRQualifiedType(RHSType,
3696 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003697 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003698 LHSType,
3699 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003700 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003701 RHSType,
3702 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003703 Expr *Args[2] = { &*LHS, &*RHS };
3704 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003705 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003706 CandidateSet);
3707 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003708 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003709 return cast<CXXMethodDecl>(Best->Function);
3710 assert(false &&
3711 "getAssignOperatorMethod - copy assignment operator method not found");
3712 return 0;
3713}
3714
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003715void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3716 CXXConstructorDecl *CopyConstructor,
3717 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003718 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003719 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3720 !CopyConstructor->isUsed()) &&
3721 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003723 CXXRecordDecl *ClassDecl
3724 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3725 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003726 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003727 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003728 // implicitly defined, all the implicitly-declared copy constructors
3729 // for its base class and its non-static data members shall have been
3730 // implicitly defined.
3731 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3732 Base != ClassDecl->bases_end(); ++Base) {
3733 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003734 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003735 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003736 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003737 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003738 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003739 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3740 FieldEnd = ClassDecl->field_end();
3741 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003742 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3743 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3744 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003746 CXXRecordDecl *FieldClassDecl
3747 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003748 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003749 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003750 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003751 }
3752 }
3753 CopyConstructor->setUsed();
3754}
3755
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003756Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003757Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003758 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003759 MultiExprArg ExprArgs,
3760 bool RequiresZeroInit) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003761 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Douglas Gregor39da0b82009-09-09 23:08:42 +00003763 // C++ [class.copy]p15:
3764 // Whenever a temporary class object is copied using a copy constructor, and
3765 // this object and the copy have the same cv-unqualified type, an
3766 // implementation is permitted to treat the original and the copy as two
3767 // different ways of referring to the same object and not perform a copy at
3768 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003770 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003771 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003772 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003773 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3774 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3775 E = ICE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003776 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3777 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003778 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3779 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3780 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003781
3782 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3783 Elidable = !CE->getCallReturnType()->isReferenceType();
3784 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003785 Elidable = true;
3786 }
Mike Stump1eb44332009-09-09 15:08:12 +00003787
3788 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003789 Elidable, move(ExprArgs), RequiresZeroInit);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003790}
3791
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003792/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3793/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003794Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003795Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3796 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003797 MultiExprArg ExprArgs,
3798 bool RequiresZeroInit) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003799 unsigned NumExprs = ExprArgs.size();
3800 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Douglas Gregor7edfb692009-11-23 12:27:39 +00003802 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003803 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003804 Constructor, Elidable, Exprs, NumExprs,
3805 RequiresZeroInit));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003806}
3807
Anders Carlssone7624a72009-08-27 05:08:22 +00003808Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003809Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3810 QualType Ty,
3811 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003812 MultiExprArg Args,
3813 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003814 unsigned NumExprs = Args.size();
3815 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Douglas Gregor7edfb692009-11-23 12:27:39 +00003817 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003818 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3819 TyBeginLoc, Exprs,
3820 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003821}
3822
3823
Mike Stump1eb44332009-09-09 15:08:12 +00003824bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003825 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003826 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003827 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003828 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003829 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003830 if (TempResult.isInvalid())
3831 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003833 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003834 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003835 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor78d15832009-05-26 18:54:04 +00003836 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Anders Carlssonfe2de492009-08-25 05:18:00 +00003838 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003839}
3840
Mike Stump1eb44332009-09-09 15:08:12 +00003841void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003842 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003843 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003844 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003845 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003846 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003847 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003848}
3849
Mike Stump1eb44332009-09-09 15:08:12 +00003850/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003851/// ActOnDeclarator, when a C++ direct initializer is present.
3852/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003853void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3854 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003855 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003856 SourceLocation *CommaLocs,
3857 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003858 unsigned NumExprs = Exprs.size();
3859 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003860 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003861
3862 // If there is no declaration, there was an error parsing it. Just ignore
3863 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003864 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003865 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003867 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3868 if (!VDecl) {
3869 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3870 RealDecl->setInvalidDecl();
3871 return;
3872 }
3873
Douglas Gregor83ddad32009-08-26 21:14:46 +00003874 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003875 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003876 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3877 //
3878 // Clients that want to distinguish between the two forms, can check for
3879 // direct initializer using VarDecl::hasCXXDirectInitializer().
3880 // A major benefit is that clients that don't particularly care about which
3881 // exactly form was it (like the CodeGen) can handle both cases without
3882 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003883
Douglas Gregor83ddad32009-08-26 21:14:46 +00003884 // If either the declaration has a dependent type or if any of the expressions
3885 // is type-dependent, we represent the initialization via a ParenListExpr for
3886 // later use during template instantiation.
3887 if (VDecl->getType()->isDependentType() ||
3888 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3889 // Let clients know that initialization was done with a direct initializer.
3890 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Douglas Gregor83ddad32009-08-26 21:14:46 +00003892 // Store the initialization expressions as a ParenListExpr.
3893 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003894 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003895 new (Context) ParenListExpr(Context, LParenLoc,
3896 (Expr **)Exprs.release(),
3897 NumExprs, RParenLoc));
3898 return;
3899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Douglas Gregor83ddad32009-08-26 21:14:46 +00003901
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003902 // C++ 8.5p11:
3903 // The form of initialization (using parentheses or '=') is generally
3904 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003905 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003906 QualType DeclInitType = VDecl->getType();
3907 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003908 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003909
Douglas Gregor615c5d42009-03-24 16:43:20 +00003910 // FIXME: This isn't the right place to complete the type.
3911 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3912 diag::err_typecheck_decl_incomplete_type)) {
3913 VDecl->setInvalidDecl();
3914 return;
3915 }
3916
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003917 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003918 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3919
Douglas Gregor18fe5682008-11-03 20:45:27 +00003920 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003921 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003922 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003923 VDecl->getLocation(),
3924 SourceRange(VDecl->getLocation(),
3925 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003926 VDecl->getDeclName(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003927 InitializationKind::CreateDirect(VDecl->getLocation(),
3928 LParenLoc,
3929 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003930 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003931 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003932 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003933 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003934 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003935 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003936 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003937 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003938 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003939 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003940 return;
3941 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003942
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003943 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003944 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3945 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003946 RealDecl->setInvalidDecl();
3947 return;
3948 }
3949
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003950 // Let clients know that initialization was done with a direct initializer.
3951 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003952
3953 assert(NumExprs == 1 && "Expected 1 expression");
3954 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003955 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3956 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003957}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003958
Douglas Gregor19aeac62009-11-14 03:27:21 +00003959/// \brief Add the applicable constructor candidates for an initialization
3960/// by constructor.
3961static void AddConstructorInitializationCandidates(Sema &SemaRef,
3962 QualType ClassType,
3963 Expr **Args,
3964 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00003965 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003966 OverloadCandidateSet &CandidateSet) {
3967 // C++ [dcl.init]p14:
3968 // If the initialization is direct-initialization, or if it is
3969 // copy-initialization where the cv-unqualified version of the
3970 // source type is the same class as, or a derived class of, the
3971 // class of the destination, constructors are considered. The
3972 // applicable constructors are enumerated (13.3.1.3), and the
3973 // best one is chosen through overload resolution (13.3). The
3974 // constructor so selected is called to initialize the object,
3975 // with the initializer expression(s) as its argument(s). If no
3976 // constructor applies, or the overload resolution is ambiguous,
3977 // the initialization is ill-formed.
3978 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3979 assert(ClassRec && "Can only initialize a class type here");
3980
3981 // FIXME: When we decide not to synthesize the implicitly-declared
3982 // constructors, we'll need to make them appear here.
3983
3984 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3985 DeclarationName ConstructorName
3986 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3987 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3988 DeclContext::lookup_const_iterator Con, ConEnd;
3989 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3990 Con != ConEnd; ++Con) {
3991 // Find the constructor (which may be a template).
3992 CXXConstructorDecl *Constructor = 0;
3993 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3994 if (ConstructorTmpl)
3995 Constructor
3996 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3997 else
3998 Constructor = cast<CXXConstructorDecl>(*Con);
3999
Douglas Gregor20093b42009-12-09 23:02:17 +00004000 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4001 (Kind.getKind() == InitializationKind::IK_Value) ||
4002 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004003 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004004 ((Kind.getKind() == InitializationKind::IK_Default) &&
4005 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004006 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004007 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4008 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004009 Args, NumArgs, CandidateSet);
4010 else
4011 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
4012 }
4013 }
4014}
4015
4016/// \brief Attempt to perform initialization by constructor
4017/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4018/// copy-initialization.
4019///
4020/// This routine determines whether initialization by constructor is possible,
4021/// but it does not emit any diagnostics in the case where the initialization
4022/// is ill-formed.
4023///
4024/// \param ClassType the type of the object being initialized, which must have
4025/// class type.
4026///
4027/// \param Args the arguments provided to initialize the object
4028///
4029/// \param NumArgs the number of arguments provided to initialize the object
4030///
4031/// \param Kind the type of initialization being performed
4032///
4033/// \returns the constructor used to initialize the object, if successful.
4034/// Otherwise, emits a diagnostic and returns NULL.
4035CXXConstructorDecl *
4036Sema::TryInitializationByConstructor(QualType ClassType,
4037 Expr **Args, unsigned NumArgs,
4038 SourceLocation Loc,
4039 InitializationKind Kind) {
4040 // Build the overload candidate set
4041 OverloadCandidateSet CandidateSet;
4042 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4043 CandidateSet);
4044
4045 // Determine whether we found a constructor we can use.
4046 OverloadCandidateSet::iterator Best;
4047 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4048 case OR_Success:
4049 case OR_Deleted:
4050 // We found a constructor. Return it.
4051 return cast<CXXConstructorDecl>(Best->Function);
4052
4053 case OR_No_Viable_Function:
4054 case OR_Ambiguous:
4055 // Overload resolution failed. Return nothing.
4056 return 0;
4057 }
4058
4059 // Silence GCC warning
4060 return 0;
4061}
4062
Douglas Gregor39da0b82009-09-09 23:08:42 +00004063/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4064/// may occur as part of direct-initialization or copy-initialization.
4065///
4066/// \param ClassType the type of the object being initialized, which must have
4067/// class type.
4068///
4069/// \param ArgsPtr the arguments provided to initialize the object
4070///
4071/// \param Loc the source location where the initialization occurs
4072///
4073/// \param Range the source range that covers the entire initialization
4074///
4075/// \param InitEntity the name of the entity being initialized, if known
4076///
4077/// \param Kind the type of initialization being performed
4078///
4079/// \param ConvertedArgs a vector that will be filled in with the
4080/// appropriately-converted arguments to the constructor (if initialization
4081/// succeeded).
4082///
4083/// \returns the constructor used to initialize the object, if successful.
4084/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004085CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004086Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004087 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004088 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004089 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004090 InitializationKind Kind,
4091 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004092
4093 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004094 Expr **Args = (Expr **)ArgsPtr.get();
4095 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004096 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004097 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4098 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004099
Douglas Gregor18fe5682008-11-03 20:45:27 +00004100 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004101 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004102 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004103 // We found a constructor. Break out so that we can convert the arguments
4104 // appropriately.
4105 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Douglas Gregor18fe5682008-11-03 20:45:27 +00004107 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004108 if (InitEntity)
4109 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004110 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004111 else
4112 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004113 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00004114 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004115 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Douglas Gregor18fe5682008-11-03 20:45:27 +00004117 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004118 if (InitEntity)
4119 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4120 else
4121 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004122 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4123 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004124
4125 case OR_Deleted:
4126 if (InitEntity)
4127 Diag(Loc, diag::err_ovl_deleted_init)
4128 << Best->Function->isDeleted()
4129 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004130 else {
4131 const CXXRecordDecl *RD =
4132 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004133 Diag(Loc, diag::err_ovl_deleted_init)
4134 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004135 << RD->getDeclName() << Range;
4136 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004137 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4138 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004139 }
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Douglas Gregor39da0b82009-09-09 23:08:42 +00004141 // Convert the arguments, fill in default arguments, etc.
4142 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4143 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4144 return 0;
4145
4146 return Constructor;
4147}
4148
4149/// \brief Given a constructor and the set of arguments provided for the
4150/// constructor, convert the arguments and add any required default arguments
4151/// to form a proper call to this constructor.
4152///
4153/// \returns true if an error occurred, false otherwise.
4154bool
4155Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4156 MultiExprArg ArgsPtr,
4157 SourceLocation Loc,
4158 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4159 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4160 unsigned NumArgs = ArgsPtr.size();
4161 Expr **Args = (Expr **)ArgsPtr.get();
4162
4163 const FunctionProtoType *Proto
4164 = Constructor->getType()->getAs<FunctionProtoType>();
4165 assert(Proto && "Constructor without a prototype?");
4166 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004167
4168 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004169 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004170 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004171 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004172 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004173
4174 VariadicCallType CallType =
4175 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4176 llvm::SmallVector<Expr *, 8> AllArgs;
4177 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4178 Proto, 0, Args, NumArgs, AllArgs,
4179 CallType);
4180 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4181 ConvertedArgs.push_back(AllArgs[i]);
4182 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004183}
4184
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004185/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4186/// determine whether they are reference-related,
4187/// reference-compatible, reference-compatible with added
4188/// qualification, or incompatible, for use in C++ initialization by
4189/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4190/// type, and the first type (T1) is the pointee type of the reference
4191/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004192Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00004193Sema::CompareReferenceRelationship(SourceLocation Loc,
4194 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004195 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004196 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004197 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004198 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004199
Douglas Gregor393896f2009-11-05 13:06:35 +00004200 QualType T1 = Context.getCanonicalType(OrigT1);
4201 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00004202 QualType UnqualT1 = T1.getLocalUnqualifiedType();
4203 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004204
4205 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004206 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004207 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004208 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004209 if (UnqualT1 == UnqualT2)
4210 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004211 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4212 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4213 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004214 DerivedToBase = true;
4215 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004216 return Ref_Incompatible;
4217
4218 // At this point, we know that T1 and T2 are reference-related (at
4219 // least).
4220
4221 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004222 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004223 // reference-related to T2 and cv1 is the same cv-qualification
4224 // as, or greater cv-qualification than, cv2. For purposes of
4225 // overload resolution, cases for which cv1 is greater
4226 // cv-qualification than cv2 are identified as
4227 // reference-compatible with added qualification (see 13.3.3.2).
4228 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
4229 return Ref_Compatible;
4230 else if (T1.isMoreQualifiedThan(T2))
4231 return Ref_Compatible_With_Added_Qualification;
4232 else
4233 return Ref_Related;
4234}
4235
4236/// CheckReferenceInit - Check the initialization of a reference
4237/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4238/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004239/// list), and DeclType is the type of the declaration. When ICS is
4240/// non-null, this routine will compute the implicit conversion
4241/// sequence according to C++ [over.ics.ref] and will not produce any
4242/// diagnostics; when ICS is null, it will emit diagnostics when any
4243/// errors are found. Either way, a return value of true indicates
4244/// that there was a failure, a return value of false indicates that
4245/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004246///
4247/// When @p SuppressUserConversions, user-defined conversions are
4248/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004249/// When @p AllowExplicit, we also permit explicit user-defined
4250/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004251/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004252/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4253/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004254bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004255Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004256 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004257 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004258 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004259 ImplicitConversionSequence *ICS,
4260 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004261 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4262
Ted Kremenek6217b802009-07-29 21:53:49 +00004263 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004264 QualType T2 = Init->getType();
4265
Douglas Gregor904eed32008-11-10 20:40:00 +00004266 // If the initializer is the address of an overloaded function, try
4267 // to resolve the overloaded function. If all goes well, T2 is the
4268 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004269 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004270 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004271 ICS != 0);
4272 if (Fn) {
4273 // Since we're performing this reference-initialization for
4274 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004275 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004276 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004277 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004278
Anders Carlsson96ad5332009-10-21 17:16:23 +00004279 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004280 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004281
4282 T2 = Fn->getType();
4283 }
4284 }
4285
Douglas Gregor15da57e2008-10-29 02:00:59 +00004286 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004287 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004288 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004289 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4290 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004291 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004292 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004293
4294 // Most paths end in a failed conversion.
4295 if (ICS)
4296 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004297
4298 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004299 // A reference to type "cv1 T1" is initialized by an expression
4300 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004301
4302 // -- If the initializer expression
4303
Sebastian Redla9845802009-03-29 15:27:50 +00004304 // Rvalue references cannot bind to lvalues (N2812).
4305 // There is absolutely no situation where they can. In particular, note that
4306 // this is ill-formed, even if B has a user-defined conversion to A&&:
4307 // B b;
4308 // A&& r = b;
4309 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4310 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004311 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004312 << Init->getSourceRange();
4313 return true;
4314 }
4315
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004316 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004317 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4318 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004319 //
4320 // Note that the bit-field check is skipped if we are just computing
4321 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004322 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004323 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004324 BindsDirectly = true;
4325
Douglas Gregor15da57e2008-10-29 02:00:59 +00004326 if (ICS) {
4327 // C++ [over.ics.ref]p1:
4328 // When a parameter of reference type binds directly (8.5.3)
4329 // to an argument expression, the implicit conversion sequence
4330 // is the identity conversion, unless the argument expression
4331 // has a type that is a derived class of the parameter type,
4332 // in which case the implicit conversion sequence is a
4333 // derived-to-base Conversion (13.3.3.1).
4334 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4335 ICS->Standard.First = ICK_Identity;
4336 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4337 ICS->Standard.Third = ICK_Identity;
4338 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4339 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004340 ICS->Standard.ReferenceBinding = true;
4341 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004342 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004343 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004344
4345 // Nothing more to do: the inaccessibility/ambiguity check for
4346 // derived-to-base conversions is suppressed when we're
4347 // computing the implicit conversion sequence (C++
4348 // [over.best.ics]p2).
4349 return false;
4350 } else {
4351 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004352 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4353 if (DerivedToBase)
4354 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004355 else if(CheckExceptionSpecCompatibility(Init, T1))
4356 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004357 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004358 }
4359 }
4360
4361 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004362 // implicitly converted to an lvalue of type "cv3 T3,"
4363 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004364 // 92) (this conversion is selected by enumerating the
4365 // applicable conversion functions (13.3.1.6) and choosing
4366 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004367 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004368 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004369 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004370 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004371
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004372 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00004373 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004374 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00004375 for (UnresolvedSet::iterator I = Conversions->begin(),
4376 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004377 NamedDecl *D = *I;
4378 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4379 if (isa<UsingShadowDecl>(D))
4380 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4381
Mike Stump1eb44332009-09-09 15:08:12 +00004382 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004383 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004384 CXXConversionDecl *Conv;
4385 if (ConvTemplate)
4386 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4387 else
John McCall701c89e2009-12-03 04:06:58 +00004388 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004389
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004390 // If the conversion function doesn't return a reference type,
4391 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004392 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004393 (AllowExplicit || !Conv->isExplicit())) {
4394 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00004395 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4396 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004397 else
John McCall701c89e2009-12-03 04:06:58 +00004398 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004399 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004400 }
4401
4402 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004403 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004404 case OR_Success:
4405 // This is a direct binding.
4406 BindsDirectly = true;
4407
4408 if (ICS) {
4409 // C++ [over.ics.ref]p1:
4410 //
4411 // [...] If the parameter binds directly to the result of
4412 // applying a conversion function to the argument
4413 // expression, the implicit conversion sequence is a
4414 // user-defined conversion sequence (13.3.3.1.2), with the
4415 // second standard conversion sequence either an identity
4416 // conversion or, if the conversion function returns an
4417 // entity of a type that is a derived class of the parameter
4418 // type, a derived-to-base Conversion.
4419 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4420 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4421 ICS->UserDefined.After = Best->FinalConversion;
4422 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004423 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004424 assert(ICS->UserDefined.After.ReferenceBinding &&
4425 ICS->UserDefined.After.DirectBinding &&
4426 "Expected a direct reference binding!");
4427 return false;
4428 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004429 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004430 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004431 CastExpr::CK_UserDefinedConversion,
4432 cast<CXXMethodDecl>(Best->Function),
4433 Owned(Init));
4434 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004435
4436 if (CheckExceptionSpecCompatibility(Init, T1))
4437 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004438 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4439 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004440 }
4441 break;
4442
4443 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004444 if (ICS) {
4445 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4446 Cand != CandidateSet.end(); ++Cand)
4447 if (Cand->Viable)
4448 ICS->ConversionFunctionSet.push_back(Cand->Function);
4449 break;
4450 }
4451 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4452 << Init->getSourceRange();
4453 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004454 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004456 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004457 case OR_Deleted:
4458 // There was no suitable conversion, or we found a deleted
4459 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004460 break;
4461 }
4462 }
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004464 if (BindsDirectly) {
4465 // C++ [dcl.init.ref]p4:
4466 // [...] In all cases where the reference-related or
4467 // reference-compatible relationship of two types is used to
4468 // establish the validity of a reference binding, and T1 is a
4469 // base class of T2, a program that necessitates such a binding
4470 // is ill-formed if T1 is an inaccessible (clause 11) or
4471 // ambiguous (10.2) base class of T2.
4472 //
4473 // Note that we only check this condition when we're allowed to
4474 // complain about errors, because we should not be checking for
4475 // ambiguity (or inaccessibility) unless the reference binding
4476 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004477 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004478 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004479 Init->getSourceRange(),
4480 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004481 else
4482 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004483 }
4484
4485 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004486 // type (i.e., cv1 shall be const), or the reference shall be an
4487 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004488 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004489 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004490 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004491 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004492 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004493 return true;
4494 }
4495
4496 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004497 // class type, and "cv1 T1" is reference-compatible with
4498 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004499 // following ways (the choice is implementation-defined):
4500 //
4501 // -- The reference is bound to the object represented by
4502 // the rvalue (see 3.10) or to a sub-object within that
4503 // object.
4504 //
Eli Friedman33a31382009-08-05 19:21:58 +00004505 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004506 // a constructor is called to copy the entire rvalue
4507 // object into the temporary. The reference is bound to
4508 // the temporary or to a sub-object within the
4509 // temporary.
4510 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004511 // The constructor that would be used to make the copy
4512 // shall be callable whether or not the copy is actually
4513 // done.
4514 //
Sebastian Redla9845802009-03-29 15:27:50 +00004515 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004516 // freedom, so we will always take the first option and never build
4517 // a temporary in this case. FIXME: We will, however, have to check
4518 // for the presence of a copy constructor in C++98/03 mode.
4519 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004520 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4521 if (ICS) {
4522 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4523 ICS->Standard.First = ICK_Identity;
4524 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4525 ICS->Standard.Third = ICK_Identity;
4526 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4527 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004528 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004529 ICS->Standard.DirectBinding = false;
4530 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004531 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004532 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004533 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4534 if (DerivedToBase)
4535 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004536 else if(CheckExceptionSpecCompatibility(Init, T1))
4537 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004538 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004539 }
4540 return false;
4541 }
4542
Eli Friedman33a31382009-08-05 19:21:58 +00004543 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004544 // initialized from the initializer expression using the
4545 // rules for a non-reference copy initialization (8.5). The
4546 // reference is then bound to the temporary. If T1 is
4547 // reference-related to T2, cv1 must be the same
4548 // cv-qualification as, or greater cv-qualification than,
4549 // cv2; otherwise, the program is ill-formed.
4550 if (RefRelationship == Ref_Related) {
4551 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4552 // we would be reference-compatible or reference-compatible with
4553 // added qualification. But that wasn't the case, so the reference
4554 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004555 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004556 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004557 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004558 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004559 return true;
4560 }
4561
Douglas Gregor734d9862009-01-30 23:27:23 +00004562 // If at least one of the types is a class type, the types are not
4563 // related, and we aren't allowed any user conversions, the
4564 // reference binding fails. This case is important for breaking
4565 // recursion, since TryImplicitConversion below will attempt to
4566 // create a temporary through the use of a copy constructor.
4567 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4568 (T1->isRecordType() || T2->isRecordType())) {
4569 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004570 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004571 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004572 return true;
4573 }
4574
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004575 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004576 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004577 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004578 //
Sebastian Redla9845802009-03-29 15:27:50 +00004579 // When a parameter of reference type is not bound directly to
4580 // an argument expression, the conversion sequence is the one
4581 // required to convert the argument expression to the
4582 // underlying type of the reference according to
4583 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4584 // to copy-initializing a temporary of the underlying type with
4585 // the argument expression. Any difference in top-level
4586 // cv-qualification is subsumed by the initialization itself
4587 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004588 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4589 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004590 /*ForceRValue=*/false,
4591 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Sebastian Redla9845802009-03-29 15:27:50 +00004593 // Of course, that's still a reference binding.
4594 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4595 ICS->Standard.ReferenceBinding = true;
4596 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004597 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004598 ImplicitConversionSequence::UserDefinedConversion) {
4599 ICS->UserDefined.After.ReferenceBinding = true;
4600 ICS->UserDefined.After.RRefBinding = isRValRef;
4601 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004602 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4603 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004604 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004605 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004606 false, false,
4607 Conversions);
4608 if (badConversion) {
4609 if ((Conversions.ConversionKind ==
4610 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004611 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004612 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004613 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4614 for (int j = Conversions.ConversionFunctionSet.size()-1;
4615 j >= 0; j--) {
4616 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4617 Diag(Func->getLocation(), diag::err_ovl_candidate);
4618 }
4619 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004620 else {
4621 if (isRValRef)
4622 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4623 << Init->getSourceRange();
4624 else
4625 Diag(DeclLoc, diag::err_invalid_initialization)
4626 << DeclType << Init->getType() << Init->getSourceRange();
4627 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004628 }
4629 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004630 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004631}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004632
Anders Carlsson20d45d22009-12-12 00:32:00 +00004633static inline bool
4634CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4635 const FunctionDecl *FnDecl) {
4636 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4637 if (isa<NamespaceDecl>(DC)) {
4638 return SemaRef.Diag(FnDecl->getLocation(),
4639 diag::err_operator_new_delete_declared_in_namespace)
4640 << FnDecl->getDeclName();
4641 }
4642
4643 if (isa<TranslationUnitDecl>(DC) &&
4644 FnDecl->getStorageClass() == FunctionDecl::Static) {
4645 return SemaRef.Diag(FnDecl->getLocation(),
4646 diag::err_operator_new_delete_declared_static)
4647 << FnDecl->getDeclName();
4648 }
4649
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004650 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004651}
4652
Anders Carlsson156c78e2009-12-13 17:53:43 +00004653static inline bool
4654CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4655 CanQualType ExpectedResultType,
4656 CanQualType ExpectedFirstParamType,
4657 unsigned DependentParamTypeDiag,
4658 unsigned InvalidParamTypeDiag) {
4659 QualType ResultType =
4660 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4661
4662 // Check that the result type is not dependent.
4663 if (ResultType->isDependentType())
4664 return SemaRef.Diag(FnDecl->getLocation(),
4665 diag::err_operator_new_delete_dependent_result_type)
4666 << FnDecl->getDeclName() << ExpectedResultType;
4667
4668 // Check that the result type is what we expect.
4669 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4670 return SemaRef.Diag(FnDecl->getLocation(),
4671 diag::err_operator_new_delete_invalid_result_type)
4672 << FnDecl->getDeclName() << ExpectedResultType;
4673
4674 // A function template must have at least 2 parameters.
4675 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4676 return SemaRef.Diag(FnDecl->getLocation(),
4677 diag::err_operator_new_delete_template_too_few_parameters)
4678 << FnDecl->getDeclName();
4679
4680 // The function decl must have at least 1 parameter.
4681 if (FnDecl->getNumParams() == 0)
4682 return SemaRef.Diag(FnDecl->getLocation(),
4683 diag::err_operator_new_delete_too_few_parameters)
4684 << FnDecl->getDeclName();
4685
4686 // Check the the first parameter type is not dependent.
4687 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4688 if (FirstParamType->isDependentType())
4689 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4690 << FnDecl->getDeclName() << ExpectedFirstParamType;
4691
4692 // Check that the first parameter type is what we expect.
4693 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4694 ExpectedFirstParamType)
4695 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4696 << FnDecl->getDeclName() << ExpectedFirstParamType;
4697
4698 return false;
4699}
4700
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004701static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004702CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004703 // C++ [basic.stc.dynamic.allocation]p1:
4704 // A program is ill-formed if an allocation function is declared in a
4705 // namespace scope other than global scope or declared static in global
4706 // scope.
4707 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4708 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004709
4710 CanQualType SizeTy =
4711 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4712
4713 // C++ [basic.stc.dynamic.allocation]p1:
4714 // The return type shall be void*. The first parameter shall have type
4715 // std::size_t.
4716 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4717 SizeTy,
4718 diag::err_operator_new_dependent_param_type,
4719 diag::err_operator_new_param_type))
4720 return true;
4721
4722 // C++ [basic.stc.dynamic.allocation]p1:
4723 // The first parameter shall not have an associated default argument.
4724 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004725 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004726 diag::err_operator_new_default_arg)
4727 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4728
4729 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004730}
4731
4732static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004733CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4734 // C++ [basic.stc.dynamic.deallocation]p1:
4735 // A program is ill-formed if deallocation functions are declared in a
4736 // namespace scope other than global scope or declared static in global
4737 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004738 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4739 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004740
4741 // C++ [basic.stc.dynamic.deallocation]p2:
4742 // Each deallocation function shall return void and its first parameter
4743 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004744 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4745 SemaRef.Context.VoidPtrTy,
4746 diag::err_operator_delete_dependent_param_type,
4747 diag::err_operator_delete_param_type))
4748 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004749
Anders Carlsson46991d62009-12-12 00:16:02 +00004750 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4751 if (FirstParamType->isDependentType())
4752 return SemaRef.Diag(FnDecl->getLocation(),
4753 diag::err_operator_delete_dependent_param_type)
4754 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4755
4756 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4757 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004758 return SemaRef.Diag(FnDecl->getLocation(),
4759 diag::err_operator_delete_param_type)
4760 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004761
4762 return false;
4763}
4764
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004765/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4766/// of this overloaded operator is well-formed. If so, returns false;
4767/// otherwise, emits appropriate diagnostics and returns true.
4768bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004769 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004770 "Expected an overloaded operator declaration");
4771
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004772 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4773
Mike Stump1eb44332009-09-09 15:08:12 +00004774 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004775 // The allocation and deallocation functions, operator new,
4776 // operator new[], operator delete and operator delete[], are
4777 // described completely in 3.7.3. The attributes and restrictions
4778 // found in the rest of this subclause do not apply to them unless
4779 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004780 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004781 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004782
Anders Carlssona3ccda52009-12-12 00:26:23 +00004783 if (Op == OO_New || Op == OO_Array_New)
4784 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004785
4786 // C++ [over.oper]p6:
4787 // An operator function shall either be a non-static member
4788 // function or be a non-member function and have at least one
4789 // parameter whose type is a class, a reference to a class, an
4790 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004791 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4792 if (MethodDecl->isStatic())
4793 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004794 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004795 } else {
4796 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004797 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4798 ParamEnd = FnDecl->param_end();
4799 Param != ParamEnd; ++Param) {
4800 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004801 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4802 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004803 ClassOrEnumParam = true;
4804 break;
4805 }
4806 }
4807
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004808 if (!ClassOrEnumParam)
4809 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004810 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004811 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004812 }
4813
4814 // C++ [over.oper]p8:
4815 // An operator function cannot have default arguments (8.3.6),
4816 // except where explicitly stated below.
4817 //
Mike Stump1eb44332009-09-09 15:08:12 +00004818 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004819 // (C++ [over.call]p1).
4820 if (Op != OO_Call) {
4821 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4822 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004823 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004824 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004825 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004826 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004827 }
4828 }
4829
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004830 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4831 { false, false, false }
4832#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4833 , { Unary, Binary, MemberOnly }
4834#include "clang/Basic/OperatorKinds.def"
4835 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004836
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004837 bool CanBeUnaryOperator = OperatorUses[Op][0];
4838 bool CanBeBinaryOperator = OperatorUses[Op][1];
4839 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004840
4841 // C++ [over.oper]p8:
4842 // [...] Operator functions cannot have more or fewer parameters
4843 // than the number required for the corresponding operator, as
4844 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004845 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004846 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004847 if (Op != OO_Call &&
4848 ((NumParams == 1 && !CanBeUnaryOperator) ||
4849 (NumParams == 2 && !CanBeBinaryOperator) ||
4850 (NumParams < 1) || (NumParams > 2))) {
4851 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004852 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004853 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004854 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004855 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004856 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004857 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004858 assert(CanBeBinaryOperator &&
4859 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004860 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004861 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004862
Chris Lattner416e46f2008-11-21 07:57:12 +00004863 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004864 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004865 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004866
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004867 // Overloaded operators other than operator() cannot be variadic.
4868 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004869 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004870 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004871 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004872 }
4873
4874 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004875 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4876 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004877 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004878 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004879 }
4880
4881 // C++ [over.inc]p1:
4882 // The user-defined function called operator++ implements the
4883 // prefix and postfix ++ operator. If this function is a member
4884 // function with no parameters, or a non-member function with one
4885 // parameter of class or enumeration type, it defines the prefix
4886 // increment operator ++ for objects of that type. If the function
4887 // is a member function with one parameter (which shall be of type
4888 // int) or a non-member function with two parameters (the second
4889 // of which shall be of type int), it defines the postfix
4890 // increment operator ++ for objects of that type.
4891 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4892 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4893 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004894 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004895 ParamIsInt = BT->getKind() == BuiltinType::Int;
4896
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004897 if (!ParamIsInt)
4898 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004899 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004900 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004901 }
4902
Sebastian Redl64b45f72009-01-05 20:52:13 +00004903 // Notify the class if it got an assignment operator.
4904 if (Op == OO_Equal) {
4905 // Would have returned earlier otherwise.
4906 assert(isa<CXXMethodDecl>(FnDecl) &&
4907 "Overloaded = not member, but not filtered.");
4908 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4909 Method->getParent()->addedAssignmentOperator(Context, Method);
4910 }
4911
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004912 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004913}
Chris Lattner5a003a42008-12-17 07:09:26 +00004914
Douglas Gregor074149e2009-01-05 19:45:36 +00004915/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4916/// linkage specification, including the language and (if present)
4917/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4918/// the location of the language string literal, which is provided
4919/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4920/// the '{' brace. Otherwise, this linkage specification does not
4921/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004922Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4923 SourceLocation ExternLoc,
4924 SourceLocation LangLoc,
4925 const char *Lang,
4926 unsigned StrSize,
4927 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004928 LinkageSpecDecl::LanguageIDs Language;
4929 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4930 Language = LinkageSpecDecl::lang_c;
4931 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4932 Language = LinkageSpecDecl::lang_cxx;
4933 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004934 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004935 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004936 }
Mike Stump1eb44332009-09-09 15:08:12 +00004937
Chris Lattnercc98eac2008-12-17 07:13:27 +00004938 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004939
Douglas Gregor074149e2009-01-05 19:45:36 +00004940 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004941 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004942 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004943 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004944 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004945 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004946}
4947
Douglas Gregor074149e2009-01-05 19:45:36 +00004948/// ActOnFinishLinkageSpecification - Completely the definition of
4949/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4950/// valid, it's the position of the closing '}' brace in a linkage
4951/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004952Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4953 DeclPtrTy LinkageSpec,
4954 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004955 if (LinkageSpec)
4956 PopDeclContext();
4957 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004958}
4959
Douglas Gregord308e622009-05-18 20:51:54 +00004960/// \brief Perform semantic analysis for the variable declaration that
4961/// occurs within a C++ catch clause, returning the newly-created
4962/// variable.
4963VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004964 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004965 IdentifierInfo *Name,
4966 SourceLocation Loc,
4967 SourceRange Range) {
4968 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004969
4970 // Arrays and functions decay.
4971 if (ExDeclType->isArrayType())
4972 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4973 else if (ExDeclType->isFunctionType())
4974 ExDeclType = Context.getPointerType(ExDeclType);
4975
4976 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4977 // The exception-declaration shall not denote a pointer or reference to an
4978 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004979 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004980 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004981 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004982 Invalid = true;
4983 }
Douglas Gregord308e622009-05-18 20:51:54 +00004984
Sebastian Redl4b07b292008-12-22 19:15:10 +00004985 QualType BaseType = ExDeclType;
4986 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004987 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004988 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004989 BaseType = Ptr->getPointeeType();
4990 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004991 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004992 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004993 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004994 BaseType = Ref->getPointeeType();
4995 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004996 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004997 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004998 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004999 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005000 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005001
Mike Stump1eb44332009-09-09 15:08:12 +00005002 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005003 RequireNonAbstractType(Loc, ExDeclType,
5004 diag::err_abstract_type_in_decl,
5005 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005006 Invalid = true;
5007
Douglas Gregord308e622009-05-18 20:51:54 +00005008 // FIXME: Need to test for ability to copy-construct and destroy the
5009 // exception variable.
5010
Sebastian Redl8351da02008-12-22 21:35:02 +00005011 // FIXME: Need to check for abstract classes.
5012
Mike Stump1eb44332009-09-09 15:08:12 +00005013 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005014 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005015
5016 if (Invalid)
5017 ExDecl->setInvalidDecl();
5018
5019 return ExDecl;
5020}
5021
5022/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5023/// handler.
5024Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005025 TypeSourceInfo *TInfo = 0;
5026 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005027
5028 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005029 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005030 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005031 // The scope should be freshly made just for us. There is just no way
5032 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005033 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005034 if (PrevDecl->isTemplateParameter()) {
5035 // Maybe we will complain about the shadowed template parameter.
5036 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005037 }
5038 }
5039
Chris Lattnereaaebc72009-04-25 08:06:05 +00005040 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005041 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5042 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005043 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005044 }
5045
John McCalla93c9342009-12-07 02:54:59 +00005046 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005047 D.getIdentifier(),
5048 D.getIdentifierLoc(),
5049 D.getDeclSpec().getSourceRange());
5050
Chris Lattnereaaebc72009-04-25 08:06:05 +00005051 if (Invalid)
5052 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005053
Sebastian Redl4b07b292008-12-22 19:15:10 +00005054 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005055 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005056 PushOnScopeChains(ExDecl, S);
5057 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005058 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005059
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005060 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005061 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005062}
Anders Carlssonfb311762009-03-14 00:25:26 +00005063
Mike Stump1eb44332009-09-09 15:08:12 +00005064Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005065 ExprArg assertexpr,
5066 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005067 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005068 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005069 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5070
Anders Carlssonc3082412009-03-14 00:33:21 +00005071 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5072 llvm::APSInt Value(32);
5073 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5074 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5075 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005076 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005077 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005078
Anders Carlssonc3082412009-03-14 00:33:21 +00005079 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005080 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005081 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005082 }
5083 }
Mike Stump1eb44332009-09-09 15:08:12 +00005084
Anders Carlsson77d81422009-03-15 17:35:16 +00005085 assertexpr.release();
5086 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005087 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005088 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005089
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005090 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005091 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005092}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005093
John McCalldd4a3b02009-09-16 22:47:08 +00005094/// Handle a friend type declaration. This works in tandem with
5095/// ActOnTag.
5096///
5097/// Notes on friend class templates:
5098///
5099/// We generally treat friend class declarations as if they were
5100/// declaring a class. So, for example, the elaborated type specifier
5101/// in a friend declaration is required to obey the restrictions of a
5102/// class-head (i.e. no typedefs in the scope chain), template
5103/// parameters are required to match up with simple template-ids, &c.
5104/// However, unlike when declaring a template specialization, it's
5105/// okay to refer to a template specialization without an empty
5106/// template parameter declaration, e.g.
5107/// friend class A<T>::B<unsigned>;
5108/// We permit this as a special case; if there are any template
5109/// parameters present at all, require proper matching, i.e.
5110/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005111Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005112 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005113 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005114
5115 assert(DS.isFriendSpecified());
5116 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5117
John McCalldd4a3b02009-09-16 22:47:08 +00005118 // Try to convert the decl specifier to a type. This works for
5119 // friend templates because ActOnTag never produces a ClassTemplateDecl
5120 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005121 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005122 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5123 if (TheDeclarator.isInvalidType())
5124 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005125
John McCalldd4a3b02009-09-16 22:47:08 +00005126 // This is definitely an error in C++98. It's probably meant to
5127 // be forbidden in C++0x, too, but the specification is just
5128 // poorly written.
5129 //
5130 // The problem is with declarations like the following:
5131 // template <T> friend A<T>::foo;
5132 // where deciding whether a class C is a friend or not now hinges
5133 // on whether there exists an instantiation of A that causes
5134 // 'foo' to equal C. There are restrictions on class-heads
5135 // (which we declare (by fiat) elaborated friend declarations to
5136 // be) that makes this tractable.
5137 //
5138 // FIXME: handle "template <> friend class A<T>;", which
5139 // is possibly well-formed? Who even knows?
5140 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5141 Diag(Loc, diag::err_tagless_friend_type_template)
5142 << DS.getSourceRange();
5143 return DeclPtrTy();
5144 }
5145
John McCall02cace72009-08-28 07:59:38 +00005146 // C++ [class.friend]p2:
5147 // An elaborated-type-specifier shall be used in a friend declaration
5148 // for a class.*
5149 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005150 // This is one of the rare places in Clang where it's legitimate to
5151 // ask about the "spelling" of the type.
5152 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5153 // If we evaluated the type to a record type, suggest putting
5154 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005155 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005156 RecordDecl *RD = RT->getDecl();
5157
5158 std::string InsertionText = std::string(" ") + RD->getKindName();
5159
John McCalle3af0232009-10-07 23:34:25 +00005160 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5161 << (unsigned) RD->getTagKind()
5162 << T
5163 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005164 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5165 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005166 return DeclPtrTy();
5167 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005168 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5169 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005170 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005171 }
5172 }
5173
John McCalle3af0232009-10-07 23:34:25 +00005174 // Enum types cannot be friends.
5175 if (T->getAs<EnumType>()) {
5176 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5177 << SourceRange(DS.getFriendSpecLoc());
5178 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005179 }
John McCall02cace72009-08-28 07:59:38 +00005180
John McCall02cace72009-08-28 07:59:38 +00005181 // C++98 [class.friend]p1: A friend of a class is a function
5182 // or class that is not a member of the class . . .
5183 // But that's a silly restriction which nobody implements for
5184 // inner classes, and C++0x removes it anyway, so we only report
5185 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00005186 if (!getLangOptions().CPlusPlus0x)
5187 if (const RecordType *RT = T->getAs<RecordType>())
5188 if (RT->getDecl()->getDeclContext() == CurContext)
5189 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00005190
John McCalldd4a3b02009-09-16 22:47:08 +00005191 Decl *D;
5192 if (TempParams.size())
5193 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5194 TempParams.size(),
5195 (TemplateParameterList**) TempParams.release(),
5196 T.getTypePtr(),
5197 DS.getFriendSpecLoc());
5198 else
5199 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5200 DS.getFriendSpecLoc());
5201 D->setAccess(AS_public);
5202 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005203
John McCalldd4a3b02009-09-16 22:47:08 +00005204 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005205}
5206
John McCallbbbcdd92009-09-11 21:02:39 +00005207Sema::DeclPtrTy
5208Sema::ActOnFriendFunctionDecl(Scope *S,
5209 Declarator &D,
5210 bool IsDefinition,
5211 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005212 const DeclSpec &DS = D.getDeclSpec();
5213
5214 assert(DS.isFriendSpecified());
5215 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5216
5217 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005218 TypeSourceInfo *TInfo = 0;
5219 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005220
5221 // C++ [class.friend]p1
5222 // A friend of a class is a function or class....
5223 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005224 // It *doesn't* see through dependent types, which is correct
5225 // according to [temp.arg.type]p3:
5226 // If a declaration acquires a function type through a
5227 // type dependent on a template-parameter and this causes
5228 // a declaration that does not use the syntactic form of a
5229 // function declarator to have a function type, the program
5230 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005231 if (!T->isFunctionType()) {
5232 Diag(Loc, diag::err_unexpected_friend);
5233
5234 // It might be worthwhile to try to recover by creating an
5235 // appropriate declaration.
5236 return DeclPtrTy();
5237 }
5238
5239 // C++ [namespace.memdef]p3
5240 // - If a friend declaration in a non-local class first declares a
5241 // class or function, the friend class or function is a member
5242 // of the innermost enclosing namespace.
5243 // - The name of the friend is not found by simple name lookup
5244 // until a matching declaration is provided in that namespace
5245 // scope (either before or after the class declaration granting
5246 // friendship).
5247 // - If a friend function is called, its name may be found by the
5248 // name lookup that considers functions from namespaces and
5249 // classes associated with the types of the function arguments.
5250 // - When looking for a prior declaration of a class or a function
5251 // declared as a friend, scopes outside the innermost enclosing
5252 // namespace scope are not considered.
5253
John McCall02cace72009-08-28 07:59:38 +00005254 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5255 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005256 assert(Name);
5257
John McCall67d1a672009-08-06 02:15:43 +00005258 // The context we found the declaration in, or in which we should
5259 // create the declaration.
5260 DeclContext *DC;
5261
5262 // FIXME: handle local classes
5263
5264 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005265 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5266 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005267 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005268 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005269 DC = computeDeclContext(ScopeQual);
5270
5271 // FIXME: handle dependent contexts
5272 if (!DC) return DeclPtrTy();
5273
John McCall68263142009-11-18 22:49:29 +00005274 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005275
5276 // If searching in that context implicitly found a declaration in
5277 // a different context, treat it like it wasn't found at all.
5278 // TODO: better diagnostics for this case. Suggesting the right
5279 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005280 // FIXME: getRepresentativeDecl() is not right here at all
5281 if (Previous.empty() ||
5282 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005283 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005284 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5285 return DeclPtrTy();
5286 }
5287
5288 // C++ [class.friend]p1: A friend of a class is a function or
5289 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005290 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005291 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5292
John McCall67d1a672009-08-06 02:15:43 +00005293 // Otherwise walk out to the nearest namespace scope looking for matches.
5294 } else {
5295 // TODO: handle local class contexts.
5296
5297 DC = CurContext;
5298 while (true) {
5299 // Skip class contexts. If someone can cite chapter and verse
5300 // for this behavior, that would be nice --- it's what GCC and
5301 // EDG do, and it seems like a reasonable intent, but the spec
5302 // really only says that checks for unqualified existing
5303 // declarations should stop at the nearest enclosing namespace,
5304 // not that they should only consider the nearest enclosing
5305 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005306 while (DC->isRecord())
5307 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005308
John McCall68263142009-11-18 22:49:29 +00005309 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005310
5311 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005312 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005313 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005314
John McCall67d1a672009-08-06 02:15:43 +00005315 if (DC->isFileContext()) break;
5316 DC = DC->getParent();
5317 }
5318
5319 // C++ [class.friend]p1: A friend of a class is a function or
5320 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005321 // C++0x changes this for both friend types and functions.
5322 // Most C++ 98 compilers do seem to give an error here, so
5323 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005324 if (!Previous.empty() && DC->Equals(CurContext)
5325 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005326 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5327 }
5328
Douglas Gregor182ddf02009-09-28 00:08:27 +00005329 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005330 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005331 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5332 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5333 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005334 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005335 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5336 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005337 return DeclPtrTy();
5338 }
John McCall67d1a672009-08-06 02:15:43 +00005339 }
5340
Douglas Gregor182ddf02009-09-28 00:08:27 +00005341 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005342 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005343 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005344 IsDefinition,
5345 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005346 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005347
Douglas Gregor182ddf02009-09-28 00:08:27 +00005348 assert(ND->getDeclContext() == DC);
5349 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005350
John McCallab88d972009-08-31 22:39:49 +00005351 // Add the function declaration to the appropriate lookup tables,
5352 // adjusting the redeclarations list as necessary. We don't
5353 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005354 //
John McCallab88d972009-08-31 22:39:49 +00005355 // Also update the scope-based lookup if the target context's
5356 // lookup context is in lexical scope.
5357 if (!CurContext->isDependentContext()) {
5358 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005359 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005360 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005361 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005362 }
John McCall02cace72009-08-28 07:59:38 +00005363
5364 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005365 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005366 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005367 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005368 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005369
Douglas Gregor182ddf02009-09-28 00:08:27 +00005370 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005371}
5372
Chris Lattnerb28317a2009-03-28 19:18:32 +00005373void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005374 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005375
Chris Lattnerb28317a2009-03-28 19:18:32 +00005376 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005377 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5378 if (!Fn) {
5379 Diag(DelLoc, diag::err_deleted_non_function);
5380 return;
5381 }
5382 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5383 Diag(DelLoc, diag::err_deleted_decl_not_first);
5384 Diag(Prev->getLocation(), diag::note_previous_declaration);
5385 // If the declaration wasn't the first, we delete the function anyway for
5386 // recovery.
5387 }
5388 Fn->setDeleted();
5389}
Sebastian Redl13e88542009-04-27 21:33:24 +00005390
5391static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5392 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5393 ++CI) {
5394 Stmt *SubStmt = *CI;
5395 if (!SubStmt)
5396 continue;
5397 if (isa<ReturnStmt>(SubStmt))
5398 Self.Diag(SubStmt->getSourceRange().getBegin(),
5399 diag::err_return_in_constructor_handler);
5400 if (!isa<Expr>(SubStmt))
5401 SearchForReturnInStmt(Self, SubStmt);
5402 }
5403}
5404
5405void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5406 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5407 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5408 SearchForReturnInStmt(*this, Handler);
5409 }
5410}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005411
Mike Stump1eb44332009-09-09 15:08:12 +00005412bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005413 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005414 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5415 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005416
5417 QualType CNewTy = Context.getCanonicalType(NewTy);
5418 QualType COldTy = Context.getCanonicalType(OldTy);
5419
Mike Stump1eb44332009-09-09 15:08:12 +00005420 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00005421 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005424 // Check if the return types are covariant
5425 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005426
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005427 /// Both types must be pointers or references to classes.
5428 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5429 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5430 NewClassTy = NewPT->getPointeeType();
5431 OldClassTy = OldPT->getPointeeType();
5432 }
5433 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5434 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5435 NewClassTy = NewRT->getPointeeType();
5436 OldClassTy = OldRT->getPointeeType();
5437 }
5438 }
Mike Stump1eb44332009-09-09 15:08:12 +00005439
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005440 // The return types aren't either both pointers or references to a class type.
5441 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005442 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005443 diag::err_different_return_type_for_overriding_virtual_function)
5444 << New->getDeclName() << NewTy << OldTy;
5445 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005446
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005447 return true;
5448 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005449
Douglas Gregora4923eb2009-11-16 21:35:15 +00005450 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005451 // Check if the new class derives from the old class.
5452 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5453 Diag(New->getLocation(),
5454 diag::err_covariant_return_not_derived)
5455 << New->getDeclName() << NewTy << OldTy;
5456 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5457 return true;
5458 }
Mike Stump1eb44332009-09-09 15:08:12 +00005459
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005460 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005461 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005462 diag::err_covariant_return_inaccessible_base,
5463 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5464 // FIXME: Should this point to the return type?
5465 New->getLocation(), SourceRange(), New->getDeclName())) {
5466 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5467 return true;
5468 }
5469 }
Mike Stump1eb44332009-09-09 15:08:12 +00005470
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005471 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005472 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005473 Diag(New->getLocation(),
5474 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005475 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005476 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5477 return true;
5478 };
Mike Stump1eb44332009-09-09 15:08:12 +00005479
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005480
5481 // The new class type must have the same or less qualifiers as the old type.
5482 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5483 Diag(New->getLocation(),
5484 diag::err_covariant_return_type_class_type_more_qualified)
5485 << New->getDeclName() << NewTy << OldTy;
5486 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5487 return true;
5488 };
Mike Stump1eb44332009-09-09 15:08:12 +00005489
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005490 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005491}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005492
Sean Huntbbd37c62009-11-21 08:43:09 +00005493bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5494 const CXXMethodDecl *Old)
5495{
5496 if (Old->hasAttr<FinalAttr>()) {
5497 Diag(New->getLocation(), diag::err_final_function_overridden)
5498 << New->getDeclName();
5499 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5500 return true;
5501 }
5502
5503 return false;
5504}
5505
Douglas Gregor4ba31362009-12-01 17:24:26 +00005506/// \brief Mark the given method pure.
5507///
5508/// \param Method the method to be marked pure.
5509///
5510/// \param InitRange the source range that covers the "0" initializer.
5511bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5512 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5513 Method->setPure();
5514
5515 // A class is abstract if at least one function is pure virtual.
5516 Method->getParent()->setAbstract(true);
5517 return false;
5518 }
5519
5520 if (!Method->isInvalidDecl())
5521 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5522 << Method->getDeclName() << InitRange;
5523 return true;
5524}
5525
John McCall731ad842009-12-19 09:28:58 +00005526/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5527/// an initializer for the out-of-line declaration 'Dcl'. The scope
5528/// is a fresh scope pushed for just this purpose.
5529///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005530/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5531/// static data member of class X, names should be looked up in the scope of
5532/// class X.
5533void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005534 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005535 Decl *D = Dcl.getAs<Decl>();
5536 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005537
John McCall731ad842009-12-19 09:28:58 +00005538 // We should only get called for declarations with scope specifiers, like:
5539 // int foo::bar;
5540 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005541 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005542}
5543
5544/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005545/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005546void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005547 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005548 Decl *D = Dcl.getAs<Decl>();
5549 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005550
John McCall731ad842009-12-19 09:28:58 +00005551 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005552 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005553}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005554
5555/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5556/// C++ if/switch/while/for statement.
5557/// e.g: "if (int x = f()) {...}"
5558Action::DeclResult
5559Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5560 // C++ 6.4p2:
5561 // The declarator shall not specify a function or an array.
5562 // The type-specifier-seq shall not contain typedef and shall not declare a
5563 // new class or enumeration.
5564 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5565 "Parser allowed 'typedef' as storage class of condition decl.");
5566
John McCalla93c9342009-12-07 02:54:59 +00005567 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005568 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005569 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005570
5571 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5572 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5573 // would be created and CXXConditionDeclExpr wants a VarDecl.
5574 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5575 << D.getSourceRange();
5576 return DeclResult();
5577 } else if (OwnedTag && OwnedTag->isDefinition()) {
5578 // The type-specifier-seq shall not declare a new class or enumeration.
5579 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5580 }
5581
5582 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5583 if (!Dcl)
5584 return DeclResult();
5585
5586 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5587 VD->setDeclaredInCondition(true);
5588 return Dcl;
5589}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005590
Anders Carlssond6a637f2009-12-07 08:24:59 +00005591void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5592 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005593 // Ignore dependent types.
5594 if (MD->isDependentContext())
5595 return;
5596
5597 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005598
5599 // Ignore classes without a vtable.
5600 if (!RD->isDynamicClass())
5601 return;
5602
Anders Carlssond6a637f2009-12-07 08:24:59 +00005603 if (!MD->isOutOfLine()) {
5604 // The only inline functions we care about are constructors. We also defer
5605 // marking the virtual members as referenced until we've reached the end
5606 // of the translation unit. We do this because we need to know the key
5607 // function of the class in order to determine the key function.
5608 if (isa<CXXConstructorDecl>(MD))
5609 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5610 return;
5611 }
5612
Anders Carlssonf53df232009-12-07 04:35:11 +00005613 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005614
5615 if (!KeyFunction) {
5616 // This record does not have a key function, so we assume that the vtable
5617 // will be emitted when it's used by the constructor.
5618 if (!isa<CXXConstructorDecl>(MD))
5619 return;
5620 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5621 // We don't have the right key function.
5622 return;
5623 }
5624
Anders Carlssond6a637f2009-12-07 08:24:59 +00005625 // Mark the members as referenced.
5626 MarkVirtualMembersReferenced(Loc, RD);
5627 ClassesWithUnmarkedVirtualMembers.erase(RD);
5628}
5629
5630bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5631 if (ClassesWithUnmarkedVirtualMembers.empty())
5632 return false;
5633
5634 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5635 ClassesWithUnmarkedVirtualMembers.begin(),
5636 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5637 CXXRecordDecl *RD = i->first;
5638
5639 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5640 if (KeyFunction) {
5641 // We know that the class has a key function. If the key function was
5642 // declared in this translation unit, then it the class decl would not
5643 // have been in the ClassesWithUnmarkedVirtualMembers map.
5644 continue;
5645 }
5646
5647 SourceLocation Loc = i->second;
5648 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005649 }
5650
Anders Carlssond6a637f2009-12-07 08:24:59 +00005651 ClassesWithUnmarkedVirtualMembers.clear();
5652 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005653}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005654
5655void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5656 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5657 e = RD->method_end(); i != e; ++i) {
5658 CXXMethodDecl *MD = *i;
5659
5660 // C++ [basic.def.odr]p2:
5661 // [...] A virtual member function is used if it is not pure. [...]
5662 if (MD->isVirtual() && !MD->isPure())
5663 MarkDeclarationReferenced(Loc, MD);
5664 }
5665}
5666