blob: f1474cd97971c16ac1e8df2319208e04417793ba [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 Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000273 // FIXME: If the parameter doesn't have an identifier then the location
274 // points to the '=' which means that the fixit hint won't remove any
275 // extra spaces between the type and the '='.
276 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000277 if (NewParam->getIdentifier())
278 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000279
Mike Stump1eb44332009-09-09 15:08:12 +0000280 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000282 << NewParam->getDefaultArgRange()
283 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
284 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000356 }
357 }
358
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000359 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000363
Douglas Gregorcda9c672009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 else
Mike Stump1eb44332009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
434 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000448 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000449 SourceLocation BaseLoc) {
450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460 Class->getTagKind() == RecordDecl::TK_class,
461 Access, BaseType);
462
463 // Base specifiers must be record types.
464 if (!BaseType->isRecordType()) {
465 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466 return 0;
467 }
468
469 // C++ [class.union]p1:
470 // A union shall not be used as a base class.
471 if (BaseType->isUnionType()) {
472 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473 return 0;
474 }
475
476 // C++ [class.derived]p2:
477 // The class-name in a base-specifier shall not be an incompletely
478 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000479 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000480 PDiag(diag::err_incomplete_base_class)
481 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 return 0;
483
Eli Friedman1d954f62009-08-15 21:55:26 +0000484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 assert(BaseDecl && "Record type has no declaration");
487 BaseDecl = BaseDecl->getDefinition(Context);
488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000489 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000491
Sean Huntbbd37c62009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000497 return 0;
498 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499
Eli Friedmand0137332009-12-05 23:03:49 +0000500 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000501
502 // Create the base specifier.
503 // FIXME: Allocate via ASTContext?
504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505 Class->getTagKind() == RecordDecl::TK_class,
506 Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510 const CXXRecordDecl *BaseClass,
511 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000512 // A class with a non-empty base class is not empty.
513 // FIXME: Standard ref?
514 if (!BaseClass->isEmpty())
515 Class->setEmpty(false);
516
517 // C++ [class.virtual]p1:
518 // A class that [...] inherits a virtual function is called a polymorphic
519 // class.
520 if (BaseClass->isPolymorphic())
521 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000522
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is [...] a class with [...] no base classes [...].
525 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000526
527 // C++ [class]p4:
528 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 Class->setPOD(false);
530
Anders Carlsson51f94042009-12-03 17:49:57 +0000531 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000532 // C++ [class.ctor]p5:
533 // A constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000535
536 // C++ [class.copy]p6:
537 // A copy constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialCopyConstructor(false);
539
540 // C++ [class.copy]p11:
541 // A copy assignment operator is trivial if its class has no virtual
542 // base classes.
543 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000544
545 // C++0x [meta.unary.prop] is_empty:
546 // T is a class type, but not a union type, with ... no virtual base
547 // classes
548 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000549 } else {
550 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000551 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000553 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000554 Class->setHasTrivialConstructor(false);
555
556 // C++ [class.copy]p6:
557 // A copy constructor is trivial if all the direct base classes of its
558 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialCopyConstructor(false);
561
562 // C++ [class.copy]p11:
563 // A copy assignment operator is trivial if all the direct base classes
564 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000567 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000568
569 // C++ [class.ctor]p3:
570 // A destructor is trivial if all the direct base classes of its class
571 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000572 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000573 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574}
575
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000578/// example:
579/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000580/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000581Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 bool Virtual, AccessSpecifier Access,
584 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000585 if (!classdecl)
586 return true;
587
Douglas Gregor40808ce2009-03-09 23:48:35 +0000588 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000590 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
592 Virtual, Access,
593 BaseType, BaseLoc))
594 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000597}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599/// \brief Performs the actual work of attaching the given base class
600/// specifiers to a C++ class.
601bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
602 unsigned NumBases) {
603 if (NumBases == 0)
604 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605
606 // Used to keep track of which base types we have already seen, so
607 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608 // that the key is always the unqualified canonical type of the base
609 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
611
612 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000616 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000618 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 if (KnownBaseTypes[NewBaseType]) {
621 // C++ [class.mi]p3:
622 // A class shall not be specified as a direct base class of a
623 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000625 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000626 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the duplicate base class specifier; we're going to
630 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000631 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632
633 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000634 } else {
635 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 KnownBaseTypes[NewBaseType] = Bases[idx];
637 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 }
639 }
640
641 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000642 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the remaining (good) base class specifiers, since their
645 // data has been copied into the CXXRecordDecl.
646 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000647 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648
649 return Invalid;
650}
651
652/// ActOnBaseSpecifiers - Attach the given base specifiers to the
653/// class, after checking whether there are any duplicate base
654/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000655void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000656 unsigned NumBases) {
657 if (!ClassDecl || !Bases || !NumBases)
658 return;
659
660 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000661 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000664
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665/// \brief Determine whether the type \p Derived is a C++ class that is
666/// derived from the type \p Base.
667bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
668 if (!getLangOptions().CPlusPlus)
669 return false;
670
671 const RecordType *DerivedRT = Derived->getAs<RecordType>();
672 if (!DerivedRT)
673 return false;
674
675 const RecordType *BaseRT = Base->getAs<RecordType>();
676 if (!BaseRT)
677 return false;
678
679 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
680 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
681 return DerivedRD->isDerivedFrom(BaseRD);
682}
683
684/// \brief Determine whether the type \p Derived is a C++ class that is
685/// derived from the type \p Base.
686bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
687 if (!getLangOptions().CPlusPlus)
688 return false;
689
690 const RecordType *DerivedRT = Derived->getAs<RecordType>();
691 if (!DerivedRT)
692 return false;
693
694 const RecordType *BaseRT = Base->getAs<RecordType>();
695 if (!BaseRT)
696 return false;
697
698 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
699 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
700 return DerivedRD->isDerivedFrom(BaseRD, Paths);
701}
702
703/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
704/// conversion (where Derived and Base are class types) is
705/// well-formed, meaning that the conversion is unambiguous (and
706/// that all of the base classes are accessible). Returns true
707/// and emits a diagnostic if the code is ill-formed, returns false
708/// otherwise. Loc is the location where this routine should point to
709/// if there is an error, and Range is the source range to highlight
710/// if there is an error.
711bool
712Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
713 unsigned InaccessibleBaseID,
714 unsigned AmbigiousBaseConvID,
715 SourceLocation Loc, SourceRange Range,
716 DeclarationName Name) {
717 // First, determine whether the path from Derived to Base is
718 // ambiguous. This is slightly more expensive than checking whether
719 // the Derived to Base conversion exists, because here we need to
720 // explore multiple paths to determine if there is an ambiguity.
721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
722 /*DetectVirtual=*/false);
723 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
724 assert(DerivationOkay &&
725 "Can only be used with a derived-to-base conversion");
726 (void)DerivationOkay;
727
728 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000729 if (InaccessibleBaseID == 0)
730 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000731 // Check that the base class can be accessed.
732 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
733 Name);
734 }
735
736 // We know that the derived-to-base conversion is ambiguous, and
737 // we're going to produce a diagnostic. Perform the derived-to-base
738 // search just one more time to compute all of the possible paths so
739 // that we can print them out. This is more expensive than any of
740 // the previous derived-to-base checks we've done, but at this point
741 // performance isn't as much of an issue.
742 Paths.clear();
743 Paths.setRecordingPaths(true);
744 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
745 assert(StillOkay && "Can only be used with a derived-to-base conversion");
746 (void)StillOkay;
747
748 // Build up a textual representation of the ambiguous paths, e.g.,
749 // D -> B -> A, that will be used to illustrate the ambiguous
750 // conversions in the diagnostic. We only print one of the paths
751 // to each base class subobject.
752 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
753
754 Diag(Loc, AmbigiousBaseConvID)
755 << Derived << Base << PathDisplayStr << Range << Name;
756 return true;
757}
758
759bool
760Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000761 SourceLocation Loc, SourceRange Range,
762 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000763 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000764 IgnoreAccess ? 0 :
765 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000766 diag::err_ambiguous_derived_to_base_conv,
767 Loc, Range, DeclarationName());
768}
769
770
771/// @brief Builds a string representing ambiguous paths from a
772/// specific derived class to different subobjects of the same base
773/// class.
774///
775/// This function builds a string that can be used in error messages
776/// to show the different paths that one can take through the
777/// inheritance hierarchy to go from the derived class to different
778/// subobjects of a base class. The result looks something like this:
779/// @code
780/// struct D -> struct B -> struct A
781/// struct D -> struct C -> struct A
782/// @endcode
783std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
784 std::string PathDisplayStr;
785 std::set<unsigned> DisplayedPaths;
786 for (CXXBasePaths::paths_iterator Path = Paths.begin();
787 Path != Paths.end(); ++Path) {
788 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
789 // We haven't displayed a path to this particular base
790 // class subobject yet.
791 PathDisplayStr += "\n ";
792 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
793 for (CXXBasePath::const_iterator Element = Path->begin();
794 Element != Path->end(); ++Element)
795 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
796 }
797 }
798
799 return PathDisplayStr;
800}
801
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000802//===----------------------------------------------------------------------===//
803// C++ class member Handling
804//===----------------------------------------------------------------------===//
805
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000806/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
807/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
808/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000809/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000810Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000812 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000813 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
814 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000815 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000816 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000817 Expr *BitWidth = static_cast<Expr*>(BW);
818 Expr *Init = static_cast<Expr*>(InitExpr);
819 SourceLocation Loc = D.getIdentifierLoc();
820
Sebastian Redl669d5d72008-11-14 23:42:31 +0000821 bool isFunc = D.isFunctionDeclarator();
822
John McCall67d1a672009-08-06 02:15:43 +0000823 assert(!DS.isFriendSpecified());
824
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000825 // C++ 9.2p6: A member shall not be declared to have automatic storage
826 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000827 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
828 // data members and cannot be applied to names declared const or static,
829 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000830 switch (DS.getStorageClassSpec()) {
831 case DeclSpec::SCS_unspecified:
832 case DeclSpec::SCS_typedef:
833 case DeclSpec::SCS_static:
834 // FALL THROUGH.
835 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000836 case DeclSpec::SCS_mutable:
837 if (isFunc) {
838 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000839 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000840 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000841 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Sebastian Redla11f42f2008-11-17 23:24:37 +0000843 // FIXME: It would be nicer if the keyword was ignored only for this
844 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000845 D.getMutableDeclSpec().ClearStorageClassSpecs();
846 } else {
847 QualType T = GetTypeForDeclarator(D, S);
848 diag::kind err = static_cast<diag::kind>(0);
849 if (T->isReferenceType())
850 err = diag::err_mutable_reference;
851 else if (T.isConstQualified())
852 err = diag::err_mutable_const;
853 if (err != 0) {
854 if (DS.getStorageClassSpecLoc().isValid())
855 Diag(DS.getStorageClassSpecLoc(), err);
856 else
857 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000858 // FIXME: It would be nicer if the keyword was ignored only for this
859 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000860 D.getMutableDeclSpec().ClearStorageClassSpecs();
861 }
862 }
863 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864 default:
865 if (DS.getStorageClassSpecLoc().isValid())
866 Diag(DS.getStorageClassSpecLoc(),
867 diag::err_storageclass_invalid_for_member);
868 else
869 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
870 D.getMutableDeclSpec().ClearStorageClassSpecs();
871 }
872
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000873 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000874 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000875 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000876 // Check also for this case:
877 //
878 // typedef int f();
879 // f a;
880 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000881 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000882 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000883 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884
Sebastian Redl669d5d72008-11-14 23:42:31 +0000885 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
886 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000887 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888
889 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000890 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000891 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000892 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
893 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000894 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000895 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000896 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000897 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000898 if (!Member) {
899 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000900 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000901 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000902
903 // Non-instance-fields can't have a bitfield.
904 if (BitWidth) {
905 if (Member->isInvalidDecl()) {
906 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000907 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000908 // C++ 9.6p3: A bit-field shall not be a static member.
909 // "static member 'A' cannot be a bit-field"
910 Diag(Loc, diag::err_static_not_bitfield)
911 << Name << BitWidth->getSourceRange();
912 } else if (isa<TypedefDecl>(Member)) {
913 // "typedef member 'x' cannot be a bit-field"
914 Diag(Loc, diag::err_typedef_not_bitfield)
915 << Name << BitWidth->getSourceRange();
916 } else {
917 // A function typedef ("typedef int f(); f a;").
918 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
919 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000920 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000921 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner8b963ef2009-03-05 23:01:03 +0000924 DeleteExpr(BitWidth);
925 BitWidth = 0;
926 Member->setInvalidDecl();
927 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000928
929 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregor37b372b2009-08-20 22:52:58 +0000931 // If we have declared a member function template, set the access of the
932 // templated declaration as well.
933 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
934 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000935 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000936
Douglas Gregor10bd3682008-11-17 22:58:34 +0000937 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000938
Douglas Gregor021c3b32009-03-11 23:00:04 +0000939 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000940 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000941 if (Deleted) // FIXME: Source location is not very good.
942 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000943
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000944 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000945 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000946 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000948 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949}
950
Douglas Gregor7ad83902008-11-05 04:29:56 +0000951/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000952Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000953Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000954 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000955 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000956 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000957 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000958 SourceLocation IdLoc,
959 SourceLocation LParenLoc,
960 ExprTy **Args, unsigned NumArgs,
961 SourceLocation *CommaLocs,
962 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000963 if (!ConstructorD)
964 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000966 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
968 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000969 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000970 if (!Constructor) {
971 // The user wrote a constructor initializer on a function that is
972 // not a C++ constructor. Ignore the error for now, because we may
973 // have more member initializers coming; we'll diagnose it just
974 // once in ActOnMemInitializers.
975 return true;
976 }
977
978 CXXRecordDecl *ClassDecl = Constructor->getParent();
979
980 // C++ [class.base.init]p2:
981 // Names in a mem-initializer-id are looked up in the scope of the
982 // constructor’s class and, if not found in that scope, are looked
983 // up in the scope containing the constructor’s
984 // definition. [Note: if the constructor’s class contains a member
985 // with the same name as a direct or virtual base class of the
986 // class, a mem-initializer-id naming the member or base class and
987 // composed of a single identifier refers to the class member. A
988 // mem-initializer-id for the hidden base class may be specified
989 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000990 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000991 // Look for a member, first.
992 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000993 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000994 = ClassDecl->lookup(MemberOrBase);
995 if (Result.first != Result.second)
996 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000997
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000998 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000999
Eli Friedman59c04372009-07-29 19:44:27 +00001000 if (Member)
1001 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001002 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001003 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001004 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001005 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001006 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001007
1008 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001009 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001010 } else {
1011 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1012 LookupParsedName(R, S, &SS);
1013
1014 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1015 if (!TyD) {
1016 if (R.isAmbiguous()) return true;
1017
1018 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1019 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1020 return true;
1021 }
1022
1023 BaseType = Context.getTypeDeclType(TyD);
1024 if (SS.isSet()) {
1025 NestedNameSpecifier *Qualifier =
1026 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1027
1028 // FIXME: preserve source range information
1029 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1030 }
1031 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
John McCalla93c9342009-12-07 02:54:59 +00001033 if (!TInfo)
1034 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001035
John McCalla93c9342009-12-07 02:54:59 +00001036 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001037 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001038}
1039
John McCallb4190042009-11-04 23:02:40 +00001040/// Checks an initializer expression for use of uninitialized fields, such as
1041/// containing the field that is being initialized. Returns true if there is an
1042/// uninitialized field was used an updates the SourceLocation parameter; false
1043/// otherwise.
1044static bool InitExprContainsUninitializedFields(const Stmt* S,
1045 const FieldDecl* LhsField,
1046 SourceLocation* L) {
1047 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1048 if (ME) {
1049 const NamedDecl* RhsField = ME->getMemberDecl();
1050 if (RhsField == LhsField) {
1051 // Initializing a field with itself. Throw a warning.
1052 // But wait; there are exceptions!
1053 // Exception #1: The field may not belong to this record.
1054 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1055 const Expr* base = ME->getBase();
1056 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1057 // Even though the field matches, it does not belong to this record.
1058 return false;
1059 }
1060 // None of the exceptions triggered; return true to indicate an
1061 // uninitialized field was used.
1062 *L = ME->getMemberLoc();
1063 return true;
1064 }
1065 }
1066 bool found = false;
1067 for (Stmt::const_child_iterator it = S->child_begin();
1068 it != S->child_end() && found == false;
1069 ++it) {
1070 if (isa<CallExpr>(S)) {
1071 // Do not descend into function calls or constructors, as the use
1072 // of an uninitialized field may be valid. One would have to inspect
1073 // the contents of the function/ctor to determine if it is safe or not.
1074 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1075 // may be safe, depending on what the function/ctor does.
1076 continue;
1077 }
1078 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1079 }
1080 return found;
1081}
1082
Eli Friedman59c04372009-07-29 19:44:27 +00001083Sema::MemInitResult
1084Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1085 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001086 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001087 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001088 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1089 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1090 ExprTemporaries.clear();
1091
John McCallb4190042009-11-04 23:02:40 +00001092 // Diagnose value-uses of fields to initialize themselves, e.g.
1093 // foo(foo)
1094 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001095 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001096 for (unsigned i = 0; i < NumArgs; ++i) {
1097 SourceLocation L;
1098 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1099 // FIXME: Return true in the case when other fields are used before being
1100 // uninitialized. For example, let this field be the i'th field. When
1101 // initializing the i'th field, throw a warning if any of the >= i'th
1102 // fields are used, as they are not yet initialized.
1103 // Right now we are only handling the case where the i'th field uses
1104 // itself in its initializer.
1105 Diag(L, diag::warn_field_is_uninit);
1106 }
1107 }
1108
Eli Friedman59c04372009-07-29 19:44:27 +00001109 bool HasDependentArg = false;
1110 for (unsigned i = 0; i < NumArgs; i++)
1111 HasDependentArg |= Args[i]->isTypeDependent();
1112
1113 CXXConstructorDecl *C = 0;
1114 QualType FieldType = Member->getType();
1115 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1116 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001117 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Eli Friedman59c04372009-07-29 19:44:27 +00001118 if (FieldType->isDependentType()) {
1119 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001120 } else if (FieldType->isRecordType()) {
1121 // Member is a record (struct/union/class), so pass the initializer
1122 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001123 if (!HasDependentArg) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00001124 C = PerformInitializationByConstructor(FieldType,
1125 MultiExprArg(*this,
1126 (void**)Args,
1127 NumArgs),
1128 IdLoc,
1129 SourceRange(IdLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001130 Member->getDeclName(),
1131 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001132 ConstructorArgs);
1133
1134 if (C) {
1135 // Take over the constructor arguments as our own.
1136 NumArgs = ConstructorArgs.size();
1137 Args = (Expr **)ConstructorArgs.take();
1138 }
1139 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001140 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001141 // The member type is not a record type (or an array of record
1142 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001143 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001144 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1145 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001146 Expr *NewExp;
1147 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001148 if (FieldType->isReferenceType()) {
1149 Diag(IdLoc, diag::err_null_intialized_reference_member)
1150 << Member->getDeclName();
1151 return Diag(Member->getLocation(), diag::note_declared_at);
1152 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001153 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1154 NumArgs = 1;
1155 }
1156 else
1157 NewExp = (Expr*)Args[0];
Chris Lattner8c3f8902009-12-31 03:10:55 +00001158 if (!Member->isInvalidDecl() &&
1159 PerformCopyInitialization(NewExp, FieldType, AA_Passing))
Eli Friedman59c04372009-07-29 19:44:27 +00001160 return true;
1161 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001162 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001163
1164 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1165 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1166 ExprTemporaries.clear();
1167
Eli Friedman59c04372009-07-29 19:44:27 +00001168 // FIXME: Perform direct initialization of the member.
Douglas Gregor802ab452009-12-02 22:36:29 +00001169 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1170 C, LParenLoc, (Expr **)Args,
1171 NumArgs, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001172}
1173
1174Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001175Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001176 Expr **Args, unsigned NumArgs,
1177 SourceLocation LParenLoc, SourceLocation RParenLoc,
1178 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001179 bool HasDependentArg = false;
1180 for (unsigned i = 0; i < NumArgs; i++)
1181 HasDependentArg |= Args[i]->isTypeDependent();
1182
John McCalla93c9342009-12-07 02:54:59 +00001183 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman59c04372009-07-29 19:44:27 +00001184 if (!BaseType->isDependentType()) {
1185 if (!BaseType->isRecordType())
Douglas Gregor802ab452009-12-02 22:36:29 +00001186 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCalla93c9342009-12-07 02:54:59 +00001187 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001188
1189 // C++ [class.base.init]p2:
1190 // [...] Unless the mem-initializer-id names a nonstatic data
1191 // member of the constructor’s class or a direct or virtual base
1192 // of that class, the mem-initializer is ill-formed. A
1193 // mem-initializer-list can initialize a base class using any
1194 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Eli Friedman59c04372009-07-29 19:44:27 +00001196 // First, check for a direct base class.
1197 const CXXBaseSpecifier *DirectBaseSpec = 0;
1198 for (CXXRecordDecl::base_class_const_iterator Base =
1199 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001200 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001201 // We found a direct base of this type. That's what we're
1202 // initializing.
1203 DirectBaseSpec = &*Base;
1204 break;
1205 }
1206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Eli Friedman59c04372009-07-29 19:44:27 +00001208 // Check for a virtual base class.
1209 // FIXME: We might be able to short-circuit this if we know in advance that
1210 // there are no virtual bases.
1211 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1212 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1213 // We haven't found a base yet; search the class hierarchy for a
1214 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001215 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1216 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001217 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001218 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001219 Path != Paths.end(); ++Path) {
1220 if (Path->back().Base->isVirtual()) {
1221 VirtualBaseSpec = Path->back().Base;
1222 break;
1223 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001224 }
1225 }
1226 }
Eli Friedman59c04372009-07-29 19:44:27 +00001227
1228 // C++ [base.class.init]p2:
1229 // If a mem-initializer-id is ambiguous because it designates both
1230 // a direct non-virtual base class and an inherited virtual base
1231 // class, the mem-initializer is ill-formed.
1232 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001233 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCalla93c9342009-12-07 02:54:59 +00001234 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001235 // C++ [base.class.init]p2:
1236 // Unless the mem-initializer-id names a nonstatic data membeer of the
1237 // constructor's class ot a direst or virtual base of that class, the
1238 // mem-initializer is ill-formed.
1239 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001240 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1241 << BaseType << ClassDecl->getNameAsCString()
John McCalla93c9342009-12-07 02:54:59 +00001242 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregor7ad83902008-11-05 04:29:56 +00001243 }
1244
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001245 CXXConstructorDecl *C = 0;
Eli Friedmane6d11b72009-12-25 23:59:21 +00001246 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Eli Friedman59c04372009-07-29 19:44:27 +00001247 if (!BaseType->isDependentType() && !HasDependentArg) {
1248 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001249 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001250
1251 C = PerformInitializationByConstructor(BaseType,
1252 MultiExprArg(*this,
1253 (void**)Args, NumArgs),
Douglas Gregor802ab452009-12-02 22:36:29 +00001254 BaseLoc,
1255 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001256 Name,
1257 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001258 ConstructorArgs);
1259 if (C) {
1260 // Take over the constructor arguments as our own.
1261 NumArgs = ConstructorArgs.size();
1262 Args = (Expr **)ConstructorArgs.take();
1263 }
Eli Friedman59c04372009-07-29 19:44:27 +00001264 }
1265
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001266 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1267 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1268 ExprTemporaries.clear();
1269
John McCalla93c9342009-12-07 02:54:59 +00001270 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregor802ab452009-12-02 22:36:29 +00001271 LParenLoc, (Expr **)Args,
1272 NumArgs, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001273}
1274
Eli Friedman80c30da2009-11-09 19:20:36 +00001275bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001276Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001277 CXXBaseOrMemberInitializer **Initializers,
1278 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001279 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001280 // We need to build the initializer AST according to order of construction
1281 // and not what user specified in the Initializers list.
1282 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1283 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1284 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1285 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001286 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001288 for (unsigned i = 0; i < NumInitializers; i++) {
1289 CXXBaseOrMemberInitializer *Member = Initializers[i];
1290 if (Member->isBaseInitializer()) {
1291 if (Member->getBaseClass()->isDependentType())
1292 HasDependentBaseInit = true;
1293 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1294 } else {
1295 AllBaseFields[Member->getMember()] = Member;
1296 }
1297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001299 if (HasDependentBaseInit) {
1300 // FIXME. This does not preserve the ordering of the initializers.
1301 // Try (with -Wreorder)
1302 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001303 // template<class X> struct B : A<X> {
1304 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001305 // int x1;
1306 // };
1307 // B<int> x;
1308 // On seeing one dependent type, we should essentially exit this routine
1309 // while preserving user-declared initializer list. When this routine is
1310 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001311 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001313 // If we have a dependent base initialization, we can't determine the
1314 // association between initializers and bases; just dump the known
1315 // initializers into the list, and don't try to deal with other bases.
1316 for (unsigned i = 0; i < NumInitializers; i++) {
1317 CXXBaseOrMemberInitializer *Member = Initializers[i];
1318 if (Member->isBaseInitializer())
1319 AllToInit.push_back(Member);
1320 }
1321 } else {
1322 // Push virtual bases before others.
1323 for (CXXRecordDecl::base_class_iterator VBase =
1324 ClassDecl->vbases_begin(),
1325 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1326 if (VBase->getType()->isDependentType())
1327 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001328 if (CXXBaseOrMemberInitializer *Value
1329 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001330 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001331 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001332 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001333 CXXRecordDecl *VBaseDecl =
Douglas Gregor802ab452009-12-02 22:36:29 +00001334 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001335 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001336 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001337 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001338 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1339 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1340 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001341 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001342 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001343 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001344 continue;
1345 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001346
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001347 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1348 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1349 Constructor->getLocation(), CtorArgs))
1350 continue;
1351
1352 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1353
Anders Carlsson8db68da2009-11-13 20:11:49 +00001354 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001355 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1356 // necessary.
1357 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001358 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001359 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001360 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001361 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001362 SourceLocation()),
1363 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001364 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001365 CtorArgs.takeAs<Expr>(),
1366 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001367 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001368 AllToInit.push_back(Member);
1369 }
1370 }
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001372 for (CXXRecordDecl::base_class_iterator Base =
1373 ClassDecl->bases_begin(),
1374 E = ClassDecl->bases_end(); Base != E; ++Base) {
1375 // Virtuals are in the virtual base list and already constructed.
1376 if (Base->isVirtual())
1377 continue;
1378 // Skip dependent types.
1379 if (Base->getType()->isDependentType())
1380 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001381 if (CXXBaseOrMemberInitializer *Value
1382 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001383 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001384 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001385 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001386 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001387 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001388 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001389 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001390 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001391 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1392 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1393 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001394 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001395 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001396 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001397 continue;
1398 }
1399
1400 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1401 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1402 Constructor->getLocation(), CtorArgs))
1403 continue;
1404
1405 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001406
Anders Carlsson8db68da2009-11-13 20:11:49 +00001407 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001408 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1409 // necessary.
1410 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001411 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001412 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001413 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001414 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001415 SourceLocation()),
1416 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001417 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001418 CtorArgs.takeAs<Expr>(),
1419 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001420 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001421 AllToInit.push_back(Member);
1422 }
1423 }
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001426 // non-static data members.
1427 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1428 E = ClassDecl->field_end(); Field != E; ++Field) {
1429 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001430 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001431 Field->getType()->getAs<RecordType>()) {
1432 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001433 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001434 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001435 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1436 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1437 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1438 // set to the anonymous union data member used in the initializer
1439 // list.
1440 Value->setMember(*Field);
1441 Value->setAnonUnionMember(*FA);
1442 AllToInit.push_back(Value);
1443 break;
1444 }
1445 }
1446 }
1447 continue;
1448 }
1449 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1450 AllToInit.push_back(Value);
1451 continue;
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Eli Friedman49c16da2009-11-09 01:05:47 +00001454 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001455 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001456
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001457 QualType FT = Context.getBaseElementType((*Field)->getType());
1458 if (const RecordType* RT = FT->getAs<RecordType>()) {
1459 CXXConstructorDecl *Ctor =
1460 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001461 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001462 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1463 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1464 << 1 << (*Field)->getDeclName();
1465 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001466 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001467 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001468 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001469 continue;
1470 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001471
1472 if (FT.isConstQualified() && Ctor->isTrivial()) {
1473 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1474 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1475 << 1 << (*Field)->getDeclName();
1476 Diag((*Field)->getLocation(), diag::note_declared_at);
1477 HadError = true;
1478 }
1479
1480 // Don't create initializers for trivial constructors, since they don't
1481 // actually need to be run.
1482 if (Ctor->isTrivial())
1483 continue;
1484
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001485 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1486 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1487 Constructor->getLocation(), CtorArgs))
1488 continue;
1489
Anders Carlsson8db68da2009-11-13 20:11:49 +00001490 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1491 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1492 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001493 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001494 new (Context) CXXBaseOrMemberInitializer(Context,
1495 *Field, SourceLocation(),
1496 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001497 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001498 CtorArgs.takeAs<Expr>(),
1499 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001500 SourceLocation());
1501
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001502 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001503 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001504 }
1505 else if (FT->isReferenceType()) {
1506 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001507 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1508 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001509 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001510 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001511 }
1512 else if (FT.isConstQualified()) {
1513 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001514 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1515 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001516 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001517 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001518 }
1519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001521 NumInitializers = AllToInit.size();
1522 if (NumInitializers > 0) {
1523 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1524 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1525 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001527 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1528 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1529 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1530 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001531
1532 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001533}
1534
Eli Friedman6347f422009-07-21 19:28:10 +00001535static void *GetKeyForTopLevelField(FieldDecl *Field) {
1536 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001537 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001538 if (RT->getDecl()->isAnonymousStructOrUnion())
1539 return static_cast<void *>(RT->getDecl());
1540 }
1541 return static_cast<void *>(Field);
1542}
1543
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001544static void *GetKeyForBase(QualType BaseType) {
1545 if (const RecordType *RT = BaseType->getAs<RecordType>())
1546 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001548 assert(0 && "Unexpected base type!");
1549 return 0;
1550}
1551
Mike Stump1eb44332009-09-09 15:08:12 +00001552static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001553 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001554 // For fields injected into the class via declaration of an anonymous union,
1555 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001556 if (Member->isMemberInitializer()) {
1557 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Eli Friedman49c16da2009-11-09 01:05:47 +00001559 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001560 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001561 // in AnonUnionMember field.
1562 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1563 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001564 if (Field->getDeclContext()->isRecord()) {
1565 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1566 if (RD->isAnonymousStructOrUnion())
1567 return static_cast<void *>(RD);
1568 }
1569 return static_cast<void *>(Field);
1570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001572 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001573}
1574
John McCall6aee6212009-11-04 23:13:52 +00001575/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001576void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001577 SourceLocation ColonLoc,
1578 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001579 if (!ConstructorDecl)
1580 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001581
1582 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001583
1584 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001585 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Anders Carlssona7b35212009-03-25 02:58:17 +00001587 if (!Constructor) {
1588 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1589 return;
1590 }
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001592 if (!Constructor->isDependentContext()) {
1593 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1594 bool err = false;
1595 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001596 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001597 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1598 void *KeyToMember = GetKeyForMember(Member);
1599 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1600 if (!PrevMember) {
1601 PrevMember = Member;
1602 continue;
1603 }
1604 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001605 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001606 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001607 << Field->getNameAsString()
1608 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001609 else {
1610 Type *BaseClass = Member->getBaseClass();
1611 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001612 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001613 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001614 << QualType(BaseClass, 0)
1615 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001616 }
1617 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1618 << 0;
1619 err = true;
1620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001622 if (err)
1623 return;
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Eli Friedman49c16da2009-11-09 01:05:47 +00001626 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001627 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001628 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001630 if (Constructor->isDependentContext())
1631 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001632
1633 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001634 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001635 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001636 Diagnostic::Ignored)
1637 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001639 // Also issue warning if order of ctor-initializer list does not match order
1640 // of 1) base class declarations and 2) order of non-static data members.
1641 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001643 CXXRecordDecl *ClassDecl
1644 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1645 // Push virtual bases before others.
1646 for (CXXRecordDecl::base_class_iterator VBase =
1647 ClassDecl->vbases_begin(),
1648 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001649 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001651 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1652 E = ClassDecl->bases_end(); Base != E; ++Base) {
1653 // Virtuals are alread in the virtual base list and are constructed
1654 // first.
1655 if (Base->isVirtual())
1656 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001657 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001658 }
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001660 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1661 E = ClassDecl->field_end(); Field != E; ++Field)
1662 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001664 int Last = AllBaseOrMembers.size();
1665 int curIndex = 0;
1666 CXXBaseOrMemberInitializer *PrevMember = 0;
1667 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001668 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001669 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1670 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001671
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001672 for (; curIndex < Last; curIndex++)
1673 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1674 break;
1675 if (curIndex == Last) {
1676 assert(PrevMember && "Member not in member list?!");
1677 // Initializer as specified in ctor-initializer list is out of order.
1678 // Issue a warning diagnostic.
1679 if (PrevMember->isBaseInitializer()) {
1680 // Diagnostics is for an initialized base class.
1681 Type *BaseClass = PrevMember->getBaseClass();
1682 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001683 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001684 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001685 } else {
1686 FieldDecl *Field = PrevMember->getMember();
1687 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001688 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001689 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001690 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001691 // Also the note!
1692 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001693 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001694 diag::note_fieldorbase_initialized_here) << 0
1695 << Field->getNameAsString();
1696 else {
1697 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001698 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001699 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001700 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001701 }
1702 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001703 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001704 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001705 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001706 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001707 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001708}
1709
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001710void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001711Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1712 // Ignore dependent destructors.
1713 if (Destructor->isDependentContext())
1714 return;
1715
1716 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Anders Carlsson9f853df2009-11-17 04:44:12 +00001718 // Non-static data members.
1719 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1720 E = ClassDecl->field_end(); I != E; ++I) {
1721 FieldDecl *Field = *I;
1722
1723 QualType FieldType = Context.getBaseElementType(Field->getType());
1724
1725 const RecordType* RT = FieldType->getAs<RecordType>();
1726 if (!RT)
1727 continue;
1728
1729 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1730 if (FieldClassDecl->hasTrivialDestructor())
1731 continue;
1732
1733 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1734 MarkDeclarationReferenced(Destructor->getLocation(),
1735 const_cast<CXXDestructorDecl*>(Dtor));
1736 }
1737
1738 // Bases.
1739 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1740 E = ClassDecl->bases_end(); Base != E; ++Base) {
1741 // Ignore virtual bases.
1742 if (Base->isVirtual())
1743 continue;
1744
1745 // Ignore trivial destructors.
1746 CXXRecordDecl *BaseClassDecl
1747 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1748 if (BaseClassDecl->hasTrivialDestructor())
1749 continue;
1750
1751 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1752 MarkDeclarationReferenced(Destructor->getLocation(),
1753 const_cast<CXXDestructorDecl*>(Dtor));
1754 }
1755
1756 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001757 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1758 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001759 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001760 CXXRecordDecl *BaseClassDecl
1761 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1762 if (BaseClassDecl->hasTrivialDestructor())
1763 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001764
1765 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1766 MarkDeclarationReferenced(Destructor->getLocation(),
1767 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001768 }
1769}
1770
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001771void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001772 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001773 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001775 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001776
1777 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001778 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001779 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001780}
1781
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001782namespace {
1783 /// PureVirtualMethodCollector - traverses a class and its superclasses
1784 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001785 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001786 ASTContext &Context;
1787
Sebastian Redldfe292d2009-03-22 21:28:55 +00001788 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001789 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001790
1791 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001792 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001794 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001796 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001797 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001798 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001800 MethodList List;
1801 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001803 // Copy the temporary list to methods, and make sure to ignore any
1804 // null entries.
1805 for (size_t i = 0, e = List.size(); i != e; ++i) {
1806 if (List[i])
1807 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001808 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001809 }
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001811 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001813 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1814 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001815 };
Mike Stump1eb44332009-09-09 15:08:12 +00001816
1817 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001818 MethodList& Methods) {
1819 // First, collect the pure virtual methods for the base classes.
1820 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1821 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001822 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001823 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001824 if (BaseDecl && BaseDecl->isAbstract())
1825 Collect(BaseDecl, Methods);
1826 }
1827 }
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001829 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001830 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001832 MethodSetTy OverriddenMethods;
1833 size_t MethodsSize = Methods.size();
1834
Mike Stump1eb44332009-09-09 15:08:12 +00001835 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001836 i != e; ++i) {
1837 // Traverse the record, looking for methods.
1838 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001839 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001840 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001841 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Anders Carlsson27823022009-10-18 19:34:08 +00001843 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001844 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1845 E = MD->end_overridden_methods(); I != E; ++I) {
1846 // Keep track of the overridden methods.
1847 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001848 }
1849 }
1850 }
Mike Stump1eb44332009-09-09 15:08:12 +00001851
1852 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001853 // overridden.
1854 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1855 if (OverriddenMethods.count(Methods[i]))
1856 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001859 }
1860}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001861
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001862
Mike Stump1eb44332009-09-09 15:08:12 +00001863bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001864 unsigned DiagID, AbstractDiagSelID SelID,
1865 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001866 if (SelID == -1)
1867 return RequireNonAbstractType(Loc, T,
1868 PDiag(DiagID), CurrentRD);
1869 else
1870 return RequireNonAbstractType(Loc, T,
1871 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001872}
1873
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001874bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1875 const PartialDiagnostic &PD,
1876 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001877 if (!getLangOptions().CPlusPlus)
1878 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Anders Carlsson11f21a02009-03-23 19:10:31 +00001880 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001881 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001882 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Ted Kremenek6217b802009-07-29 21:53:49 +00001884 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001885 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001886 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001887 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001889 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001890 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001891 }
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Ted Kremenek6217b802009-07-29 21:53:49 +00001893 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001894 if (!RT)
1895 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001897 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1898 if (!RD)
1899 return false;
1900
Anders Carlssone65a3c82009-03-24 17:23:42 +00001901 if (CurrentRD && CurrentRD != RD)
1902 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001904 if (!RD->isAbstract())
1905 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001907 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001909 // Check if we've already emitted the list of pure virtual functions for this
1910 // class.
1911 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1912 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001914 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001915
1916 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001917 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1918 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
1920 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001921 MD->getDeclName();
1922 }
1923
1924 if (!PureVirtualClassDiagSet)
1925 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1926 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001928 return true;
1929}
1930
Anders Carlsson8211eff2009-03-24 01:19:16 +00001931namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001932 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001933 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1934 Sema &SemaRef;
1935 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Anders Carlssone65a3c82009-03-24 17:23:42 +00001937 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001938 bool Invalid = false;
1939
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001940 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1941 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001942 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001943
Anders Carlsson8211eff2009-03-24 01:19:16 +00001944 return Invalid;
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Anders Carlssone65a3c82009-03-24 17:23:42 +00001947 public:
1948 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1949 : SemaRef(SemaRef), AbstractClass(ac) {
1950 Visit(SemaRef.Context.getTranslationUnitDecl());
1951 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001952
Anders Carlssone65a3c82009-03-24 17:23:42 +00001953 bool VisitFunctionDecl(const FunctionDecl *FD) {
1954 if (FD->isThisDeclarationADefinition()) {
1955 // No need to do the check if we're in a definition, because it requires
1956 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001957 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001958 return VisitDeclContext(FD);
1959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Anders Carlssone65a3c82009-03-24 17:23:42 +00001961 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001962 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001963 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001964 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1965 diag::err_abstract_type_in_decl,
1966 Sema::AbstractReturnType,
1967 AbstractClass);
1968
Mike Stump1eb44332009-09-09 15:08:12 +00001969 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001970 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001971 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001972 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001973 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001974 VD->getOriginalType(),
1975 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001976 Sema::AbstractParamType,
1977 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001978 }
1979
1980 return Invalid;
1981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Anders Carlssone65a3c82009-03-24 17:23:42 +00001983 bool VisitDecl(const Decl* D) {
1984 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1985 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Anders Carlssone65a3c82009-03-24 17:23:42 +00001987 return false;
1988 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001989 };
1990}
1991
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001992/// \brief Perform semantic checks on a class definition that has been
1993/// completing, introducing implicitly-declared members, checking for
1994/// abstract types, etc.
1995void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1996 if (!Record || Record->isInvalidDecl())
1997 return;
1998
Eli Friedmanff2d8782009-12-16 20:00:27 +00001999 if (!Record->isDependentType())
2000 AddImplicitlyDeclaredMembersToClass(Record);
2001
2002 if (Record->isInvalidDecl())
2003 return;
2004
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002005 if (!Record->isAbstract()) {
2006 // Collect all the pure virtual methods and see if this is an abstract
2007 // class after all.
2008 PureVirtualMethodCollector Collector(Context, Record);
2009 if (!Collector.empty())
2010 Record->setAbstract(true);
2011 }
2012
2013 if (Record->isAbstract())
2014 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002015}
2016
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002018 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002019 SourceLocation LBrac,
2020 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002021 if (!TagDecl)
2022 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Douglas Gregor42af25f2009-05-11 19:58:34 +00002024 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002025
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002026 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002027 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002028 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002029
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002030 CheckCompletedCXXClass(
2031 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002032}
2033
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002034/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2035/// special functions, such as the default constructor, copy
2036/// constructor, or destructor, to the given C++ class (C++
2037/// [special]p1). This routine can only be executed just before the
2038/// definition of the class is complete.
2039void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002040 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002041 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002042
Sebastian Redl465226e2009-05-27 22:11:52 +00002043 // FIXME: Implicit declarations have exception specifications, which are
2044 // the union of the specifications of the implicitly called functions.
2045
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002046 if (!ClassDecl->hasUserDeclaredConstructor()) {
2047 // C++ [class.ctor]p5:
2048 // A default constructor for a class X is a constructor of class X
2049 // that can be called without an argument. If there is no
2050 // user-declared constructor for class X, a default constructor is
2051 // implicitly declared. An implicitly-declared default constructor
2052 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002053 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002054 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002055 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002056 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002057 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002058 Context.getFunctionType(Context.VoidTy,
2059 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002060 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002061 /*isExplicit=*/false,
2062 /*isInline=*/true,
2063 /*isImplicitlyDeclared=*/true);
2064 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002065 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002066 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002067 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002068 }
2069
2070 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2071 // C++ [class.copy]p4:
2072 // If the class definition does not explicitly declare a copy
2073 // constructor, one is declared implicitly.
2074
2075 // C++ [class.copy]p5:
2076 // The implicitly-declared copy constructor for a class X will
2077 // have the form
2078 //
2079 // X::X(const X&)
2080 //
2081 // if
2082 bool HasConstCopyConstructor = true;
2083
2084 // -- each direct or virtual base class B of X has a copy
2085 // constructor whose first parameter is of type const B& or
2086 // const volatile B&, and
2087 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2088 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2089 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002090 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002091 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002092 = BaseClassDecl->hasConstCopyConstructor(Context);
2093 }
2094
2095 // -- for all the nonstatic data members of X that are of a
2096 // class type M (or array thereof), each such class type
2097 // has a copy constructor whose first parameter is of type
2098 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002099 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2100 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002101 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002102 QualType FieldType = (*Field)->getType();
2103 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2104 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002105 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002106 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002107 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002108 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002109 = FieldClassDecl->hasConstCopyConstructor(Context);
2110 }
2111 }
2112
Sebastian Redl64b45f72009-01-05 20:52:13 +00002113 // Otherwise, the implicitly declared copy constructor will have
2114 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002115 //
2116 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002117 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002118 if (HasConstCopyConstructor)
2119 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002120 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002121
Sebastian Redl64b45f72009-01-05 20:52:13 +00002122 // An implicitly-declared copy constructor is an inline public
2123 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002124 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002125 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002126 CXXConstructorDecl *CopyConstructor
2127 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002128 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002129 Context.getFunctionType(Context.VoidTy,
2130 &ArgType, 1,
2131 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002132 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002133 /*isExplicit=*/false,
2134 /*isInline=*/true,
2135 /*isImplicitlyDeclared=*/true);
2136 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002137 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002138 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002139
2140 // Add the parameter to the constructor.
2141 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2142 ClassDecl->getLocation(),
2143 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002144 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002145 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002146 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002147 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002148 }
2149
Sebastian Redl64b45f72009-01-05 20:52:13 +00002150 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2151 // Note: The following rules are largely analoguous to the copy
2152 // constructor rules. Note that virtual bases are not taken into account
2153 // for determining the argument type of the operator. Note also that
2154 // operators taking an object instead of a reference are allowed.
2155 //
2156 // C++ [class.copy]p10:
2157 // If the class definition does not explicitly declare a copy
2158 // assignment operator, one is declared implicitly.
2159 // The implicitly-defined copy assignment operator for a class X
2160 // will have the form
2161 //
2162 // X& X::operator=(const X&)
2163 //
2164 // if
2165 bool HasConstCopyAssignment = true;
2166
2167 // -- each direct base class B of X has a copy assignment operator
2168 // whose parameter is of type const B&, const volatile B& or B,
2169 // and
2170 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2171 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002172 assert(!Base->getType()->isDependentType() &&
2173 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002174 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002175 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002176 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002177 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002178 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002179 }
2180
2181 // -- for all the nonstatic data members of X that are of a class
2182 // type M (or array thereof), each such class type has a copy
2183 // assignment operator whose parameter is of type const M&,
2184 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002185 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2186 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002187 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002188 QualType FieldType = (*Field)->getType();
2189 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2190 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002191 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002192 const CXXRecordDecl *FieldClassDecl
2193 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002194 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002195 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002196 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002197 }
2198 }
2199
2200 // Otherwise, the implicitly declared copy assignment operator will
2201 // have the form
2202 //
2203 // X& X::operator=(X&)
2204 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002205 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002206 if (HasConstCopyAssignment)
2207 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002208 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002209
2210 // An implicitly-declared copy assignment operator is an inline public
2211 // member of its class.
2212 DeclarationName Name =
2213 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2214 CXXMethodDecl *CopyAssignment =
2215 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2216 Context.getFunctionType(RetType, &ArgType, 1,
2217 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002218 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002219 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002220 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002221 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002222 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002223
2224 // Add the parameter to the operator.
2225 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2226 ClassDecl->getLocation(),
2227 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002228 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002229 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002230 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002231
2232 // Don't call addedAssignmentOperator. There is no way to distinguish an
2233 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002234 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002235 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002236 }
2237
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002238 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002239 // C++ [class.dtor]p2:
2240 // If a class has no user-declared destructor, a destructor is
2241 // declared implicitly. An implicitly-declared destructor is an
2242 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002243 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002244 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002245 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002246 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002247 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002248 Context.getFunctionType(Context.VoidTy,
2249 0, 0, false, 0),
2250 /*isInline=*/true,
2251 /*isImplicitlyDeclared=*/true);
2252 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002253 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002254 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002255 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002256
2257 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002258 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002259}
2260
Douglas Gregor6569d682009-05-27 23:11:45 +00002261void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002262 Decl *D = TemplateD.getAs<Decl>();
2263 if (!D)
2264 return;
2265
2266 TemplateParameterList *Params = 0;
2267 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2268 Params = Template->getTemplateParameters();
2269 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2270 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2271 Params = PartialSpec->getTemplateParameters();
2272 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002273 return;
2274
Douglas Gregor6569d682009-05-27 23:11:45 +00002275 for (TemplateParameterList::iterator Param = Params->begin(),
2276 ParamEnd = Params->end();
2277 Param != ParamEnd; ++Param) {
2278 NamedDecl *Named = cast<NamedDecl>(*Param);
2279 if (Named->getDeclName()) {
2280 S->AddDecl(DeclPtrTy::make(Named));
2281 IdResolver.AddDecl(Named);
2282 }
2283 }
2284}
2285
John McCall7a1dc562009-12-19 10:49:29 +00002286void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2287 if (!RecordD) return;
2288 AdjustDeclIfTemplate(RecordD);
2289 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2290 PushDeclContext(S, Record);
2291}
2292
2293void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2294 if (!RecordD) return;
2295 PopDeclContext();
2296}
2297
Douglas Gregor72b505b2008-12-16 21:30:33 +00002298/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2299/// parsing a top-level (non-nested) C++ class, and we are now
2300/// parsing those parts of the given Method declaration that could
2301/// not be parsed earlier (C++ [class.mem]p2), such as default
2302/// arguments. This action should enter the scope of the given
2303/// Method declaration as if we had just parsed the qualified method
2304/// name. However, it should not bring the parameters into scope;
2305/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002306void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002307}
2308
2309/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2310/// C++ method declaration. We're (re-)introducing the given
2311/// function parameter into scope for use in parsing later parts of
2312/// the method declaration. For example, we could see an
2313/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002314void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002315 if (!ParamD)
2316 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Chris Lattnerb28317a2009-03-28 19:18:32 +00002318 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002319
2320 // If this parameter has an unparsed default argument, clear it out
2321 // to make way for the parsed default argument.
2322 if (Param->hasUnparsedDefaultArg())
2323 Param->setDefaultArg(0);
2324
Chris Lattnerb28317a2009-03-28 19:18:32 +00002325 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002326 if (Param->getDeclName())
2327 IdResolver.AddDecl(Param);
2328}
2329
2330/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2331/// processing the delayed method declaration for Method. The method
2332/// declaration is now considered finished. There may be a separate
2333/// ActOnStartOfFunctionDef action later (not necessarily
2334/// immediately!) for this method, if it was also defined inside the
2335/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002336void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002337 if (!MethodD)
2338 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002340 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Chris Lattnerb28317a2009-03-28 19:18:32 +00002342 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002343
2344 // Now that we have our default arguments, check the constructor
2345 // again. It could produce additional diagnostics or affect whether
2346 // the class has implicitly-declared destructors, among other
2347 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002348 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2349 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002350
2351 // Check the default arguments, which we may have added.
2352 if (!Method->isInvalidDecl())
2353 CheckCXXDefaultArguments(Method);
2354}
2355
Douglas Gregor42a552f2008-11-05 20:51:48 +00002356/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002357/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002358/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002359/// emit diagnostics and set the invalid bit to true. In any case, the type
2360/// will be updated to reflect a well-formed type for the constructor and
2361/// returned.
2362QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2363 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002364 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002365
2366 // C++ [class.ctor]p3:
2367 // A constructor shall not be virtual (10.3) or static (9.4). A
2368 // constructor can be invoked for a const, volatile or const
2369 // volatile object. A constructor shall not be declared const,
2370 // volatile, or const volatile (9.3.2).
2371 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002372 if (!D.isInvalidType())
2373 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2374 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2375 << SourceRange(D.getIdentifierLoc());
2376 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002377 }
2378 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002379 if (!D.isInvalidType())
2380 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2381 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2382 << SourceRange(D.getIdentifierLoc());
2383 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002384 SC = FunctionDecl::None;
2385 }
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Chris Lattner65401802009-04-25 08:28:21 +00002387 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2388 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002389 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002390 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2391 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002392 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002393 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2394 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002395 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002396 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2397 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002398 }
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Douglas Gregor42a552f2008-11-05 20:51:48 +00002400 // Rebuild the function type "R" without any type qualifiers (in
2401 // case any of the errors above fired) and with "void" as the
2402 // return type, since constructors don't have return types. We
2403 // *always* have to do this, because GetTypeForDeclarator will
2404 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002405 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002406 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2407 Proto->getNumArgs(),
2408 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002409}
2410
Douglas Gregor72b505b2008-12-16 21:30:33 +00002411/// CheckConstructor - Checks a fully-formed constructor for
2412/// well-formedness, issuing any diagnostics required. Returns true if
2413/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002414void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002415 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002416 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2417 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002418 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002419
2420 // C++ [class.copy]p3:
2421 // A declaration of a constructor for a class X is ill-formed if
2422 // its first parameter is of type (optionally cv-qualified) X and
2423 // either there are no other parameters or else all other
2424 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002425 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002426 ((Constructor->getNumParams() == 1) ||
2427 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002428 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2429 Constructor->getTemplateSpecializationKind()
2430 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002431 QualType ParamType = Constructor->getParamDecl(0)->getType();
2432 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2433 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002434 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2435 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002436 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002437
2438 // FIXME: Rather that making the constructor invalid, we should endeavor
2439 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002440 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002441 }
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Douglas Gregor72b505b2008-12-16 21:30:33 +00002444 // Notify the class that we've added a constructor.
2445 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002446}
2447
Anders Carlsson37909802009-11-30 21:24:50 +00002448/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2449/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002450bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002451 CXXRecordDecl *RD = Destructor->getParent();
2452
2453 if (Destructor->isVirtual()) {
2454 SourceLocation Loc;
2455
2456 if (!Destructor->isImplicit())
2457 Loc = Destructor->getLocation();
2458 else
2459 Loc = RD->getLocation();
2460
2461 // If we have a virtual destructor, look up the deallocation function
2462 FunctionDecl *OperatorDelete = 0;
2463 DeclarationName Name =
2464 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002465 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002466 return true;
2467
2468 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002469 }
Anders Carlsson37909802009-11-30 21:24:50 +00002470
2471 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002472}
2473
Mike Stump1eb44332009-09-09 15:08:12 +00002474static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002475FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2476 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2477 FTI.ArgInfo[0].Param &&
2478 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2479}
2480
Douglas Gregor42a552f2008-11-05 20:51:48 +00002481/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2482/// the well-formednes of the destructor declarator @p D with type @p
2483/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002484/// emit diagnostics and set the declarator to invalid. Even if this happens,
2485/// will be updated to reflect a well-formed type for the destructor and
2486/// returned.
2487QualType Sema::CheckDestructorDeclarator(Declarator &D,
2488 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002489 // C++ [class.dtor]p1:
2490 // [...] A typedef-name that names a class is a class-name
2491 // (7.1.3); however, a typedef-name that names a class shall not
2492 // be used as the identifier in the declarator for a destructor
2493 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002494 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002495 if (isa<TypedefType>(DeclaratorType)) {
2496 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002497 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002498 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002499 }
2500
2501 // C++ [class.dtor]p2:
2502 // A destructor is used to destroy objects of its class type. A
2503 // destructor takes no parameters, and no return type can be
2504 // specified for it (not even void). The address of a destructor
2505 // shall not be taken. A destructor shall not be static. A
2506 // destructor can be invoked for a const, volatile or const
2507 // volatile object. A destructor shall not be declared const,
2508 // volatile or const volatile (9.3.2).
2509 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002510 if (!D.isInvalidType())
2511 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2512 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2513 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002514 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002515 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002516 }
Chris Lattner65401802009-04-25 08:28:21 +00002517 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002518 // Destructors don't have return types, but the parser will
2519 // happily parse something like:
2520 //
2521 // class X {
2522 // float ~X();
2523 // };
2524 //
2525 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002526 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2527 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2528 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002529 }
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Chris Lattner65401802009-04-25 08:28:21 +00002531 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2532 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002533 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002534 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2535 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002536 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002537 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2538 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002539 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002540 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2541 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002542 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002543 }
2544
2545 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002546 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002547 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2548
2549 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002550 FTI.freeArgs();
2551 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002552 }
2553
Mike Stump1eb44332009-09-09 15:08:12 +00002554 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002555 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002556 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002557 D.setInvalidType();
2558 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002559
2560 // Rebuild the function type "R" without any type qualifiers or
2561 // parameters (in case any of the errors above fired) and with
2562 // "void" as the return type, since destructors don't have return
2563 // types. We *always* have to do this, because GetTypeForDeclarator
2564 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002565 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002566}
2567
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002568/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2569/// well-formednes of the conversion function declarator @p D with
2570/// type @p R. If there are any errors in the declarator, this routine
2571/// will emit diagnostics and return true. Otherwise, it will return
2572/// false. Either way, the type @p R will be updated to reflect a
2573/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002574void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002575 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002576 // C++ [class.conv.fct]p1:
2577 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002578 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002579 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002580 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002581 if (!D.isInvalidType())
2582 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2583 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2584 << SourceRange(D.getIdentifierLoc());
2585 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002586 SC = FunctionDecl::None;
2587 }
Chris Lattner6e475012009-04-25 08:35:12 +00002588 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002589 // Conversion functions don't have return types, but the parser will
2590 // happily parse something like:
2591 //
2592 // class X {
2593 // float operator bool();
2594 // };
2595 //
2596 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002597 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2598 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2599 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002600 }
2601
2602 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002603 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002604 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2605
2606 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002607 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002608 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002609 }
2610
Mike Stump1eb44332009-09-09 15:08:12 +00002611 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002612 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002613 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002614 D.setInvalidType();
2615 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002616
2617 // C++ [class.conv.fct]p4:
2618 // The conversion-type-id shall not represent a function type nor
2619 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002620 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002621 if (ConvType->isArrayType()) {
2622 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2623 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002624 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002625 } else if (ConvType->isFunctionType()) {
2626 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2627 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002628 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002629 }
2630
2631 // Rebuild the function type "R" without any parameters (in case any
2632 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002633 // return type.
2634 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002635 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002636
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002637 // C++0x explicit conversion operators.
2638 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002639 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002640 diag::warn_explicit_conversion_functions)
2641 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002642}
2643
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002644/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2645/// the declaration of the given C++ conversion function. This routine
2646/// is responsible for recording the conversion function in the C++
2647/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002648Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002649 assert(Conversion && "Expected to receive a conversion function declaration");
2650
Douglas Gregor9d350972008-12-12 08:25:50 +00002651 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002652
2653 // Make sure we aren't redeclaring the conversion function.
2654 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002655
2656 // C++ [class.conv.fct]p1:
2657 // [...] A conversion function is never used to convert a
2658 // (possibly cv-qualified) object to the (possibly cv-qualified)
2659 // same object type (or a reference to it), to a (possibly
2660 // cv-qualified) base class of that type (or a reference to it),
2661 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002662 // FIXME: Suppress this warning if the conversion function ends up being a
2663 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002664 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002665 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002666 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002667 ConvType = ConvTypeRef->getPointeeType();
2668 if (ConvType->isRecordType()) {
2669 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2670 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002671 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002672 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002673 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002674 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002675 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002676 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002677 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002678 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002679 }
2680
Douglas Gregor70316a02008-12-26 15:00:45 +00002681 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002682 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002683 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002684 = Conversion->getDescribedFunctionTemplate())
2685 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002686 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2687 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002688 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002689 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002690 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002691 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002692 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002693 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002694
Chris Lattnerb28317a2009-03-28 19:18:32 +00002695 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002696}
2697
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002698//===----------------------------------------------------------------------===//
2699// Namespace Handling
2700//===----------------------------------------------------------------------===//
2701
2702/// ActOnStartNamespaceDef - This is called at the start of a namespace
2703/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002704Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2705 SourceLocation IdentLoc,
2706 IdentifierInfo *II,
2707 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002708 NamespaceDecl *Namespc =
2709 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2710 Namespc->setLBracLoc(LBrace);
2711
2712 Scope *DeclRegionScope = NamespcScope->getParent();
2713
2714 if (II) {
2715 // C++ [namespace.def]p2:
2716 // The identifier in an original-namespace-definition shall not have been
2717 // previously defined in the declarative region in which the
2718 // original-namespace-definition appears. The identifier in an
2719 // original-namespace-definition is the name of the namespace. Subsequently
2720 // in that declarative region, it is treated as an original-namespace-name.
2721
John McCallf36e02d2009-10-09 21:13:30 +00002722 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002723 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002724 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregor44b43212008-12-11 16:49:14 +00002726 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2727 // This is an extended namespace definition.
2728 // Attach this namespace decl to the chain of extended namespace
2729 // definitions.
2730 OrigNS->setNextNamespace(Namespc);
2731 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002732
Mike Stump1eb44332009-09-09 15:08:12 +00002733 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002734 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002735 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002736 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002737 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002738 } else if (PrevDecl) {
2739 // This is an invalid name redefinition.
2740 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2741 << Namespc->getDeclName();
2742 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2743 Namespc->setInvalidDecl();
2744 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002745 } else if (II->isStr("std") &&
2746 CurContext->getLookupContext()->isTranslationUnit()) {
2747 // This is the first "real" definition of the namespace "std", so update
2748 // our cache of the "std" namespace to point at this definition.
2749 if (StdNamespace) {
2750 // We had already defined a dummy namespace "std". Link this new
2751 // namespace definition to the dummy namespace "std".
2752 StdNamespace->setNextNamespace(Namespc);
2753 StdNamespace->setLocation(IdentLoc);
2754 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2755 }
2756
2757 // Make our StdNamespace cache point at the first real definition of the
2758 // "std" namespace.
2759 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002760 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002761
2762 PushOnScopeChains(Namespc, DeclRegionScope);
2763 } else {
John McCall9aeed322009-10-01 00:25:31 +00002764 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002765 assert(Namespc->isAnonymousNamespace());
2766 CurContext->addDecl(Namespc);
2767
2768 // Link the anonymous namespace into its parent.
2769 NamespaceDecl *PrevDecl;
2770 DeclContext *Parent = CurContext->getLookupContext();
2771 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2772 PrevDecl = TU->getAnonymousNamespace();
2773 TU->setAnonymousNamespace(Namespc);
2774 } else {
2775 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2776 PrevDecl = ND->getAnonymousNamespace();
2777 ND->setAnonymousNamespace(Namespc);
2778 }
2779
2780 // Link the anonymous namespace with its previous declaration.
2781 if (PrevDecl) {
2782 assert(PrevDecl->isAnonymousNamespace());
2783 assert(!PrevDecl->getNextNamespace());
2784 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2785 PrevDecl->setNextNamespace(Namespc);
2786 }
John McCall9aeed322009-10-01 00:25:31 +00002787
2788 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2789 // behaves as if it were replaced by
2790 // namespace unique { /* empty body */ }
2791 // using namespace unique;
2792 // namespace unique { namespace-body }
2793 // where all occurrences of 'unique' in a translation unit are
2794 // replaced by the same identifier and this identifier differs
2795 // from all other identifiers in the entire program.
2796
2797 // We just create the namespace with an empty name and then add an
2798 // implicit using declaration, just like the standard suggests.
2799 //
2800 // CodeGen enforces the "universally unique" aspect by giving all
2801 // declarations semantically contained within an anonymous
2802 // namespace internal linkage.
2803
John McCall5fdd7642009-12-16 02:06:49 +00002804 if (!PrevDecl) {
2805 UsingDirectiveDecl* UD
2806 = UsingDirectiveDecl::Create(Context, CurContext,
2807 /* 'using' */ LBrace,
2808 /* 'namespace' */ SourceLocation(),
2809 /* qualifier */ SourceRange(),
2810 /* NNS */ NULL,
2811 /* identifier */ SourceLocation(),
2812 Namespc,
2813 /* Ancestor */ CurContext);
2814 UD->setImplicit();
2815 CurContext->addDecl(UD);
2816 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002817 }
2818
2819 // Although we could have an invalid decl (i.e. the namespace name is a
2820 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002821 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2822 // for the namespace has the declarations that showed up in that particular
2823 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002824 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002825 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002826}
2827
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002828/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2829/// is a namespace alias, returns the namespace it points to.
2830static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2831 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2832 return AD->getNamespace();
2833 return dyn_cast_or_null<NamespaceDecl>(D);
2834}
2835
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002836/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2837/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002838void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2839 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002840 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2841 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2842 Namespc->setRBracLoc(RBrace);
2843 PopDeclContext();
2844}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002845
Chris Lattnerb28317a2009-03-28 19:18:32 +00002846Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2847 SourceLocation UsingLoc,
2848 SourceLocation NamespcLoc,
2849 const CXXScopeSpec &SS,
2850 SourceLocation IdentLoc,
2851 IdentifierInfo *NamespcName,
2852 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002853 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2854 assert(NamespcName && "Invalid NamespcName.");
2855 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002856 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002857
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002858 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002859
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002860 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002861 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2862 LookupParsedName(R, S, &SS);
2863 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002864 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002865
John McCallf36e02d2009-10-09 21:13:30 +00002866 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002867 NamedDecl *Named = R.getFoundDecl();
2868 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2869 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002870 // C++ [namespace.udir]p1:
2871 // A using-directive specifies that the names in the nominated
2872 // namespace can be used in the scope in which the
2873 // using-directive appears after the using-directive. During
2874 // unqualified name lookup (3.4.1), the names appear as if they
2875 // were declared in the nearest enclosing namespace which
2876 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002877 // namespace. [Note: in this context, "contains" means "contains
2878 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002879
2880 // Find enclosing context containing both using-directive and
2881 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002882 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002883 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2884 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2885 CommonAncestor = CommonAncestor->getParent();
2886
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002887 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002888 SS.getRange(),
2889 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002890 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002891 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002892 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002893 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002894 }
2895
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002896 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002897 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002898 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002899}
2900
2901void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2902 // If scope has associated entity, then using directive is at namespace
2903 // or translation unit scope. We add UsingDirectiveDecls, into
2904 // it's lookup structure.
2905 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002906 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002907 else
2908 // Otherwise it is block-sope. using-directives will affect lookup
2909 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002910 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002911}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002912
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002913
2914Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002915 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00002916 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002917 SourceLocation UsingLoc,
2918 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002919 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002920 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002921 bool IsTypeName,
2922 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002923 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Douglas Gregor12c118a2009-11-04 16:30:06 +00002925 switch (Name.getKind()) {
2926 case UnqualifiedId::IK_Identifier:
2927 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002928 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002929 case UnqualifiedId::IK_ConversionFunctionId:
2930 break;
2931
2932 case UnqualifiedId::IK_ConstructorName:
John McCall604e7f12009-12-08 07:46:18 +00002933 // C++0x inherited constructors.
2934 if (getLangOptions().CPlusPlus0x) break;
2935
Douglas Gregor12c118a2009-11-04 16:30:06 +00002936 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2937 << SS.getRange();
2938 return DeclPtrTy();
2939
2940 case UnqualifiedId::IK_DestructorName:
2941 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2942 << SS.getRange();
2943 return DeclPtrTy();
2944
2945 case UnqualifiedId::IK_TemplateId:
2946 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2947 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2948 return DeclPtrTy();
2949 }
2950
2951 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00002952 if (!TargetName)
2953 return DeclPtrTy();
2954
John McCall60fa3cf2009-12-11 02:10:03 +00002955 // Warn about using declarations.
2956 // TODO: store that the declaration was written without 'using' and
2957 // talk about access decls instead of using decls in the
2958 // diagnostics.
2959 if (!HasUsingKeyword) {
2960 UsingLoc = Name.getSourceRange().getBegin();
2961
2962 Diag(UsingLoc, diag::warn_access_decl_deprecated)
2963 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
2964 "using ");
2965 }
2966
John McCall9488ea12009-11-17 05:59:44 +00002967 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002968 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002969 TargetName, AttrList,
2970 /* IsInstantiation */ false,
2971 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00002972 if (UD)
2973 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Anders Carlssonc72160b2009-08-28 05:40:36 +00002975 return DeclPtrTy::make(UD);
2976}
2977
John McCall9f54ad42009-12-10 09:41:52 +00002978/// Determines whether to create a using shadow decl for a particular
2979/// decl, given the set of decls existing prior to this using lookup.
2980bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2981 const LookupResult &Previous) {
2982 // Diagnose finding a decl which is not from a base class of the
2983 // current class. We do this now because there are cases where this
2984 // function will silently decide not to build a shadow decl, which
2985 // will pre-empt further diagnostics.
2986 //
2987 // We don't need to do this in C++0x because we do the check once on
2988 // the qualifier.
2989 //
2990 // FIXME: diagnose the following if we care enough:
2991 // struct A { int foo; };
2992 // struct B : A { using A::foo; };
2993 // template <class T> struct C : A {};
2994 // template <class T> struct D : C<T> { using B::foo; } // <---
2995 // This is invalid (during instantiation) in C++03 because B::foo
2996 // resolves to the using decl in B, which is not a base class of D<T>.
2997 // We can't diagnose it immediately because C<T> is an unknown
2998 // specialization. The UsingShadowDecl in D<T> then points directly
2999 // to A::foo, which will look well-formed when we instantiate.
3000 // The right solution is to not collapse the shadow-decl chain.
3001 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3002 DeclContext *OrigDC = Orig->getDeclContext();
3003
3004 // Handle enums and anonymous structs.
3005 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3006 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3007 while (OrigRec->isAnonymousStructOrUnion())
3008 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3009
3010 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3011 if (OrigDC == CurContext) {
3012 Diag(Using->getLocation(),
3013 diag::err_using_decl_nested_name_specifier_is_current_class)
3014 << Using->getNestedNameRange();
3015 Diag(Orig->getLocation(), diag::note_using_decl_target);
3016 return true;
3017 }
3018
3019 Diag(Using->getNestedNameRange().getBegin(),
3020 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3021 << Using->getTargetNestedNameDecl()
3022 << cast<CXXRecordDecl>(CurContext)
3023 << Using->getNestedNameRange();
3024 Diag(Orig->getLocation(), diag::note_using_decl_target);
3025 return true;
3026 }
3027 }
3028
3029 if (Previous.empty()) return false;
3030
3031 NamedDecl *Target = Orig;
3032 if (isa<UsingShadowDecl>(Target))
3033 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3034
John McCalld7533ec2009-12-11 02:33:26 +00003035 // If the target happens to be one of the previous declarations, we
3036 // don't have a conflict.
3037 //
3038 // FIXME: but we might be increasing its access, in which case we
3039 // should redeclare it.
3040 NamedDecl *NonTag = 0, *Tag = 0;
3041 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3042 I != E; ++I) {
3043 NamedDecl *D = (*I)->getUnderlyingDecl();
3044 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3045 return false;
3046
3047 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3048 }
3049
John McCall9f54ad42009-12-10 09:41:52 +00003050 if (Target->isFunctionOrFunctionTemplate()) {
3051 FunctionDecl *FD;
3052 if (isa<FunctionTemplateDecl>(Target))
3053 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3054 else
3055 FD = cast<FunctionDecl>(Target);
3056
3057 NamedDecl *OldDecl = 0;
3058 switch (CheckOverload(FD, Previous, OldDecl)) {
3059 case Ovl_Overload:
3060 return false;
3061
3062 case Ovl_NonFunction:
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 // We found a decl with the exact signature.
3067 case Ovl_Match:
3068 if (isa<UsingShadowDecl>(OldDecl)) {
3069 // Silently ignore the possible conflict.
3070 return false;
3071 }
3072
3073 // If we're in a record, we want to hide the target, so we
3074 // return true (without a diagnostic) to tell the caller not to
3075 // build a shadow decl.
3076 if (CurContext->isRecord())
3077 return true;
3078
3079 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003080 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003081 break;
3082 }
3083
3084 Diag(Target->getLocation(), diag::note_using_decl_target);
3085 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3086 return true;
3087 }
3088
3089 // Target is not a function.
3090
John McCall9f54ad42009-12-10 09:41:52 +00003091 if (isa<TagDecl>(Target)) {
3092 // No conflict between a tag and a non-tag.
3093 if (!Tag) return false;
3094
John McCall41ce66f2009-12-10 19:51:03 +00003095 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003096 Diag(Target->getLocation(), diag::note_using_decl_target);
3097 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3098 return true;
3099 }
3100
3101 // No conflict between a tag and a non-tag.
3102 if (!NonTag) return false;
3103
John McCall41ce66f2009-12-10 19:51:03 +00003104 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003105 Diag(Target->getLocation(), diag::note_using_decl_target);
3106 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3107 return true;
3108}
3109
John McCall9488ea12009-11-17 05:59:44 +00003110/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003111UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003112 UsingDecl *UD,
3113 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003114
3115 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003116 NamedDecl *Target = Orig;
3117 if (isa<UsingShadowDecl>(Target)) {
3118 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3119 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003120 }
3121
3122 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003123 = UsingShadowDecl::Create(Context, CurContext,
3124 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003125 UD->addShadowDecl(Shadow);
3126
3127 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003128 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003129 else
John McCall604e7f12009-12-08 07:46:18 +00003130 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003131 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003132
John McCall604e7f12009-12-08 07:46:18 +00003133 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3134 Shadow->setInvalidDecl();
3135
John McCall9f54ad42009-12-10 09:41:52 +00003136 return Shadow;
3137}
John McCall604e7f12009-12-08 07:46:18 +00003138
John McCall9f54ad42009-12-10 09:41:52 +00003139/// Hides a using shadow declaration. This is required by the current
3140/// using-decl implementation when a resolvable using declaration in a
3141/// class is followed by a declaration which would hide or override
3142/// one or more of the using decl's targets; for example:
3143///
3144/// struct Base { void foo(int); };
3145/// struct Derived : Base {
3146/// using Base::foo;
3147/// void foo(int);
3148/// };
3149///
3150/// The governing language is C++03 [namespace.udecl]p12:
3151///
3152/// When a using-declaration brings names from a base class into a
3153/// derived class scope, member functions in the derived class
3154/// override and/or hide member functions with the same name and
3155/// parameter types in a base class (rather than conflicting).
3156///
3157/// There are two ways to implement this:
3158/// (1) optimistically create shadow decls when they're not hidden
3159/// by existing declarations, or
3160/// (2) don't create any shadow decls (or at least don't make them
3161/// visible) until we've fully parsed/instantiated the class.
3162/// The problem with (1) is that we might have to retroactively remove
3163/// a shadow decl, which requires several O(n) operations because the
3164/// decl structures are (very reasonably) not designed for removal.
3165/// (2) avoids this but is very fiddly and phase-dependent.
3166void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3167 // Remove it from the DeclContext...
3168 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003169
John McCall9f54ad42009-12-10 09:41:52 +00003170 // ...and the scope, if applicable...
3171 if (S) {
3172 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3173 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003174 }
3175
John McCall9f54ad42009-12-10 09:41:52 +00003176 // ...and the using decl.
3177 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3178
3179 // TODO: complain somehow if Shadow was used. It shouldn't
3180 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003181}
3182
John McCall7ba107a2009-11-18 02:36:19 +00003183/// Builds a using declaration.
3184///
3185/// \param IsInstantiation - Whether this call arises from an
3186/// instantiation of an unresolved using declaration. We treat
3187/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003188NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3189 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003190 const CXXScopeSpec &SS,
3191 SourceLocation IdentLoc,
3192 DeclarationName Name,
3193 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003194 bool IsInstantiation,
3195 bool IsTypeName,
3196 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003197 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3198 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003199
Anders Carlsson550b14b2009-08-28 05:49:21 +00003200 // FIXME: We ignore attributes for now.
3201 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003203 if (SS.isEmpty()) {
3204 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003205 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003206 }
Mike Stump1eb44332009-09-09 15:08:12 +00003207
John McCall9f54ad42009-12-10 09:41:52 +00003208 // Do the redeclaration lookup in the current scope.
3209 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3210 ForRedeclaration);
3211 Previous.setHideTags(false);
3212 if (S) {
3213 LookupName(Previous, S);
3214
3215 // It is really dumb that we have to do this.
3216 LookupResult::Filter F = Previous.makeFilter();
3217 while (F.hasNext()) {
3218 NamedDecl *D = F.next();
3219 if (!isDeclInScope(D, CurContext, S))
3220 F.erase();
3221 }
3222 F.done();
3223 } else {
3224 assert(IsInstantiation && "no scope in non-instantiation");
3225 assert(CurContext->isRecord() && "scope not record in instantiation");
3226 LookupQualifiedName(Previous, CurContext);
3227 }
3228
Mike Stump1eb44332009-09-09 15:08:12 +00003229 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003230 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3231
John McCall9f54ad42009-12-10 09:41:52 +00003232 // Check for invalid redeclarations.
3233 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3234 return 0;
3235
3236 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003237 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3238 return 0;
3239
John McCallaf8e6ed2009-11-12 03:15:40 +00003240 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003241 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003242 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003243 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003244 // FIXME: not all declaration name kinds are legal here
3245 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3246 UsingLoc, TypenameLoc,
3247 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003248 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003249 } else {
3250 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3251 UsingLoc, SS.getRange(), NNS,
3252 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003253 }
John McCalled976492009-12-04 22:46:56 +00003254 } else {
3255 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3256 SS.getRange(), UsingLoc, NNS, Name,
3257 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003258 }
John McCalled976492009-12-04 22:46:56 +00003259 D->setAccess(AS);
3260 CurContext->addDecl(D);
3261
3262 if (!LookupContext) return D;
3263 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003264
John McCall604e7f12009-12-08 07:46:18 +00003265 if (RequireCompleteDeclContext(SS)) {
3266 UD->setInvalidDecl();
3267 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003268 }
3269
John McCall604e7f12009-12-08 07:46:18 +00003270 // Look up the target name.
3271
John McCalla24dc2e2009-11-17 02:14:36 +00003272 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003273
John McCall604e7f12009-12-08 07:46:18 +00003274 // Unlike most lookups, we don't always want to hide tag
3275 // declarations: tag names are visible through the using declaration
3276 // even if hidden by ordinary names, *except* in a dependent context
3277 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003278 if (!IsInstantiation)
3279 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003280
John McCalla24dc2e2009-11-17 02:14:36 +00003281 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003282
John McCallf36e02d2009-10-09 21:13:30 +00003283 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003284 Diag(IdentLoc, diag::err_no_member)
3285 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003286 UD->setInvalidDecl();
3287 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003288 }
3289
John McCalled976492009-12-04 22:46:56 +00003290 if (R.isAmbiguous()) {
3291 UD->setInvalidDecl();
3292 return UD;
3293 }
Mike Stump1eb44332009-09-09 15:08:12 +00003294
John McCall7ba107a2009-11-18 02:36:19 +00003295 if (IsTypeName) {
3296 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003297 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003298 Diag(IdentLoc, diag::err_using_typename_non_type);
3299 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3300 Diag((*I)->getUnderlyingDecl()->getLocation(),
3301 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003302 UD->setInvalidDecl();
3303 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003304 }
3305 } else {
3306 // If we asked for a non-typename and we got a type, error out,
3307 // but only if this is an instantiation of an unresolved using
3308 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003309 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003310 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3311 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003312 UD->setInvalidDecl();
3313 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003314 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003315 }
3316
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003317 // C++0x N2914 [namespace.udecl]p6:
3318 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003319 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003320 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3321 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003322 UD->setInvalidDecl();
3323 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003324 }
Mike Stump1eb44332009-09-09 15:08:12 +00003325
John McCall9f54ad42009-12-10 09:41:52 +00003326 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3327 if (!CheckUsingShadowDecl(UD, *I, Previous))
3328 BuildUsingShadowDecl(S, UD, *I);
3329 }
John McCall9488ea12009-11-17 05:59:44 +00003330
3331 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003332}
3333
John McCall9f54ad42009-12-10 09:41:52 +00003334/// Checks that the given using declaration is not an invalid
3335/// redeclaration. Note that this is checking only for the using decl
3336/// itself, not for any ill-formedness among the UsingShadowDecls.
3337bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3338 bool isTypeName,
3339 const CXXScopeSpec &SS,
3340 SourceLocation NameLoc,
3341 const LookupResult &Prev) {
3342 // C++03 [namespace.udecl]p8:
3343 // C++0x [namespace.udecl]p10:
3344 // A using-declaration is a declaration and can therefore be used
3345 // repeatedly where (and only where) multiple declarations are
3346 // allowed.
3347 // That's only in file contexts.
3348 if (CurContext->getLookupContext()->isFileContext())
3349 return false;
3350
3351 NestedNameSpecifier *Qual
3352 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3353
3354 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3355 NamedDecl *D = *I;
3356
3357 bool DTypename;
3358 NestedNameSpecifier *DQual;
3359 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3360 DTypename = UD->isTypeName();
3361 DQual = UD->getTargetNestedNameDecl();
3362 } else if (UnresolvedUsingValueDecl *UD
3363 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3364 DTypename = false;
3365 DQual = UD->getTargetNestedNameSpecifier();
3366 } else if (UnresolvedUsingTypenameDecl *UD
3367 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3368 DTypename = true;
3369 DQual = UD->getTargetNestedNameSpecifier();
3370 } else continue;
3371
3372 // using decls differ if one says 'typename' and the other doesn't.
3373 // FIXME: non-dependent using decls?
3374 if (isTypeName != DTypename) continue;
3375
3376 // using decls differ if they name different scopes (but note that
3377 // template instantiation can cause this check to trigger when it
3378 // didn't before instantiation).
3379 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3380 Context.getCanonicalNestedNameSpecifier(DQual))
3381 continue;
3382
3383 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003384 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003385 return true;
3386 }
3387
3388 return false;
3389}
3390
John McCall604e7f12009-12-08 07:46:18 +00003391
John McCalled976492009-12-04 22:46:56 +00003392/// Checks that the given nested-name qualifier used in a using decl
3393/// in the current context is appropriately related to the current
3394/// scope. If an error is found, diagnoses it and returns true.
3395bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3396 const CXXScopeSpec &SS,
3397 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003398 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003399
John McCall604e7f12009-12-08 07:46:18 +00003400 if (!CurContext->isRecord()) {
3401 // C++03 [namespace.udecl]p3:
3402 // C++0x [namespace.udecl]p8:
3403 // A using-declaration for a class member shall be a member-declaration.
3404
3405 // If we weren't able to compute a valid scope, it must be a
3406 // dependent class scope.
3407 if (!NamedContext || NamedContext->isRecord()) {
3408 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3409 << SS.getRange();
3410 return true;
3411 }
3412
3413 // Otherwise, everything is known to be fine.
3414 return false;
3415 }
3416
3417 // The current scope is a record.
3418
3419 // If the named context is dependent, we can't decide much.
3420 if (!NamedContext) {
3421 // FIXME: in C++0x, we can diagnose if we can prove that the
3422 // nested-name-specifier does not refer to a base class, which is
3423 // still possible in some cases.
3424
3425 // Otherwise we have to conservatively report that things might be
3426 // okay.
3427 return false;
3428 }
3429
3430 if (!NamedContext->isRecord()) {
3431 // Ideally this would point at the last name in the specifier,
3432 // but we don't have that level of source info.
3433 Diag(SS.getRange().getBegin(),
3434 diag::err_using_decl_nested_name_specifier_is_not_class)
3435 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3436 return true;
3437 }
3438
3439 if (getLangOptions().CPlusPlus0x) {
3440 // C++0x [namespace.udecl]p3:
3441 // In a using-declaration used as a member-declaration, the
3442 // nested-name-specifier shall name a base class of the class
3443 // being defined.
3444
3445 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3446 cast<CXXRecordDecl>(NamedContext))) {
3447 if (CurContext == NamedContext) {
3448 Diag(NameLoc,
3449 diag::err_using_decl_nested_name_specifier_is_current_class)
3450 << SS.getRange();
3451 return true;
3452 }
3453
3454 Diag(SS.getRange().getBegin(),
3455 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3456 << (NestedNameSpecifier*) SS.getScopeRep()
3457 << cast<CXXRecordDecl>(CurContext)
3458 << SS.getRange();
3459 return true;
3460 }
3461
3462 return false;
3463 }
3464
3465 // C++03 [namespace.udecl]p4:
3466 // A using-declaration used as a member-declaration shall refer
3467 // to a member of a base class of the class being defined [etc.].
3468
3469 // Salient point: SS doesn't have to name a base class as long as
3470 // lookup only finds members from base classes. Therefore we can
3471 // diagnose here only if we can prove that that can't happen,
3472 // i.e. if the class hierarchies provably don't intersect.
3473
3474 // TODO: it would be nice if "definitely valid" results were cached
3475 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3476 // need to be repeated.
3477
3478 struct UserData {
3479 llvm::DenseSet<const CXXRecordDecl*> Bases;
3480
3481 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3482 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3483 Data->Bases.insert(Base);
3484 return true;
3485 }
3486
3487 bool hasDependentBases(const CXXRecordDecl *Class) {
3488 return !Class->forallBases(collect, this);
3489 }
3490
3491 /// Returns true if the base is dependent or is one of the
3492 /// accumulated base classes.
3493 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3494 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3495 return !Data->Bases.count(Base);
3496 }
3497
3498 bool mightShareBases(const CXXRecordDecl *Class) {
3499 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3500 }
3501 };
3502
3503 UserData Data;
3504
3505 // Returns false if we find a dependent base.
3506 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3507 return false;
3508
3509 // Returns false if the class has a dependent base or if it or one
3510 // of its bases is present in the base set of the current context.
3511 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3512 return false;
3513
3514 Diag(SS.getRange().getBegin(),
3515 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3516 << (NestedNameSpecifier*) SS.getScopeRep()
3517 << cast<CXXRecordDecl>(CurContext)
3518 << SS.getRange();
3519
3520 return true;
John McCalled976492009-12-04 22:46:56 +00003521}
3522
Mike Stump1eb44332009-09-09 15:08:12 +00003523Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003524 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003525 SourceLocation AliasLoc,
3526 IdentifierInfo *Alias,
3527 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003528 SourceLocation IdentLoc,
3529 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Anders Carlsson81c85c42009-03-28 23:53:49 +00003531 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003532 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3533 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003534
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003535 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003536 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003537 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003538 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003539 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003540 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003541 if (!R.isAmbiguous() && !R.empty() &&
3542 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003543 return DeclPtrTy();
3544 }
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003546 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3547 diag::err_redefinition_different_kind;
3548 Diag(AliasLoc, DiagID) << Alias;
3549 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003550 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003551 }
3552
John McCalla24dc2e2009-11-17 02:14:36 +00003553 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003554 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003555
John McCallf36e02d2009-10-09 21:13:30 +00003556 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003557 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003558 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003561 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003562 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3563 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003564 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003565 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003567 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003568 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003569}
3570
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003571void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3572 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003573 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3574 !Constructor->isUsed()) &&
3575 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Eli Friedman80c30da2009-11-09 19:20:36 +00003577 CXXRecordDecl *ClassDecl
3578 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3579 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003580
Eli Friedman80c30da2009-11-09 19:20:36 +00003581 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003582 Diag(CurrentLocation, diag::note_member_synthesized_at)
3583 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003584 Constructor->setInvalidDecl();
3585 } else {
3586 Constructor->setUsed();
3587 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003588}
3589
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003590void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003591 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003592 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3593 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003594 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003595 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3596 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003597 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003598 // implicitly defined, all the implicitly-declared default destructors
3599 // for its base class and its non-static data members shall have been
3600 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003601 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3602 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003603 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003604 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003605 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003606 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003607 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3608 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3609 else
Mike Stump1eb44332009-09-09 15:08:12 +00003610 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003611 "DefineImplicitDestructor - missing dtor in a base class");
3612 }
3613 }
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003615 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3616 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003617 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3618 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3619 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003620 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003621 CXXRecordDecl *FieldClassDecl
3622 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3623 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003624 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003625 const_cast<CXXDestructorDecl*>(
3626 FieldClassDecl->getDestructor(Context)))
3627 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3628 else
Mike Stump1eb44332009-09-09 15:08:12 +00003629 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003630 "DefineImplicitDestructor - missing dtor in class of a data member");
3631 }
3632 }
3633 }
Anders Carlsson37909802009-11-30 21:24:50 +00003634
3635 // FIXME: If CheckDestructor fails, we should emit a note about where the
3636 // implicit destructor was needed.
3637 if (CheckDestructor(Destructor)) {
3638 Diag(CurrentLocation, diag::note_member_synthesized_at)
3639 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3640
3641 Destructor->setInvalidDecl();
3642 return;
3643 }
3644
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003645 Destructor->setUsed();
3646}
3647
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003648void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3649 CXXMethodDecl *MethodDecl) {
3650 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3651 MethodDecl->getOverloadedOperator() == OO_Equal &&
3652 !MethodDecl->isUsed()) &&
3653 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003655 CXXRecordDecl *ClassDecl
3656 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003658 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003659 // Before the implicitly-declared copy assignment operator for a class is
3660 // implicitly defined, all implicitly-declared copy assignment operators
3661 // for its direct base classes and its nonstatic data members shall have
3662 // been implicitly defined.
3663 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003664 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3665 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003666 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003667 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003668 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003669 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3670 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003671 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3672 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003673 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3674 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003675 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3676 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3677 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003678 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003679 CXXRecordDecl *FieldClassDecl
3680 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003681 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003682 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3683 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003684 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003685 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003686 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003687 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3688 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003689 Diag(CurrentLocation, diag::note_first_required_here);
3690 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003691 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003692 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003693 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3694 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003695 Diag(CurrentLocation, diag::note_first_required_here);
3696 err = true;
3697 }
3698 }
3699 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003700 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003701}
3702
3703CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003704Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3705 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003706 CXXRecordDecl *ClassDecl) {
3707 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3708 QualType RHSType(LHSType);
3709 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003710 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003711 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003712 RHSType = Context.getCVRQualifiedType(RHSType,
3713 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003714 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003715 LHSType,
3716 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003717 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003718 RHSType,
3719 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003720 Expr *Args[2] = { &*LHS, &*RHS };
3721 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003722 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003723 CandidateSet);
3724 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003725 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003726 return cast<CXXMethodDecl>(Best->Function);
3727 assert(false &&
3728 "getAssignOperatorMethod - copy assignment operator method not found");
3729 return 0;
3730}
3731
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003732void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3733 CXXConstructorDecl *CopyConstructor,
3734 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003735 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003736 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003737 !CopyConstructor->isUsed()) &&
3738 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003740 CXXRecordDecl *ClassDecl
3741 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3742 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003743 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003744 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003745 // implicitly defined, all the implicitly-declared copy constructors
3746 // for its base class and its non-static data members shall have been
3747 // implicitly defined.
3748 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3749 Base != ClassDecl->bases_end(); ++Base) {
3750 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003751 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003752 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003753 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003754 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003755 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003756 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3757 FieldEnd = ClassDecl->field_end();
3758 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003759 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3760 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3761 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003762 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003763 CXXRecordDecl *FieldClassDecl
3764 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003765 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003766 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003767 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003768 }
3769 }
3770 CopyConstructor->setUsed();
3771}
3772
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003773Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003774Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003775 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003776 MultiExprArg ExprArgs,
3777 bool RequiresZeroInit) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003778 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003779
Douglas Gregor39da0b82009-09-09 23:08:42 +00003780 // C++ [class.copy]p15:
3781 // Whenever a temporary class object is copied using a copy constructor, and
3782 // this object and the copy have the same cv-unqualified type, an
3783 // implementation is permitted to treat the original and the copy as two
3784 // different ways of referring to the same object and not perform a copy at
3785 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003787 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003788 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003789 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003790 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3791 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3792 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003793 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3794 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003795 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3796 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003797 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3798 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3799 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003800
3801 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3802 Elidable = !CE->getCallReturnType()->isReferenceType();
3803 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003804 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003805 else if (isa<CXXConstructExpr>(E))
3806 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003807 }
Mike Stump1eb44332009-09-09 15:08:12 +00003808
3809 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003810 Elidable, move(ExprArgs), RequiresZeroInit);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003811}
3812
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003813/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3814/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003815Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003816Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3817 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003818 MultiExprArg ExprArgs,
3819 bool RequiresZeroInit) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003820 unsigned NumExprs = ExprArgs.size();
3821 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Douglas Gregor7edfb692009-11-23 12:27:39 +00003823 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003824 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003825 Constructor, Elidable, Exprs, NumExprs,
3826 RequiresZeroInit));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003827}
3828
Anders Carlssone7624a72009-08-27 05:08:22 +00003829Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003830Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3831 QualType Ty,
3832 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003833 MultiExprArg Args,
3834 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003835 unsigned NumExprs = Args.size();
3836 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Douglas Gregor7edfb692009-11-23 12:27:39 +00003838 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003839 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3840 TyBeginLoc, Exprs,
3841 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003842}
3843
3844
Mike Stump1eb44332009-09-09 15:08:12 +00003845bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003846 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003847 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003848 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003849 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003850 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003851 if (TempResult.isInvalid())
3852 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003854 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003855 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003856 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor78d15832009-05-26 18:54:04 +00003857 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Anders Carlssonfe2de492009-08-25 05:18:00 +00003859 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003860}
3861
Mike Stump1eb44332009-09-09 15:08:12 +00003862void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003863 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003864 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003865 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003866 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003867 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003868 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003869}
3870
Mike Stump1eb44332009-09-09 15:08:12 +00003871/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003872/// ActOnDeclarator, when a C++ direct initializer is present.
3873/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003874void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3875 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003876 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003877 SourceLocation *CommaLocs,
3878 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00003879 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003880 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003881
3882 // If there is no declaration, there was an error parsing it. Just ignore
3883 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003884 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003885 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003887 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3888 if (!VDecl) {
3889 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3890 RealDecl->setInvalidDecl();
3891 return;
3892 }
3893
Douglas Gregor83ddad32009-08-26 21:14:46 +00003894 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003895 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003896 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3897 //
3898 // Clients that want to distinguish between the two forms, can check for
3899 // direct initializer using VarDecl::hasCXXDirectInitializer().
3900 // A major benefit is that clients that don't particularly care about which
3901 // exactly form was it (like the CodeGen) can handle both cases without
3902 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003903
Douglas Gregor83ddad32009-08-26 21:14:46 +00003904 // If either the declaration has a dependent type or if any of the expressions
3905 // is type-dependent, we represent the initialization via a ParenListExpr for
3906 // later use during template instantiation.
3907 if (VDecl->getType()->isDependentType() ||
3908 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3909 // Let clients know that initialization was done with a direct initializer.
3910 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Douglas Gregor83ddad32009-08-26 21:14:46 +00003912 // Store the initialization expressions as a ParenListExpr.
3913 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003914 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003915 new (Context) ParenListExpr(Context, LParenLoc,
3916 (Expr **)Exprs.release(),
3917 NumExprs, RParenLoc));
3918 return;
3919 }
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Douglas Gregor83ddad32009-08-26 21:14:46 +00003921
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003922 // C++ 8.5p11:
3923 // The form of initialization (using parentheses or '=') is generally
3924 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003925 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003926 QualType DeclInitType = VDecl->getType();
3927 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003928 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003929
Douglas Gregor615c5d42009-03-24 16:43:20 +00003930 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3931 diag::err_typecheck_decl_incomplete_type)) {
3932 VDecl->setInvalidDecl();
3933 return;
3934 }
3935
Douglas Gregor90f93822009-12-22 22:17:25 +00003936 // The variable can not have an abstract class type.
3937 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3938 diag::err_abstract_type_in_decl,
3939 AbstractVariableType))
3940 VDecl->setInvalidDecl();
3941
3942 const VarDecl *Def = 0;
3943 if (VDecl->getDefinition(Def)) {
3944 Diag(VDecl->getLocation(), diag::err_redefinition)
3945 << VDecl->getDeclName();
3946 Diag(Def->getLocation(), diag::note_previous_definition);
3947 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003948 return;
3949 }
Douglas Gregor90f93822009-12-22 22:17:25 +00003950
3951 // Capture the variable that is being initialized and the style of
3952 // initialization.
3953 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3954
3955 // FIXME: Poor source location information.
3956 InitializationKind Kind
3957 = InitializationKind::CreateDirect(VDecl->getLocation(),
3958 LParenLoc, RParenLoc);
3959
3960 InitializationSequence InitSeq(*this, Entity, Kind,
3961 (Expr**)Exprs.get(), Exprs.size());
3962 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
3963 if (Result.isInvalid()) {
3964 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003965 return;
3966 }
Douglas Gregor90f93822009-12-22 22:17:25 +00003967
3968 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
3969 VDecl->setInit(Context, Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003970 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003971
Douglas Gregor90f93822009-12-22 22:17:25 +00003972 if (VDecl->getType()->getAs<RecordType>())
3973 FinalizeVarWithDestructor(VDecl, DeclInitType);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003974}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003975
Douglas Gregor19aeac62009-11-14 03:27:21 +00003976/// \brief Add the applicable constructor candidates for an initialization
3977/// by constructor.
3978static void AddConstructorInitializationCandidates(Sema &SemaRef,
3979 QualType ClassType,
3980 Expr **Args,
3981 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00003982 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003983 OverloadCandidateSet &CandidateSet) {
3984 // C++ [dcl.init]p14:
3985 // If the initialization is direct-initialization, or if it is
3986 // copy-initialization where the cv-unqualified version of the
3987 // source type is the same class as, or a derived class of, the
3988 // class of the destination, constructors are considered. The
3989 // applicable constructors are enumerated (13.3.1.3), and the
3990 // best one is chosen through overload resolution (13.3). The
3991 // constructor so selected is called to initialize the object,
3992 // with the initializer expression(s) as its argument(s). If no
3993 // constructor applies, or the overload resolution is ambiguous,
3994 // the initialization is ill-formed.
3995 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3996 assert(ClassRec && "Can only initialize a class type here");
3997
3998 // FIXME: When we decide not to synthesize the implicitly-declared
3999 // constructors, we'll need to make them appear here.
4000
4001 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4002 DeclarationName ConstructorName
4003 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4004 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4005 DeclContext::lookup_const_iterator Con, ConEnd;
4006 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4007 Con != ConEnd; ++Con) {
4008 // Find the constructor (which may be a template).
4009 CXXConstructorDecl *Constructor = 0;
4010 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4011 if (ConstructorTmpl)
4012 Constructor
4013 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4014 else
4015 Constructor = cast<CXXConstructorDecl>(*Con);
4016
Douglas Gregor20093b42009-12-09 23:02:17 +00004017 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4018 (Kind.getKind() == InitializationKind::IK_Value) ||
4019 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004020 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004021 ((Kind.getKind() == InitializationKind::IK_Default) &&
4022 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004023 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004024 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4025 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004026 Args, NumArgs, CandidateSet);
4027 else
4028 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
4029 }
4030 }
4031}
4032
4033/// \brief Attempt to perform initialization by constructor
4034/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4035/// copy-initialization.
4036///
4037/// This routine determines whether initialization by constructor is possible,
4038/// but it does not emit any diagnostics in the case where the initialization
4039/// is ill-formed.
4040///
4041/// \param ClassType the type of the object being initialized, which must have
4042/// class type.
4043///
4044/// \param Args the arguments provided to initialize the object
4045///
4046/// \param NumArgs the number of arguments provided to initialize the object
4047///
4048/// \param Kind the type of initialization being performed
4049///
4050/// \returns the constructor used to initialize the object, if successful.
4051/// Otherwise, emits a diagnostic and returns NULL.
4052CXXConstructorDecl *
4053Sema::TryInitializationByConstructor(QualType ClassType,
4054 Expr **Args, unsigned NumArgs,
4055 SourceLocation Loc,
4056 InitializationKind Kind) {
4057 // Build the overload candidate set
4058 OverloadCandidateSet CandidateSet;
4059 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4060 CandidateSet);
4061
4062 // Determine whether we found a constructor we can use.
4063 OverloadCandidateSet::iterator Best;
4064 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4065 case OR_Success:
4066 case OR_Deleted:
4067 // We found a constructor. Return it.
4068 return cast<CXXConstructorDecl>(Best->Function);
4069
4070 case OR_No_Viable_Function:
4071 case OR_Ambiguous:
4072 // Overload resolution failed. Return nothing.
4073 return 0;
4074 }
4075
4076 // Silence GCC warning
4077 return 0;
4078}
4079
Douglas Gregor39da0b82009-09-09 23:08:42 +00004080/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4081/// may occur as part of direct-initialization or copy-initialization.
4082///
4083/// \param ClassType the type of the object being initialized, which must have
4084/// class type.
4085///
4086/// \param ArgsPtr the arguments provided to initialize the object
4087///
4088/// \param Loc the source location where the initialization occurs
4089///
4090/// \param Range the source range that covers the entire initialization
4091///
4092/// \param InitEntity the name of the entity being initialized, if known
4093///
4094/// \param Kind the type of initialization being performed
4095///
4096/// \param ConvertedArgs a vector that will be filled in with the
4097/// appropriately-converted arguments to the constructor (if initialization
4098/// succeeded).
4099///
4100/// \returns the constructor used to initialize the object, if successful.
4101/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004102CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004103Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004104 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004105 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004106 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004107 InitializationKind Kind,
4108 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004109
4110 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004111 Expr **Args = (Expr **)ArgsPtr.get();
4112 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004113 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004114 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4115 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004116
Douglas Gregor18fe5682008-11-03 20:45:27 +00004117 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004118 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004119 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004120 // We found a constructor. Break out so that we can convert the arguments
4121 // appropriately.
4122 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Douglas Gregor18fe5682008-11-03 20:45:27 +00004124 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004125 if (InitEntity)
4126 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004127 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004128 else
4129 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004130 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00004131 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004132 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Douglas Gregor18fe5682008-11-03 20:45:27 +00004134 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004135 if (InitEntity)
4136 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4137 else
4138 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004139 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4140 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004141
4142 case OR_Deleted:
4143 if (InitEntity)
4144 Diag(Loc, diag::err_ovl_deleted_init)
4145 << Best->Function->isDeleted()
4146 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004147 else {
4148 const CXXRecordDecl *RD =
4149 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004150 Diag(Loc, diag::err_ovl_deleted_init)
4151 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004152 << RD->getDeclName() << Range;
4153 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4155 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004156 }
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Douglas Gregor39da0b82009-09-09 23:08:42 +00004158 // Convert the arguments, fill in default arguments, etc.
4159 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4160 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4161 return 0;
4162
4163 return Constructor;
4164}
4165
4166/// \brief Given a constructor and the set of arguments provided for the
4167/// constructor, convert the arguments and add any required default arguments
4168/// to form a proper call to this constructor.
4169///
4170/// \returns true if an error occurred, false otherwise.
4171bool
4172Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4173 MultiExprArg ArgsPtr,
4174 SourceLocation Loc,
4175 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4176 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4177 unsigned NumArgs = ArgsPtr.size();
4178 Expr **Args = (Expr **)ArgsPtr.get();
4179
4180 const FunctionProtoType *Proto
4181 = Constructor->getType()->getAs<FunctionProtoType>();
4182 assert(Proto && "Constructor without a prototype?");
4183 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004184
4185 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004186 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004187 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004188 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004189 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004190
4191 VariadicCallType CallType =
4192 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4193 llvm::SmallVector<Expr *, 8> AllArgs;
4194 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4195 Proto, 0, Args, NumArgs, AllArgs,
4196 CallType);
4197 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4198 ConvertedArgs.push_back(AllArgs[i]);
4199 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004200}
4201
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004202/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4203/// determine whether they are reference-related,
4204/// reference-compatible, reference-compatible with added
4205/// qualification, or incompatible, for use in C++ initialization by
4206/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4207/// type, and the first type (T1) is the pointee type of the reference
4208/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004209Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004210Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004211 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004212 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004213 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004214 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004215 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004216
Douglas Gregor393896f2009-11-05 13:06:35 +00004217 QualType T1 = Context.getCanonicalType(OrigT1);
4218 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004219 Qualifiers T1Quals, T2Quals;
4220 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4221 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004222
4223 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004224 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004225 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004226 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004227 if (UnqualT1 == UnqualT2)
4228 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004229 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4230 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4231 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004232 DerivedToBase = true;
4233 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004234 return Ref_Incompatible;
4235
4236 // At this point, we know that T1 and T2 are reference-related (at
4237 // least).
4238
Chandler Carruth28e318c2009-12-29 07:16:59 +00004239 // If the type is an array type, promote the element qualifiers to the type
4240 // for comparison.
4241 if (isa<ArrayType>(T1) && T1Quals)
4242 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4243 if (isa<ArrayType>(T2) && T2Quals)
4244 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4245
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004246 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004247 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004248 // reference-related to T2 and cv1 is the same cv-qualification
4249 // as, or greater cv-qualification than, cv2. For purposes of
4250 // overload resolution, cases for which cv1 is greater
4251 // cv-qualification than cv2 are identified as
4252 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004253 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004254 return Ref_Compatible;
4255 else if (T1.isMoreQualifiedThan(T2))
4256 return Ref_Compatible_With_Added_Qualification;
4257 else
4258 return Ref_Related;
4259}
4260
4261/// CheckReferenceInit - Check the initialization of a reference
4262/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4263/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004264/// list), and DeclType is the type of the declaration. When ICS is
4265/// non-null, this routine will compute the implicit conversion
4266/// sequence according to C++ [over.ics.ref] and will not produce any
4267/// diagnostics; when ICS is null, it will emit diagnostics when any
4268/// errors are found. Either way, a return value of true indicates
4269/// that there was a failure, a return value of false indicates that
4270/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004271///
4272/// When @p SuppressUserConversions, user-defined conversions are
4273/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004274/// When @p AllowExplicit, we also permit explicit user-defined
4275/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004276/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004277/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4278/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004279bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004280Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004281 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004282 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004283 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004284 ImplicitConversionSequence *ICS,
4285 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004286 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4287
Ted Kremenek6217b802009-07-29 21:53:49 +00004288 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004289 QualType T2 = Init->getType();
4290
Douglas Gregor904eed32008-11-10 20:40:00 +00004291 // If the initializer is the address of an overloaded function, try
4292 // to resolve the overloaded function. If all goes well, T2 is the
4293 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004294 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004295 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004296 ICS != 0);
4297 if (Fn) {
4298 // Since we're performing this reference-initialization for
4299 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004300 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004301 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004302 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004303
Anders Carlsson96ad5332009-10-21 17:16:23 +00004304 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004305 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004306
4307 T2 = Fn->getType();
4308 }
4309 }
4310
Douglas Gregor15da57e2008-10-29 02:00:59 +00004311 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004312 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004313 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004314 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4315 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004316 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004317 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004318
4319 // Most paths end in a failed conversion.
4320 if (ICS)
4321 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004322
4323 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004324 // A reference to type "cv1 T1" is initialized by an expression
4325 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004326
4327 // -- If the initializer expression
4328
Sebastian Redla9845802009-03-29 15:27:50 +00004329 // Rvalue references cannot bind to lvalues (N2812).
4330 // There is absolutely no situation where they can. In particular, note that
4331 // this is ill-formed, even if B has a user-defined conversion to A&&:
4332 // B b;
4333 // A&& r = b;
4334 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4335 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004336 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004337 << Init->getSourceRange();
4338 return true;
4339 }
4340
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004341 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004342 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4343 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004344 //
4345 // Note that the bit-field check is skipped if we are just computing
4346 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004347 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004348 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004349 BindsDirectly = true;
4350
Douglas Gregor15da57e2008-10-29 02:00:59 +00004351 if (ICS) {
4352 // C++ [over.ics.ref]p1:
4353 // When a parameter of reference type binds directly (8.5.3)
4354 // to an argument expression, the implicit conversion sequence
4355 // is the identity conversion, unless the argument expression
4356 // has a type that is a derived class of the parameter type,
4357 // in which case the implicit conversion sequence is a
4358 // derived-to-base Conversion (13.3.3.1).
4359 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4360 ICS->Standard.First = ICK_Identity;
4361 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4362 ICS->Standard.Third = ICK_Identity;
4363 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4364 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004365 ICS->Standard.ReferenceBinding = true;
4366 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004367 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004368 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004369
4370 // Nothing more to do: the inaccessibility/ambiguity check for
4371 // derived-to-base conversions is suppressed when we're
4372 // computing the implicit conversion sequence (C++
4373 // [over.best.ics]p2).
4374 return false;
4375 } else {
4376 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004377 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4378 if (DerivedToBase)
4379 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004380 else if(CheckExceptionSpecCompatibility(Init, T1))
4381 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004382 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004383 }
4384 }
4385
4386 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004387 // implicitly converted to an lvalue of type "cv3 T3,"
4388 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004389 // 92) (this conversion is selected by enumerating the
4390 // applicable conversion functions (13.3.1.6) and choosing
4391 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004392 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004393 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004394 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004395 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004396
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004397 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00004398 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004399 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00004400 for (UnresolvedSet::iterator I = Conversions->begin(),
4401 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004402 NamedDecl *D = *I;
4403 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4404 if (isa<UsingShadowDecl>(D))
4405 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4406
Mike Stump1eb44332009-09-09 15:08:12 +00004407 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004408 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004409 CXXConversionDecl *Conv;
4410 if (ConvTemplate)
4411 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4412 else
John McCall701c89e2009-12-03 04:06:58 +00004413 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004414
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004415 // If the conversion function doesn't return a reference type,
4416 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004417 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004418 (AllowExplicit || !Conv->isExplicit())) {
4419 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00004420 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4421 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004422 else
John McCall701c89e2009-12-03 04:06:58 +00004423 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004424 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004425 }
4426
4427 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004428 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004429 case OR_Success:
4430 // This is a direct binding.
4431 BindsDirectly = true;
4432
4433 if (ICS) {
4434 // C++ [over.ics.ref]p1:
4435 //
4436 // [...] If the parameter binds directly to the result of
4437 // applying a conversion function to the argument
4438 // expression, the implicit conversion sequence is a
4439 // user-defined conversion sequence (13.3.3.1.2), with the
4440 // second standard conversion sequence either an identity
4441 // conversion or, if the conversion function returns an
4442 // entity of a type that is a derived class of the parameter
4443 // type, a derived-to-base Conversion.
4444 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4445 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4446 ICS->UserDefined.After = Best->FinalConversion;
4447 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004448 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004449 assert(ICS->UserDefined.After.ReferenceBinding &&
4450 ICS->UserDefined.After.DirectBinding &&
4451 "Expected a direct reference binding!");
4452 return false;
4453 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004454 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004455 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004456 CastExpr::CK_UserDefinedConversion,
4457 cast<CXXMethodDecl>(Best->Function),
4458 Owned(Init));
4459 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004460
4461 if (CheckExceptionSpecCompatibility(Init, T1))
4462 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004463 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4464 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004465 }
4466 break;
4467
4468 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004469 if (ICS) {
4470 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4471 Cand != CandidateSet.end(); ++Cand)
4472 if (Cand->Viable)
4473 ICS->ConversionFunctionSet.push_back(Cand->Function);
4474 break;
4475 }
4476 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4477 << Init->getSourceRange();
4478 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004479 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004481 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004482 case OR_Deleted:
4483 // There was no suitable conversion, or we found a deleted
4484 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004485 break;
4486 }
4487 }
Mike Stump1eb44332009-09-09 15:08:12 +00004488
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004489 if (BindsDirectly) {
4490 // C++ [dcl.init.ref]p4:
4491 // [...] In all cases where the reference-related or
4492 // reference-compatible relationship of two types is used to
4493 // establish the validity of a reference binding, and T1 is a
4494 // base class of T2, a program that necessitates such a binding
4495 // is ill-formed if T1 is an inaccessible (clause 11) or
4496 // ambiguous (10.2) base class of T2.
4497 //
4498 // Note that we only check this condition when we're allowed to
4499 // complain about errors, because we should not be checking for
4500 // ambiguity (or inaccessibility) unless the reference binding
4501 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004502 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004503 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004504 Init->getSourceRange(),
4505 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004506 else
4507 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004508 }
4509
4510 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004511 // type (i.e., cv1 shall be const), or the reference shall be an
4512 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004513 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004514 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004515 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004516 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004517 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004518 return true;
4519 }
4520
4521 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004522 // class type, and "cv1 T1" is reference-compatible with
4523 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004524 // following ways (the choice is implementation-defined):
4525 //
4526 // -- The reference is bound to the object represented by
4527 // the rvalue (see 3.10) or to a sub-object within that
4528 // object.
4529 //
Eli Friedman33a31382009-08-05 19:21:58 +00004530 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004531 // a constructor is called to copy the entire rvalue
4532 // object into the temporary. The reference is bound to
4533 // the temporary or to a sub-object within the
4534 // temporary.
4535 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004536 // The constructor that would be used to make the copy
4537 // shall be callable whether or not the copy is actually
4538 // done.
4539 //
Sebastian Redla9845802009-03-29 15:27:50 +00004540 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004541 // freedom, so we will always take the first option and never build
4542 // a temporary in this case. FIXME: We will, however, have to check
4543 // for the presence of a copy constructor in C++98/03 mode.
4544 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004545 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4546 if (ICS) {
4547 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4548 ICS->Standard.First = ICK_Identity;
4549 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4550 ICS->Standard.Third = ICK_Identity;
4551 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4552 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004553 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004554 ICS->Standard.DirectBinding = false;
4555 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004556 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004557 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004558 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4559 if (DerivedToBase)
4560 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004561 else if(CheckExceptionSpecCompatibility(Init, T1))
4562 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004563 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004564 }
4565 return false;
4566 }
4567
Eli Friedman33a31382009-08-05 19:21:58 +00004568 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004569 // initialized from the initializer expression using the
4570 // rules for a non-reference copy initialization (8.5). The
4571 // reference is then bound to the temporary. If T1 is
4572 // reference-related to T2, cv1 must be the same
4573 // cv-qualification as, or greater cv-qualification than,
4574 // cv2; otherwise, the program is ill-formed.
4575 if (RefRelationship == Ref_Related) {
4576 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4577 // we would be reference-compatible or reference-compatible with
4578 // added qualification. But that wasn't the case, so the reference
4579 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004580 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004581 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004582 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004583 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004584 return true;
4585 }
4586
Douglas Gregor734d9862009-01-30 23:27:23 +00004587 // If at least one of the types is a class type, the types are not
4588 // related, and we aren't allowed any user conversions, the
4589 // reference binding fails. This case is important for breaking
4590 // recursion, since TryImplicitConversion below will attempt to
4591 // create a temporary through the use of a copy constructor.
4592 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4593 (T1->isRecordType() || T2->isRecordType())) {
4594 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004595 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004596 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004597 return true;
4598 }
4599
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004600 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004601 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004602 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004603 //
Sebastian Redla9845802009-03-29 15:27:50 +00004604 // When a parameter of reference type is not bound directly to
4605 // an argument expression, the conversion sequence is the one
4606 // required to convert the argument expression to the
4607 // underlying type of the reference according to
4608 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4609 // to copy-initializing a temporary of the underlying type with
4610 // the argument expression. Any difference in top-level
4611 // cv-qualification is subsumed by the initialization itself
4612 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004613 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4614 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004615 /*ForceRValue=*/false,
4616 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Sebastian Redla9845802009-03-29 15:27:50 +00004618 // Of course, that's still a reference binding.
4619 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4620 ICS->Standard.ReferenceBinding = true;
4621 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004622 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004623 ImplicitConversionSequence::UserDefinedConversion) {
4624 ICS->UserDefined.After.ReferenceBinding = true;
4625 ICS->UserDefined.After.RRefBinding = isRValRef;
4626 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004627 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4628 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004629 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004630 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004631 false, false,
4632 Conversions);
4633 if (badConversion) {
4634 if ((Conversions.ConversionKind ==
4635 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004636 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004637 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004638 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4639 for (int j = Conversions.ConversionFunctionSet.size()-1;
4640 j >= 0; j--) {
4641 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4642 Diag(Func->getLocation(), diag::err_ovl_candidate);
4643 }
4644 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004645 else {
4646 if (isRValRef)
4647 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4648 << Init->getSourceRange();
4649 else
4650 Diag(DeclLoc, diag::err_invalid_initialization)
4651 << DeclType << Init->getType() << Init->getSourceRange();
4652 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004653 }
4654 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004655 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004656}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004657
Anders Carlsson20d45d22009-12-12 00:32:00 +00004658static inline bool
4659CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4660 const FunctionDecl *FnDecl) {
4661 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4662 if (isa<NamespaceDecl>(DC)) {
4663 return SemaRef.Diag(FnDecl->getLocation(),
4664 diag::err_operator_new_delete_declared_in_namespace)
4665 << FnDecl->getDeclName();
4666 }
4667
4668 if (isa<TranslationUnitDecl>(DC) &&
4669 FnDecl->getStorageClass() == FunctionDecl::Static) {
4670 return SemaRef.Diag(FnDecl->getLocation(),
4671 diag::err_operator_new_delete_declared_static)
4672 << FnDecl->getDeclName();
4673 }
4674
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004675 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004676}
4677
Anders Carlsson156c78e2009-12-13 17:53:43 +00004678static inline bool
4679CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4680 CanQualType ExpectedResultType,
4681 CanQualType ExpectedFirstParamType,
4682 unsigned DependentParamTypeDiag,
4683 unsigned InvalidParamTypeDiag) {
4684 QualType ResultType =
4685 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4686
4687 // Check that the result type is not dependent.
4688 if (ResultType->isDependentType())
4689 return SemaRef.Diag(FnDecl->getLocation(),
4690 diag::err_operator_new_delete_dependent_result_type)
4691 << FnDecl->getDeclName() << ExpectedResultType;
4692
4693 // Check that the result type is what we expect.
4694 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4695 return SemaRef.Diag(FnDecl->getLocation(),
4696 diag::err_operator_new_delete_invalid_result_type)
4697 << FnDecl->getDeclName() << ExpectedResultType;
4698
4699 // A function template must have at least 2 parameters.
4700 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4701 return SemaRef.Diag(FnDecl->getLocation(),
4702 diag::err_operator_new_delete_template_too_few_parameters)
4703 << FnDecl->getDeclName();
4704
4705 // The function decl must have at least 1 parameter.
4706 if (FnDecl->getNumParams() == 0)
4707 return SemaRef.Diag(FnDecl->getLocation(),
4708 diag::err_operator_new_delete_too_few_parameters)
4709 << FnDecl->getDeclName();
4710
4711 // Check the the first parameter type is not dependent.
4712 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4713 if (FirstParamType->isDependentType())
4714 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4715 << FnDecl->getDeclName() << ExpectedFirstParamType;
4716
4717 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004718 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004719 ExpectedFirstParamType)
4720 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4721 << FnDecl->getDeclName() << ExpectedFirstParamType;
4722
4723 return false;
4724}
4725
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004726static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004727CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004728 // C++ [basic.stc.dynamic.allocation]p1:
4729 // A program is ill-formed if an allocation function is declared in a
4730 // namespace scope other than global scope or declared static in global
4731 // scope.
4732 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4733 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004734
4735 CanQualType SizeTy =
4736 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4737
4738 // C++ [basic.stc.dynamic.allocation]p1:
4739 // The return type shall be void*. The first parameter shall have type
4740 // std::size_t.
4741 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4742 SizeTy,
4743 diag::err_operator_new_dependent_param_type,
4744 diag::err_operator_new_param_type))
4745 return true;
4746
4747 // C++ [basic.stc.dynamic.allocation]p1:
4748 // The first parameter shall not have an associated default argument.
4749 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004750 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004751 diag::err_operator_new_default_arg)
4752 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4753
4754 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004755}
4756
4757static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004758CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4759 // C++ [basic.stc.dynamic.deallocation]p1:
4760 // A program is ill-formed if deallocation functions are declared in a
4761 // namespace scope other than global scope or declared static in global
4762 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004763 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4764 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004765
4766 // C++ [basic.stc.dynamic.deallocation]p2:
4767 // Each deallocation function shall return void and its first parameter
4768 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004769 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4770 SemaRef.Context.VoidPtrTy,
4771 diag::err_operator_delete_dependent_param_type,
4772 diag::err_operator_delete_param_type))
4773 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004774
Anders Carlsson46991d62009-12-12 00:16:02 +00004775 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4776 if (FirstParamType->isDependentType())
4777 return SemaRef.Diag(FnDecl->getLocation(),
4778 diag::err_operator_delete_dependent_param_type)
4779 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4780
4781 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4782 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004783 return SemaRef.Diag(FnDecl->getLocation(),
4784 diag::err_operator_delete_param_type)
4785 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004786
4787 return false;
4788}
4789
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004790/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4791/// of this overloaded operator is well-formed. If so, returns false;
4792/// otherwise, emits appropriate diagnostics and returns true.
4793bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004794 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004795 "Expected an overloaded operator declaration");
4796
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004797 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4798
Mike Stump1eb44332009-09-09 15:08:12 +00004799 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004800 // The allocation and deallocation functions, operator new,
4801 // operator new[], operator delete and operator delete[], are
4802 // described completely in 3.7.3. The attributes and restrictions
4803 // found in the rest of this subclause do not apply to them unless
4804 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004805 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004806 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004807
Anders Carlssona3ccda52009-12-12 00:26:23 +00004808 if (Op == OO_New || Op == OO_Array_New)
4809 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004810
4811 // C++ [over.oper]p6:
4812 // An operator function shall either be a non-static member
4813 // function or be a non-member function and have at least one
4814 // parameter whose type is a class, a reference to a class, an
4815 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004816 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4817 if (MethodDecl->isStatic())
4818 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004819 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004820 } else {
4821 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004822 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4823 ParamEnd = FnDecl->param_end();
4824 Param != ParamEnd; ++Param) {
4825 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004826 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4827 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004828 ClassOrEnumParam = true;
4829 break;
4830 }
4831 }
4832
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004833 if (!ClassOrEnumParam)
4834 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004835 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004836 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004837 }
4838
4839 // C++ [over.oper]p8:
4840 // An operator function cannot have default arguments (8.3.6),
4841 // except where explicitly stated below.
4842 //
Mike Stump1eb44332009-09-09 15:08:12 +00004843 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004844 // (C++ [over.call]p1).
4845 if (Op != OO_Call) {
4846 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4847 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004848 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004849 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004850 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004851 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004852 }
4853 }
4854
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004855 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4856 { false, false, false }
4857#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4858 , { Unary, Binary, MemberOnly }
4859#include "clang/Basic/OperatorKinds.def"
4860 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004861
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004862 bool CanBeUnaryOperator = OperatorUses[Op][0];
4863 bool CanBeBinaryOperator = OperatorUses[Op][1];
4864 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004865
4866 // C++ [over.oper]p8:
4867 // [...] Operator functions cannot have more or fewer parameters
4868 // than the number required for the corresponding operator, as
4869 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004870 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004871 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004872 if (Op != OO_Call &&
4873 ((NumParams == 1 && !CanBeUnaryOperator) ||
4874 (NumParams == 2 && !CanBeBinaryOperator) ||
4875 (NumParams < 1) || (NumParams > 2))) {
4876 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004877 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004878 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004879 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004880 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004881 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004882 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004883 assert(CanBeBinaryOperator &&
4884 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004885 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004886 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004887
Chris Lattner416e46f2008-11-21 07:57:12 +00004888 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004889 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004890 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004891
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004892 // Overloaded operators other than operator() cannot be variadic.
4893 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004894 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004895 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004896 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004897 }
4898
4899 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004900 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4901 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004902 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004903 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004904 }
4905
4906 // C++ [over.inc]p1:
4907 // The user-defined function called operator++ implements the
4908 // prefix and postfix ++ operator. If this function is a member
4909 // function with no parameters, or a non-member function with one
4910 // parameter of class or enumeration type, it defines the prefix
4911 // increment operator ++ for objects of that type. If the function
4912 // is a member function with one parameter (which shall be of type
4913 // int) or a non-member function with two parameters (the second
4914 // of which shall be of type int), it defines the postfix
4915 // increment operator ++ for objects of that type.
4916 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4917 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4918 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004919 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004920 ParamIsInt = BT->getKind() == BuiltinType::Int;
4921
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004922 if (!ParamIsInt)
4923 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004924 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004925 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004926 }
4927
Sebastian Redl64b45f72009-01-05 20:52:13 +00004928 // Notify the class if it got an assignment operator.
4929 if (Op == OO_Equal) {
4930 // Would have returned earlier otherwise.
4931 assert(isa<CXXMethodDecl>(FnDecl) &&
4932 "Overloaded = not member, but not filtered.");
4933 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4934 Method->getParent()->addedAssignmentOperator(Context, Method);
4935 }
4936
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004937 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004938}
Chris Lattner5a003a42008-12-17 07:09:26 +00004939
Douglas Gregor074149e2009-01-05 19:45:36 +00004940/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4941/// linkage specification, including the language and (if present)
4942/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4943/// the location of the language string literal, which is provided
4944/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4945/// the '{' brace. Otherwise, this linkage specification does not
4946/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004947Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4948 SourceLocation ExternLoc,
4949 SourceLocation LangLoc,
4950 const char *Lang,
4951 unsigned StrSize,
4952 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004953 LinkageSpecDecl::LanguageIDs Language;
4954 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4955 Language = LinkageSpecDecl::lang_c;
4956 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4957 Language = LinkageSpecDecl::lang_cxx;
4958 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004959 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004960 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004961 }
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Chris Lattnercc98eac2008-12-17 07:13:27 +00004963 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Douglas Gregor074149e2009-01-05 19:45:36 +00004965 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004966 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004967 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004968 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004969 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004970 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004971}
4972
Douglas Gregor074149e2009-01-05 19:45:36 +00004973/// ActOnFinishLinkageSpecification - Completely the definition of
4974/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4975/// valid, it's the position of the closing '}' brace in a linkage
4976/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004977Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4978 DeclPtrTy LinkageSpec,
4979 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004980 if (LinkageSpec)
4981 PopDeclContext();
4982 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004983}
4984
Douglas Gregord308e622009-05-18 20:51:54 +00004985/// \brief Perform semantic analysis for the variable declaration that
4986/// occurs within a C++ catch clause, returning the newly-created
4987/// variable.
4988VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004989 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004990 IdentifierInfo *Name,
4991 SourceLocation Loc,
4992 SourceRange Range) {
4993 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004994
4995 // Arrays and functions decay.
4996 if (ExDeclType->isArrayType())
4997 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4998 else if (ExDeclType->isFunctionType())
4999 ExDeclType = Context.getPointerType(ExDeclType);
5000
5001 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5002 // The exception-declaration shall not denote a pointer or reference to an
5003 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005004 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005005 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005006 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005007 Invalid = true;
5008 }
Douglas Gregord308e622009-05-18 20:51:54 +00005009
Sebastian Redl4b07b292008-12-22 19:15:10 +00005010 QualType BaseType = ExDeclType;
5011 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005012 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005013 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005014 BaseType = Ptr->getPointeeType();
5015 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005016 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005017 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005018 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005019 BaseType = Ref->getPointeeType();
5020 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005021 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005022 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005023 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005024 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005025 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005026
Mike Stump1eb44332009-09-09 15:08:12 +00005027 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005028 RequireNonAbstractType(Loc, ExDeclType,
5029 diag::err_abstract_type_in_decl,
5030 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005031 Invalid = true;
5032
Douglas Gregord308e622009-05-18 20:51:54 +00005033 // FIXME: Need to test for ability to copy-construct and destroy the
5034 // exception variable.
5035
Sebastian Redl8351da02008-12-22 21:35:02 +00005036 // FIXME: Need to check for abstract classes.
5037
Mike Stump1eb44332009-09-09 15:08:12 +00005038 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005039 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005040
5041 if (Invalid)
5042 ExDecl->setInvalidDecl();
5043
5044 return ExDecl;
5045}
5046
5047/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5048/// handler.
5049Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005050 TypeSourceInfo *TInfo = 0;
5051 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005052
5053 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005054 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005055 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005056 // The scope should be freshly made just for us. There is just no way
5057 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005058 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005059 if (PrevDecl->isTemplateParameter()) {
5060 // Maybe we will complain about the shadowed template parameter.
5061 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005062 }
5063 }
5064
Chris Lattnereaaebc72009-04-25 08:06:05 +00005065 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005066 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5067 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005068 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005069 }
5070
John McCalla93c9342009-12-07 02:54:59 +00005071 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005072 D.getIdentifier(),
5073 D.getIdentifierLoc(),
5074 D.getDeclSpec().getSourceRange());
5075
Chris Lattnereaaebc72009-04-25 08:06:05 +00005076 if (Invalid)
5077 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005078
Sebastian Redl4b07b292008-12-22 19:15:10 +00005079 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005080 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005081 PushOnScopeChains(ExDecl, S);
5082 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005083 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005084
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005085 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005086 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005087}
Anders Carlssonfb311762009-03-14 00:25:26 +00005088
Mike Stump1eb44332009-09-09 15:08:12 +00005089Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005090 ExprArg assertexpr,
5091 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005092 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005093 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005094 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5095
Anders Carlssonc3082412009-03-14 00:33:21 +00005096 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5097 llvm::APSInt Value(32);
5098 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5099 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5100 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005101 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005102 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005103
Anders Carlssonc3082412009-03-14 00:33:21 +00005104 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005105 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005106 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005107 }
5108 }
Mike Stump1eb44332009-09-09 15:08:12 +00005109
Anders Carlsson77d81422009-03-15 17:35:16 +00005110 assertexpr.release();
5111 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005112 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005113 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005114
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005115 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005116 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005117}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005118
John McCalldd4a3b02009-09-16 22:47:08 +00005119/// Handle a friend type declaration. This works in tandem with
5120/// ActOnTag.
5121///
5122/// Notes on friend class templates:
5123///
5124/// We generally treat friend class declarations as if they were
5125/// declaring a class. So, for example, the elaborated type specifier
5126/// in a friend declaration is required to obey the restrictions of a
5127/// class-head (i.e. no typedefs in the scope chain), template
5128/// parameters are required to match up with simple template-ids, &c.
5129/// However, unlike when declaring a template specialization, it's
5130/// okay to refer to a template specialization without an empty
5131/// template parameter declaration, e.g.
5132/// friend class A<T>::B<unsigned>;
5133/// We permit this as a special case; if there are any template
5134/// parameters present at all, require proper matching, i.e.
5135/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005136Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005137 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005138 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005139
5140 assert(DS.isFriendSpecified());
5141 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5142
John McCalldd4a3b02009-09-16 22:47:08 +00005143 // Try to convert the decl specifier to a type. This works for
5144 // friend templates because ActOnTag never produces a ClassTemplateDecl
5145 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005146 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005147 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5148 if (TheDeclarator.isInvalidType())
5149 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005150
John McCalldd4a3b02009-09-16 22:47:08 +00005151 // This is definitely an error in C++98. It's probably meant to
5152 // be forbidden in C++0x, too, but the specification is just
5153 // poorly written.
5154 //
5155 // The problem is with declarations like the following:
5156 // template <T> friend A<T>::foo;
5157 // where deciding whether a class C is a friend or not now hinges
5158 // on whether there exists an instantiation of A that causes
5159 // 'foo' to equal C. There are restrictions on class-heads
5160 // (which we declare (by fiat) elaborated friend declarations to
5161 // be) that makes this tractable.
5162 //
5163 // FIXME: handle "template <> friend class A<T>;", which
5164 // is possibly well-formed? Who even knows?
5165 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5166 Diag(Loc, diag::err_tagless_friend_type_template)
5167 << DS.getSourceRange();
5168 return DeclPtrTy();
5169 }
5170
John McCall02cace72009-08-28 07:59:38 +00005171 // C++ [class.friend]p2:
5172 // An elaborated-type-specifier shall be used in a friend declaration
5173 // for a class.*
5174 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005175 // This is one of the rare places in Clang where it's legitimate to
5176 // ask about the "spelling" of the type.
5177 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5178 // If we evaluated the type to a record type, suggest putting
5179 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005180 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005181 RecordDecl *RD = RT->getDecl();
5182
5183 std::string InsertionText = std::string(" ") + RD->getKindName();
5184
John McCalle3af0232009-10-07 23:34:25 +00005185 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5186 << (unsigned) RD->getTagKind()
5187 << T
5188 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005189 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5190 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005191 return DeclPtrTy();
5192 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005193 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5194 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005195 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005196 }
5197 }
5198
John McCalle3af0232009-10-07 23:34:25 +00005199 // Enum types cannot be friends.
5200 if (T->getAs<EnumType>()) {
5201 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5202 << SourceRange(DS.getFriendSpecLoc());
5203 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005204 }
John McCall02cace72009-08-28 07:59:38 +00005205
John McCall02cace72009-08-28 07:59:38 +00005206 // C++98 [class.friend]p1: A friend of a class is a function
5207 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005208 // This is fixed in DR77, which just barely didn't make the C++03
5209 // deadline. It's also a very silly restriction that seriously
5210 // affects inner classes and which nobody else seems to implement;
5211 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005212
John McCalldd4a3b02009-09-16 22:47:08 +00005213 Decl *D;
5214 if (TempParams.size())
5215 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5216 TempParams.size(),
5217 (TemplateParameterList**) TempParams.release(),
5218 T.getTypePtr(),
5219 DS.getFriendSpecLoc());
5220 else
5221 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5222 DS.getFriendSpecLoc());
5223 D->setAccess(AS_public);
5224 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005225
John McCalldd4a3b02009-09-16 22:47:08 +00005226 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005227}
5228
John McCallbbbcdd92009-09-11 21:02:39 +00005229Sema::DeclPtrTy
5230Sema::ActOnFriendFunctionDecl(Scope *S,
5231 Declarator &D,
5232 bool IsDefinition,
5233 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005234 const DeclSpec &DS = D.getDeclSpec();
5235
5236 assert(DS.isFriendSpecified());
5237 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5238
5239 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005240 TypeSourceInfo *TInfo = 0;
5241 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005242
5243 // C++ [class.friend]p1
5244 // A friend of a class is a function or class....
5245 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005246 // It *doesn't* see through dependent types, which is correct
5247 // according to [temp.arg.type]p3:
5248 // If a declaration acquires a function type through a
5249 // type dependent on a template-parameter and this causes
5250 // a declaration that does not use the syntactic form of a
5251 // function declarator to have a function type, the program
5252 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005253 if (!T->isFunctionType()) {
5254 Diag(Loc, diag::err_unexpected_friend);
5255
5256 // It might be worthwhile to try to recover by creating an
5257 // appropriate declaration.
5258 return DeclPtrTy();
5259 }
5260
5261 // C++ [namespace.memdef]p3
5262 // - If a friend declaration in a non-local class first declares a
5263 // class or function, the friend class or function is a member
5264 // of the innermost enclosing namespace.
5265 // - The name of the friend is not found by simple name lookup
5266 // until a matching declaration is provided in that namespace
5267 // scope (either before or after the class declaration granting
5268 // friendship).
5269 // - If a friend function is called, its name may be found by the
5270 // name lookup that considers functions from namespaces and
5271 // classes associated with the types of the function arguments.
5272 // - When looking for a prior declaration of a class or a function
5273 // declared as a friend, scopes outside the innermost enclosing
5274 // namespace scope are not considered.
5275
John McCall02cace72009-08-28 07:59:38 +00005276 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5277 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005278 assert(Name);
5279
John McCall67d1a672009-08-06 02:15:43 +00005280 // The context we found the declaration in, or in which we should
5281 // create the declaration.
5282 DeclContext *DC;
5283
5284 // FIXME: handle local classes
5285
5286 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005287 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5288 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005289 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005290 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005291 DC = computeDeclContext(ScopeQual);
5292
5293 // FIXME: handle dependent contexts
5294 if (!DC) return DeclPtrTy();
5295
John McCall68263142009-11-18 22:49:29 +00005296 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005297
5298 // If searching in that context implicitly found a declaration in
5299 // a different context, treat it like it wasn't found at all.
5300 // TODO: better diagnostics for this case. Suggesting the right
5301 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005302 // FIXME: getRepresentativeDecl() is not right here at all
5303 if (Previous.empty() ||
5304 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005305 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005306 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5307 return DeclPtrTy();
5308 }
5309
5310 // C++ [class.friend]p1: A friend of a class is a function or
5311 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005312 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005313 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5314
John McCall67d1a672009-08-06 02:15:43 +00005315 // Otherwise walk out to the nearest namespace scope looking for matches.
5316 } else {
5317 // TODO: handle local class contexts.
5318
5319 DC = CurContext;
5320 while (true) {
5321 // Skip class contexts. If someone can cite chapter and verse
5322 // for this behavior, that would be nice --- it's what GCC and
5323 // EDG do, and it seems like a reasonable intent, but the spec
5324 // really only says that checks for unqualified existing
5325 // declarations should stop at the nearest enclosing namespace,
5326 // not that they should only consider the nearest enclosing
5327 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005328 while (DC->isRecord())
5329 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005330
John McCall68263142009-11-18 22:49:29 +00005331 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005332
5333 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005334 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005335 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005336
John McCall67d1a672009-08-06 02:15:43 +00005337 if (DC->isFileContext()) break;
5338 DC = DC->getParent();
5339 }
5340
5341 // C++ [class.friend]p1: A friend of a class is a function or
5342 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005343 // C++0x changes this for both friend types and functions.
5344 // Most C++ 98 compilers do seem to give an error here, so
5345 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005346 if (!Previous.empty() && DC->Equals(CurContext)
5347 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005348 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5349 }
5350
Douglas Gregor182ddf02009-09-28 00:08:27 +00005351 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005352 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005353 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5354 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5355 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005356 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005357 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5358 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005359 return DeclPtrTy();
5360 }
John McCall67d1a672009-08-06 02:15:43 +00005361 }
5362
Douglas Gregor182ddf02009-09-28 00:08:27 +00005363 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005364 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005365 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005366 IsDefinition,
5367 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005368 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005369
Douglas Gregor182ddf02009-09-28 00:08:27 +00005370 assert(ND->getDeclContext() == DC);
5371 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005372
John McCallab88d972009-08-31 22:39:49 +00005373 // Add the function declaration to the appropriate lookup tables,
5374 // adjusting the redeclarations list as necessary. We don't
5375 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005376 //
John McCallab88d972009-08-31 22:39:49 +00005377 // Also update the scope-based lookup if the target context's
5378 // lookup context is in lexical scope.
5379 if (!CurContext->isDependentContext()) {
5380 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005381 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005382 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005383 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005384 }
John McCall02cace72009-08-28 07:59:38 +00005385
5386 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005387 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005388 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005389 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005390 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005391
Douglas Gregor7557a132009-12-24 20:56:24 +00005392 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5393 FrD->setSpecialization(true);
5394
Douglas Gregor182ddf02009-09-28 00:08:27 +00005395 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005396}
5397
Chris Lattnerb28317a2009-03-28 19:18:32 +00005398void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005399 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005400
Chris Lattnerb28317a2009-03-28 19:18:32 +00005401 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005402 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5403 if (!Fn) {
5404 Diag(DelLoc, diag::err_deleted_non_function);
5405 return;
5406 }
5407 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5408 Diag(DelLoc, diag::err_deleted_decl_not_first);
5409 Diag(Prev->getLocation(), diag::note_previous_declaration);
5410 // If the declaration wasn't the first, we delete the function anyway for
5411 // recovery.
5412 }
5413 Fn->setDeleted();
5414}
Sebastian Redl13e88542009-04-27 21:33:24 +00005415
5416static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5417 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5418 ++CI) {
5419 Stmt *SubStmt = *CI;
5420 if (!SubStmt)
5421 continue;
5422 if (isa<ReturnStmt>(SubStmt))
5423 Self.Diag(SubStmt->getSourceRange().getBegin(),
5424 diag::err_return_in_constructor_handler);
5425 if (!isa<Expr>(SubStmt))
5426 SearchForReturnInStmt(Self, SubStmt);
5427 }
5428}
5429
5430void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5431 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5432 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5433 SearchForReturnInStmt(*this, Handler);
5434 }
5435}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005436
Mike Stump1eb44332009-09-09 15:08:12 +00005437bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005438 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005439 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5440 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005441
5442 QualType CNewTy = Context.getCanonicalType(NewTy);
5443 QualType COldTy = Context.getCanonicalType(OldTy);
5444
Mike Stump1eb44332009-09-09 15:08:12 +00005445 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00005446 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005447 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005449 // Check if the return types are covariant
5450 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005451
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005452 /// Both types must be pointers or references to classes.
5453 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5454 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5455 NewClassTy = NewPT->getPointeeType();
5456 OldClassTy = OldPT->getPointeeType();
5457 }
5458 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5459 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5460 NewClassTy = NewRT->getPointeeType();
5461 OldClassTy = OldRT->getPointeeType();
5462 }
5463 }
Mike Stump1eb44332009-09-09 15:08:12 +00005464
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005465 // The return types aren't either both pointers or references to a class type.
5466 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005467 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005468 diag::err_different_return_type_for_overriding_virtual_function)
5469 << New->getDeclName() << NewTy << OldTy;
5470 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005471
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005472 return true;
5473 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005474
Douglas Gregora4923eb2009-11-16 21:35:15 +00005475 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005476 // Check if the new class derives from the old class.
5477 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5478 Diag(New->getLocation(),
5479 diag::err_covariant_return_not_derived)
5480 << New->getDeclName() << NewTy << OldTy;
5481 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5482 return true;
5483 }
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005485 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005486 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005487 diag::err_covariant_return_inaccessible_base,
5488 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5489 // FIXME: Should this point to the return type?
5490 New->getLocation(), SourceRange(), New->getDeclName())) {
5491 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5492 return true;
5493 }
5494 }
Mike Stump1eb44332009-09-09 15:08:12 +00005495
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005496 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005497 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005498 Diag(New->getLocation(),
5499 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005500 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005501 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5502 return true;
5503 };
Mike Stump1eb44332009-09-09 15:08:12 +00005504
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005505
5506 // The new class type must have the same or less qualifiers as the old type.
5507 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5508 Diag(New->getLocation(),
5509 diag::err_covariant_return_type_class_type_more_qualified)
5510 << New->getDeclName() << NewTy << OldTy;
5511 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5512 return true;
5513 };
Mike Stump1eb44332009-09-09 15:08:12 +00005514
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005515 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005516}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005517
Sean Huntbbd37c62009-11-21 08:43:09 +00005518bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5519 const CXXMethodDecl *Old)
5520{
5521 if (Old->hasAttr<FinalAttr>()) {
5522 Diag(New->getLocation(), diag::err_final_function_overridden)
5523 << New->getDeclName();
5524 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5525 return true;
5526 }
5527
5528 return false;
5529}
5530
Douglas Gregor4ba31362009-12-01 17:24:26 +00005531/// \brief Mark the given method pure.
5532///
5533/// \param Method the method to be marked pure.
5534///
5535/// \param InitRange the source range that covers the "0" initializer.
5536bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5537 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5538 Method->setPure();
5539
5540 // A class is abstract if at least one function is pure virtual.
5541 Method->getParent()->setAbstract(true);
5542 return false;
5543 }
5544
5545 if (!Method->isInvalidDecl())
5546 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5547 << Method->getDeclName() << InitRange;
5548 return true;
5549}
5550
John McCall731ad842009-12-19 09:28:58 +00005551/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5552/// an initializer for the out-of-line declaration 'Dcl'. The scope
5553/// is a fresh scope pushed for just this purpose.
5554///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005555/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5556/// static data member of class X, names should be looked up in the scope of
5557/// class X.
5558void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005559 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005560 Decl *D = Dcl.getAs<Decl>();
5561 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005562
John McCall731ad842009-12-19 09:28:58 +00005563 // We should only get called for declarations with scope specifiers, like:
5564 // int foo::bar;
5565 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005566 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005567}
5568
5569/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005570/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005571void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005572 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005573 Decl *D = Dcl.getAs<Decl>();
5574 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005575
John McCall731ad842009-12-19 09:28:58 +00005576 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005577 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005578}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005579
5580/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5581/// C++ if/switch/while/for statement.
5582/// e.g: "if (int x = f()) {...}"
5583Action::DeclResult
5584Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5585 // C++ 6.4p2:
5586 // The declarator shall not specify a function or an array.
5587 // The type-specifier-seq shall not contain typedef and shall not declare a
5588 // new class or enumeration.
5589 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5590 "Parser allowed 'typedef' as storage class of condition decl.");
5591
John McCalla93c9342009-12-07 02:54:59 +00005592 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005593 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005594 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005595
5596 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5597 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5598 // would be created and CXXConditionDeclExpr wants a VarDecl.
5599 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5600 << D.getSourceRange();
5601 return DeclResult();
5602 } else if (OwnedTag && OwnedTag->isDefinition()) {
5603 // The type-specifier-seq shall not declare a new class or enumeration.
5604 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5605 }
5606
5607 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5608 if (!Dcl)
5609 return DeclResult();
5610
5611 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5612 VD->setDeclaredInCondition(true);
5613 return Dcl;
5614}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005615
Anders Carlssond6a637f2009-12-07 08:24:59 +00005616void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5617 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005618 // Ignore dependent types.
5619 if (MD->isDependentContext())
5620 return;
5621
5622 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005623
5624 // Ignore classes without a vtable.
5625 if (!RD->isDynamicClass())
5626 return;
5627
Anders Carlssond6a637f2009-12-07 08:24:59 +00005628 if (!MD->isOutOfLine()) {
5629 // The only inline functions we care about are constructors. We also defer
5630 // marking the virtual members as referenced until we've reached the end
5631 // of the translation unit. We do this because we need to know the key
5632 // function of the class in order to determine the key function.
5633 if (isa<CXXConstructorDecl>(MD))
5634 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5635 return;
5636 }
5637
Anders Carlssonf53df232009-12-07 04:35:11 +00005638 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005639
5640 if (!KeyFunction) {
5641 // This record does not have a key function, so we assume that the vtable
5642 // will be emitted when it's used by the constructor.
5643 if (!isa<CXXConstructorDecl>(MD))
5644 return;
5645 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5646 // We don't have the right key function.
5647 return;
5648 }
5649
Anders Carlssond6a637f2009-12-07 08:24:59 +00005650 // Mark the members as referenced.
5651 MarkVirtualMembersReferenced(Loc, RD);
5652 ClassesWithUnmarkedVirtualMembers.erase(RD);
5653}
5654
5655bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5656 if (ClassesWithUnmarkedVirtualMembers.empty())
5657 return false;
5658
5659 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5660 ClassesWithUnmarkedVirtualMembers.begin(),
5661 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5662 CXXRecordDecl *RD = i->first;
5663
5664 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5665 if (KeyFunction) {
5666 // We know that the class has a key function. If the key function was
5667 // declared in this translation unit, then it the class decl would not
5668 // have been in the ClassesWithUnmarkedVirtualMembers map.
5669 continue;
5670 }
5671
5672 SourceLocation Loc = i->second;
5673 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005674 }
5675
Anders Carlssond6a637f2009-12-07 08:24:59 +00005676 ClassesWithUnmarkedVirtualMembers.clear();
5677 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005678}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005679
5680void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5681 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5682 e = RD->method_end(); i != e; ++i) {
5683 CXXMethodDecl *MD = *i;
5684
5685 // C++ [basic.def.odr]p2:
5686 // [...] A virtual member function is used if it is not pure. [...]
5687 if (MD->isVirtual() && !MD->isPure())
5688 MarkDeclarationReferenced(Loc, MD);
5689 }
5690}
5691