blob: 4552d544b9c0ac92d7b3851147166184a5ad15a0 [file] [log] [blame]
Chris Lattner199abbc2008-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 Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlssonf98849e2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000030#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000031#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner58258242008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000049
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 public:
Mike Stump11289f42009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 };
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000066 }
67
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000093 }
Chris Lattner58258242008-04-10 02:22:51 +000094
Douglas Gregor8e12c382008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000097
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107}
108
Anders Carlssonc80a1272009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000119
Anders Carlssonc80a1272009-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 Gregor85dabae2009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman5f101b92009-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 Carlsson4562f1f2009-08-25 03:18:48 +0000133 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000135
Anders Carlsson6e997b22009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000137
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Anders Carlssonc80a1272009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000142
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000143 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000144}
145
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000149void
Mike Stump11289f42009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattner83f095c2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlssonf1c26952009-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 Stump11289f42009-09-09 15:08:12 +0000174
Anders Carlssonc80a1272009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000176}
177
Douglas Gregor58354032008-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 Stump11289f42009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner83f095c2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000191
Anders Carlsson84613c42009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000193}
194
Douglas Gregor4d87df52008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump11289f42009-09-09 15:08:12 +0000200
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000202
Anders Carlsson84613c42009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000204
Anders Carlsson84613c42009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000206}
207
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-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 Gregor58354032008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor75a45ba2009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000356 }
357 }
358
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000359 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +0000361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000363
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 else
Mike Stump11289f42009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregor556877c2008-04-13 21:30:24 +0000420
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
436 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump11289f42009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000450 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000451 SourceLocation BaseLoc) {
452 // C++ [class.union]p1:
453 // A union shall not have base classes.
454 if (Class->isUnion()) {
455 Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 << SpecifierRange;
457 return 0;
458 }
459
460 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000462 Class->getTagKind() == RecordDecl::TK_class,
463 Access, BaseType);
464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
483 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000484 return 0;
485
Eli Friedmanc96d4962009-08-15 21:55:26 +0000486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Record type has no declaration");
489 BaseDecl = BaseDecl->getDefinition(Context);
490 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000493
Alexis Hunt96d5c762009-11-21 08:43:09 +0000494 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
495 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000499 return 0;
500 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000501
Eli Friedman89c038e2009-12-05 23:03:49 +0000502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000503
504 // Create the base specifier.
505 // FIXME: Allocate via ASTContext?
506 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507 Class->getTagKind() == RecordDecl::TK_class,
508 Access, BaseType);
509}
510
511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512 const CXXRecordDecl *BaseClass,
513 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000514 // A class with a non-empty base class is not empty.
515 // FIXME: Standard ref?
516 if (!BaseClass->isEmpty())
517 Class->setEmpty(false);
518
519 // C++ [class.virtual]p1:
520 // A class that [...] inherits a virtual function is called a polymorphic
521 // class.
522 if (BaseClass->isPolymorphic())
523 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000524
Douglas Gregor463421d2009-03-03 04:44:36 +0000525 // C++ [dcl.init.aggr]p1:
526 // An aggregate is [...] a class with [...] no base classes [...].
527 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000528
529 // C++ [class]p4:
530 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000531 Class->setPOD(false);
532
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000533 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000534 // C++ [class.ctor]p5:
535 // A constructor is trivial if its class has no virtual base classes.
536 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000537
538 // C++ [class.copy]p6:
539 // A copy constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialCopyConstructor(false);
541
542 // C++ [class.copy]p11:
543 // A copy assignment operator is trivial if its class has no virtual
544 // base classes.
545 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000546
547 // C++0x [meta.unary.prop] is_empty:
548 // T is a class type, but not a union type, with ... no virtual base
549 // classes
550 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000551 } else {
552 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000553 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000554 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000555 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000556 Class->setHasTrivialConstructor(false);
557
558 // C++ [class.copy]p6:
559 // A copy constructor is trivial if all the direct base classes of its
560 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000561 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000562 Class->setHasTrivialCopyConstructor(false);
563
564 // C++ [class.copy]p11:
565 // A copy assignment operator is trivial if all the direct base classes
566 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000567 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000568 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000569 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000570
571 // C++ [class.ctor]p3:
572 // A destructor is trivial if all the direct base classes of its class
573 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000574 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000575 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000576}
577
Douglas Gregor556877c2008-04-13 21:30:24 +0000578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000580/// example:
581/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000582/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000583Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000585 bool Virtual, AccessSpecifier Access,
586 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000587 if (!classdecl)
588 return true;
589
Douglas Gregorc40290e2009-03-09 23:48:35 +0000590 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000591 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000592 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
594 Virtual, Access,
595 BaseType, BaseLoc))
596 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000597
Douglas Gregor463421d2009-03-03 04:44:36 +0000598 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000599}
Douglas Gregor556877c2008-04-13 21:30:24 +0000600
Douglas Gregor463421d2009-03-03 04:44:36 +0000601/// \brief Performs the actual work of attaching the given base class
602/// specifiers to a C++ class.
603bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
604 unsigned NumBases) {
605 if (NumBases == 0)
606 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000607
608 // Used to keep track of which base types we have already seen, so
609 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610 // that the key is always the unqualified canonical type of the base
611 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000612 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
613
614 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000616 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000617 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000618 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000619 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000620 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000621
Douglas Gregor29a92472008-10-22 17:49:05 +0000622 if (KnownBaseTypes[NewBaseType]) {
623 // C++ [class.mi]p3:
624 // A class shall not be specified as a direct base class of a
625 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000627 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000628 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000629 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000630
631 // Delete the duplicate base class specifier; we're going to
632 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000634
635 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000636 } else {
637 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 KnownBaseTypes[NewBaseType] = Bases[idx];
639 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000640 }
641 }
642
643 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000644 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000645
646 // Delete the remaining (good) base class specifiers, since their
647 // data has been copied into the CXXRecordDecl.
648 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000649 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000650
651 return Invalid;
652}
653
654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
655/// class, after checking whether there are any duplicate base
656/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000657void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000658 unsigned NumBases) {
659 if (!ClassDecl || !Bases || !NumBases)
660 return;
661
662 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000664 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000665}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000666
Douglas Gregor36d1b142009-10-06 17:59:45 +0000667/// \brief Determine whether the type \p Derived is a C++ class that is
668/// derived from the type \p Base.
669bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
670 if (!getLangOptions().CPlusPlus)
671 return false;
672
673 const RecordType *DerivedRT = Derived->getAs<RecordType>();
674 if (!DerivedRT)
675 return false;
676
677 const RecordType *BaseRT = Base->getAs<RecordType>();
678 if (!BaseRT)
679 return false;
680
681 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
682 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
683 return DerivedRD->isDerivedFrom(BaseRD);
684}
685
686/// \brief Determine whether the type \p Derived is a C++ class that is
687/// derived from the type \p Base.
688bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
689 if (!getLangOptions().CPlusPlus)
690 return false;
691
692 const RecordType *DerivedRT = Derived->getAs<RecordType>();
693 if (!DerivedRT)
694 return false;
695
696 const RecordType *BaseRT = Base->getAs<RecordType>();
697 if (!BaseRT)
698 return false;
699
700 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
701 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
702 return DerivedRD->isDerivedFrom(BaseRD, Paths);
703}
704
705/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
706/// conversion (where Derived and Base are class types) is
707/// well-formed, meaning that the conversion is unambiguous (and
708/// that all of the base classes are accessible). Returns true
709/// and emits a diagnostic if the code is ill-formed, returns false
710/// otherwise. Loc is the location where this routine should point to
711/// if there is an error, and Range is the source range to highlight
712/// if there is an error.
713bool
714Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
715 unsigned InaccessibleBaseID,
716 unsigned AmbigiousBaseConvID,
717 SourceLocation Loc, SourceRange Range,
718 DeclarationName Name) {
719 // First, determine whether the path from Derived to Base is
720 // ambiguous. This is slightly more expensive than checking whether
721 // the Derived to Base conversion exists, because here we need to
722 // explore multiple paths to determine if there is an ambiguity.
723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
724 /*DetectVirtual=*/false);
725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
726 assert(DerivationOkay &&
727 "Can only be used with a derived-to-base conversion");
728 (void)DerivationOkay;
729
730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000731 if (InaccessibleBaseID == 0)
732 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000733 // Check that the base class can be accessed.
734 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
735 Name);
736 }
737
738 // We know that the derived-to-base conversion is ambiguous, and
739 // we're going to produce a diagnostic. Perform the derived-to-base
740 // search just one more time to compute all of the possible paths so
741 // that we can print them out. This is more expensive than any of
742 // the previous derived-to-base checks we've done, but at this point
743 // performance isn't as much of an issue.
744 Paths.clear();
745 Paths.setRecordingPaths(true);
746 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
747 assert(StillOkay && "Can only be used with a derived-to-base conversion");
748 (void)StillOkay;
749
750 // Build up a textual representation of the ambiguous paths, e.g.,
751 // D -> B -> A, that will be used to illustrate the ambiguous
752 // conversions in the diagnostic. We only print one of the paths
753 // to each base class subobject.
754 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
755
756 Diag(Loc, AmbigiousBaseConvID)
757 << Derived << Base << PathDisplayStr << Range << Name;
758 return true;
759}
760
761bool
762Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000763 SourceLocation Loc, SourceRange Range,
764 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000765 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000766 IgnoreAccess ? 0 :
767 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000768 diag::err_ambiguous_derived_to_base_conv,
769 Loc, Range, DeclarationName());
770}
771
772
773/// @brief Builds a string representing ambiguous paths from a
774/// specific derived class to different subobjects of the same base
775/// class.
776///
777/// This function builds a string that can be used in error messages
778/// to show the different paths that one can take through the
779/// inheritance hierarchy to go from the derived class to different
780/// subobjects of a base class. The result looks something like this:
781/// @code
782/// struct D -> struct B -> struct A
783/// struct D -> struct C -> struct A
784/// @endcode
785std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
786 std::string PathDisplayStr;
787 std::set<unsigned> DisplayedPaths;
788 for (CXXBasePaths::paths_iterator Path = Paths.begin();
789 Path != Paths.end(); ++Path) {
790 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
791 // We haven't displayed a path to this particular base
792 // class subobject yet.
793 PathDisplayStr += "\n ";
794 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
795 for (CXXBasePath::const_iterator Element = Path->begin();
796 Element != Path->end(); ++Element)
797 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
798 }
799 }
800
801 return PathDisplayStr;
802}
803
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000804//===----------------------------------------------------------------------===//
805// C++ class member Handling
806//===----------------------------------------------------------------------===//
807
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000808/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
809/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
810/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000811/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000812Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000813Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000814 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000815 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
816 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000817 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000818 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000819 Expr *BitWidth = static_cast<Expr*>(BW);
820 Expr *Init = static_cast<Expr*>(InitExpr);
821 SourceLocation Loc = D.getIdentifierLoc();
822
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000823 bool isFunc = D.isFunctionDeclarator();
824
John McCall07e91c02009-08-06 02:15:43 +0000825 assert(!DS.isFriendSpecified());
826
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000827 // C++ 9.2p6: A member shall not be declared to have automatic storage
828 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000829 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
830 // data members and cannot be applied to names declared const or static,
831 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000832 switch (DS.getStorageClassSpec()) {
833 case DeclSpec::SCS_unspecified:
834 case DeclSpec::SCS_typedef:
835 case DeclSpec::SCS_static:
836 // FALL THROUGH.
837 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000838 case DeclSpec::SCS_mutable:
839 if (isFunc) {
840 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000841 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000842 else
Chris Lattner3b054132008-11-19 05:08:23 +0000843 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000844
Sebastian Redl8071edb2008-11-17 23:24:37 +0000845 // FIXME: It would be nicer if the keyword was ignored only for this
846 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000847 D.getMutableDeclSpec().ClearStorageClassSpecs();
848 } else {
849 QualType T = GetTypeForDeclarator(D, S);
850 diag::kind err = static_cast<diag::kind>(0);
851 if (T->isReferenceType())
852 err = diag::err_mutable_reference;
853 else if (T.isConstQualified())
854 err = diag::err_mutable_const;
855 if (err != 0) {
856 if (DS.getStorageClassSpecLoc().isValid())
857 Diag(DS.getStorageClassSpecLoc(), err);
858 else
859 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000860 // FIXME: It would be nicer if the keyword was ignored only for this
861 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000862 D.getMutableDeclSpec().ClearStorageClassSpecs();
863 }
864 }
865 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000866 default:
867 if (DS.getStorageClassSpecLoc().isValid())
868 Diag(DS.getStorageClassSpecLoc(),
869 diag::err_storageclass_invalid_for_member);
870 else
871 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
872 D.getMutableDeclSpec().ClearStorageClassSpecs();
873 }
874
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000875 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000876 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000877 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000878 // Check also for this case:
879 //
880 // typedef int f();
881 // f a;
882 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000883 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000884 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000885 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000886
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000887 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
888 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000889 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000890
891 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000892 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000893 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000894 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
895 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000896 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000897 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000898 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000899 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000900 if (!Member) {
901 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000902 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000903 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000904
905 // Non-instance-fields can't have a bitfield.
906 if (BitWidth) {
907 if (Member->isInvalidDecl()) {
908 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000909 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000910 // C++ 9.6p3: A bit-field shall not be a static member.
911 // "static member 'A' cannot be a bit-field"
912 Diag(Loc, diag::err_static_not_bitfield)
913 << Name << BitWidth->getSourceRange();
914 } else if (isa<TypedefDecl>(Member)) {
915 // "typedef member 'x' cannot be a bit-field"
916 Diag(Loc, diag::err_typedef_not_bitfield)
917 << Name << BitWidth->getSourceRange();
918 } else {
919 // A function typedef ("typedef int f(); f a;").
920 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
921 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000922 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000923 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattnerd26760a2009-03-05 23:01:03 +0000926 DeleteExpr(BitWidth);
927 BitWidth = 0;
928 Member->setInvalidDecl();
929 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000930
931 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregor3447e762009-08-20 22:52:58 +0000933 // If we have declared a member function template, set the access of the
934 // templated declaration as well.
935 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
936 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000937 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000938
Douglas Gregor92751d42008-11-17 22:58:34 +0000939 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000940
Douglas Gregor0c880302009-03-11 23:00:04 +0000941 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000942 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000943 if (Deleted) // FIXME: Source location is not very good.
944 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000945
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000947 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000948 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000949 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000950 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000951}
952
Douglas Gregor15e77a22009-12-31 09:10:24 +0000953/// \brief Find the direct and/or virtual base specifiers that
954/// correspond to the given base type, for use in base initialization
955/// within a constructor.
956static bool FindBaseInitializer(Sema &SemaRef,
957 CXXRecordDecl *ClassDecl,
958 QualType BaseType,
959 const CXXBaseSpecifier *&DirectBaseSpec,
960 const CXXBaseSpecifier *&VirtualBaseSpec) {
961 // First, check for a direct base class.
962 DirectBaseSpec = 0;
963 for (CXXRecordDecl::base_class_const_iterator Base
964 = ClassDecl->bases_begin();
965 Base != ClassDecl->bases_end(); ++Base) {
966 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
967 // We found a direct base of this type. That's what we're
968 // initializing.
969 DirectBaseSpec = &*Base;
970 break;
971 }
972 }
973
974 // Check for a virtual base class.
975 // FIXME: We might be able to short-circuit this if we know in advance that
976 // there are no virtual bases.
977 VirtualBaseSpec = 0;
978 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
979 // We haven't found a base yet; search the class hierarchy for a
980 // virtual base class.
981 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
982 /*DetectVirtual=*/false);
983 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
984 BaseType, Paths)) {
985 for (CXXBasePaths::paths_iterator Path = Paths.begin();
986 Path != Paths.end(); ++Path) {
987 if (Path->back().Base->isVirtual()) {
988 VirtualBaseSpec = Path->back().Base;
989 break;
990 }
991 }
992 }
993 }
994
995 return DirectBaseSpec || VirtualBaseSpec;
996}
997
Douglas Gregore8381c02008-11-05 04:29:56 +0000998/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000999Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001000Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001001 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001002 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001003 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001004 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001005 SourceLocation IdLoc,
1006 SourceLocation LParenLoc,
1007 ExprTy **Args, unsigned NumArgs,
1008 SourceLocation *CommaLocs,
1009 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001010 if (!ConstructorD)
1011 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001012
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001013 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001014
1015 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001016 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001017 if (!Constructor) {
1018 // The user wrote a constructor initializer on a function that is
1019 // not a C++ constructor. Ignore the error for now, because we may
1020 // have more member initializers coming; we'll diagnose it just
1021 // once in ActOnMemInitializers.
1022 return true;
1023 }
1024
1025 CXXRecordDecl *ClassDecl = Constructor->getParent();
1026
1027 // C++ [class.base.init]p2:
1028 // Names in a mem-initializer-id are looked up in the scope of the
1029 // constructor’s class and, if not found in that scope, are looked
1030 // up in the scope containing the constructor’s
1031 // definition. [Note: if the constructor’s class contains a member
1032 // with the same name as a direct or virtual base class of the
1033 // class, a mem-initializer-id naming the member or base class and
1034 // composed of a single identifier refers to the class member. A
1035 // mem-initializer-id for the hidden base class may be specified
1036 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001037 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001038 // Look for a member, first.
1039 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001040 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001041 = ClassDecl->lookup(MemberOrBase);
1042 if (Result.first != Result.second)
1043 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001044
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001045 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001046
Eli Friedman8e1433b2009-07-29 19:44:27 +00001047 if (Member)
1048 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001049 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001050 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001051 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001052 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001053 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001054
1055 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001056 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001057 } else {
1058 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1059 LookupParsedName(R, S, &SS);
1060
1061 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1062 if (!TyD) {
1063 if (R.isAmbiguous()) return true;
1064
Douglas Gregora3b624a2010-01-19 06:46:48 +00001065 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1066 bool NotUnknownSpecialization = false;
1067 DeclContext *DC = computeDeclContext(SS, false);
1068 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1069 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1070
1071 if (!NotUnknownSpecialization) {
1072 // When the scope specifier can refer to a member of an unknown
1073 // specialization, we take it as a type name.
1074 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1075 *MemberOrBase, SS.getRange());
1076 R.clear();
1077 }
1078 }
1079
Douglas Gregor15e77a22009-12-31 09:10:24 +00001080 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001081 if (R.empty() && BaseType.isNull() &&
Douglas Gregor15e77a22009-12-31 09:10:24 +00001082 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1083 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1084 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1085 // We have found a non-static data member with a similar
1086 // name to what was typed; complain and initialize that
1087 // member.
1088 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1089 << MemberOrBase << true << R.getLookupName()
1090 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1091 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001092 Diag(Member->getLocation(), diag::note_previous_decl)
1093 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001094
1095 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1096 LParenLoc, RParenLoc);
1097 }
1098 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1099 const CXXBaseSpecifier *DirectBaseSpec;
1100 const CXXBaseSpecifier *VirtualBaseSpec;
1101 if (FindBaseInitializer(*this, ClassDecl,
1102 Context.getTypeDeclType(Type),
1103 DirectBaseSpec, VirtualBaseSpec)) {
1104 // We have found a direct or virtual base class with a
1105 // similar name to what was typed; complain and initialize
1106 // that base class.
1107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1108 << MemberOrBase << false << R.getLookupName()
1109 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1110 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001111
1112 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1113 : VirtualBaseSpec;
1114 Diag(BaseSpec->getSourceRange().getBegin(),
1115 diag::note_base_class_specified_here)
1116 << BaseSpec->getType()
1117 << BaseSpec->getSourceRange();
1118
Douglas Gregor15e77a22009-12-31 09:10:24 +00001119 TyD = Type;
1120 }
1121 }
1122 }
1123
Douglas Gregora3b624a2010-01-19 06:46:48 +00001124 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001125 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1126 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1127 return true;
1128 }
John McCallb5a0d312009-12-21 10:41:20 +00001129 }
1130
Douglas Gregora3b624a2010-01-19 06:46:48 +00001131 if (BaseType.isNull()) {
1132 BaseType = Context.getTypeDeclType(TyD);
1133 if (SS.isSet()) {
1134 NestedNameSpecifier *Qualifier =
1135 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001136
Douglas Gregora3b624a2010-01-19 06:46:48 +00001137 // FIXME: preserve source range information
1138 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1139 }
John McCallb5a0d312009-12-21 10:41:20 +00001140 }
1141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
John McCallbcd03502009-12-07 02:54:59 +00001143 if (!TInfo)
1144 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001145
John McCallbcd03502009-12-07 02:54:59 +00001146 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001147 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001148}
1149
John McCalle22a04a2009-11-04 23:02:40 +00001150/// Checks an initializer expression for use of uninitialized fields, such as
1151/// containing the field that is being initialized. Returns true if there is an
1152/// uninitialized field was used an updates the SourceLocation parameter; false
1153/// otherwise.
1154static bool InitExprContainsUninitializedFields(const Stmt* S,
1155 const FieldDecl* LhsField,
1156 SourceLocation* L) {
1157 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1158 if (ME) {
1159 const NamedDecl* RhsField = ME->getMemberDecl();
1160 if (RhsField == LhsField) {
1161 // Initializing a field with itself. Throw a warning.
1162 // But wait; there are exceptions!
1163 // Exception #1: The field may not belong to this record.
1164 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1165 const Expr* base = ME->getBase();
1166 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1167 // Even though the field matches, it does not belong to this record.
1168 return false;
1169 }
1170 // None of the exceptions triggered; return true to indicate an
1171 // uninitialized field was used.
1172 *L = ME->getMemberLoc();
1173 return true;
1174 }
1175 }
1176 bool found = false;
1177 for (Stmt::const_child_iterator it = S->child_begin();
1178 it != S->child_end() && found == false;
1179 ++it) {
1180 if (isa<CallExpr>(S)) {
1181 // Do not descend into function calls or constructors, as the use
1182 // of an uninitialized field may be valid. One would have to inspect
1183 // the contents of the function/ctor to determine if it is safe or not.
1184 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1185 // may be safe, depending on what the function/ctor does.
1186 continue;
1187 }
1188 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1189 }
1190 return found;
1191}
1192
Eli Friedman8e1433b2009-07-29 19:44:27 +00001193Sema::MemInitResult
1194Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1195 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001196 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001197 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001198 // Diagnose value-uses of fields to initialize themselves, e.g.
1199 // foo(foo)
1200 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001201 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001202 for (unsigned i = 0; i < NumArgs; ++i) {
1203 SourceLocation L;
1204 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1205 // FIXME: Return true in the case when other fields are used before being
1206 // uninitialized. For example, let this field be the i'th field. When
1207 // initializing the i'th field, throw a warning if any of the >= i'th
1208 // fields are used, as they are not yet initialized.
1209 // Right now we are only handling the case where the i'th field uses
1210 // itself in its initializer.
1211 Diag(L, diag::warn_field_is_uninit);
1212 }
1213 }
1214
Eli Friedman8e1433b2009-07-29 19:44:27 +00001215 bool HasDependentArg = false;
1216 for (unsigned i = 0; i < NumArgs; i++)
1217 HasDependentArg |= Args[i]->isTypeDependent();
1218
Eli Friedman8e1433b2009-07-29 19:44:27 +00001219 QualType FieldType = Member->getType();
1220 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1221 FieldType = Array->getElementType();
Eli Friedman11c7b152009-12-25 23:59:21 +00001222 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001223 if (FieldType->isDependentType() || HasDependentArg) {
1224 // Can't check initialization for a member of dependent type or when
1225 // any of the arguments are type-dependent expressions.
1226 OwningExprResult Init
1227 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1228 RParenLoc));
1229
1230 // Erase any temporaries within this evaluation context; we're not
1231 // going to track them in the AST, since we'll be rebuilding the
1232 // ASTs during template instantiation.
1233 ExprTemporaries.erase(
1234 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1235 ExprTemporaries.end());
1236
1237 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1238 LParenLoc,
1239 Init.takeAs<Expr>(),
1240 RParenLoc);
1241
Douglas Gregore8381c02008-11-05 04:29:56 +00001242 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001243
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001244 if (Member->isInvalidDecl())
1245 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001246
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001247 // Initialize the member.
1248 InitializedEntity MemberEntity =
1249 InitializedEntity::InitializeMember(Member, 0);
1250 InitializationKind Kind =
1251 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1252
1253 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1254
1255 OwningExprResult MemberInit =
1256 InitSeq.Perform(*this, MemberEntity, Kind,
1257 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1258 if (MemberInit.isInvalid())
1259 return true;
1260
1261 // C++0x [class.base.init]p7:
1262 // The initialization of each base and member constitutes a
1263 // full-expression.
1264 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1265 if (MemberInit.isInvalid())
1266 return true;
1267
1268 // If we are in a dependent context, template instantiation will
1269 // perform this type-checking again. Just save the arguments that we
1270 // received in a ParenListExpr.
1271 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1272 // of the information that we have about the member
1273 // initializer. However, deconstructing the ASTs is a dicey process,
1274 // and this approach is far more likely to get the corner cases right.
1275 if (CurContext->isDependentContext()) {
1276 // Bump the reference count of all of the arguments.
1277 for (unsigned I = 0; I != NumArgs; ++I)
1278 Args[I]->Retain();
1279
1280 OwningExprResult Init
1281 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1282 RParenLoc));
1283 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1284 LParenLoc,
1285 Init.takeAs<Expr>(),
1286 RParenLoc);
1287 }
1288
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001289 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001290 LParenLoc,
1291 MemberInit.takeAs<Expr>(),
1292 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001293}
1294
1295Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001296Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001297 Expr **Args, unsigned NumArgs,
1298 SourceLocation LParenLoc, SourceLocation RParenLoc,
1299 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001300 bool HasDependentArg = false;
1301 for (unsigned i = 0; i < NumArgs; i++)
1302 HasDependentArg |= Args[i]->isTypeDependent();
1303
John McCallbcd03502009-12-07 02:54:59 +00001304 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001305 if (BaseType->isDependentType() || HasDependentArg) {
1306 // Can't check initialization for a base of dependent type or when
1307 // any of the arguments are type-dependent expressions.
1308 OwningExprResult BaseInit
1309 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1310 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001311
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001312 // Erase any temporaries within this evaluation context; we're not
1313 // going to track them in the AST, since we'll be rebuilding the
1314 // ASTs during template instantiation.
1315 ExprTemporaries.erase(
1316 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1317 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001318
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001319 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1320 LParenLoc,
1321 BaseInit.takeAs<Expr>(),
1322 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001323 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001324
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001325 if (!BaseType->isRecordType())
1326 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1327 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1328
1329 // C++ [class.base.init]p2:
1330 // [...] Unless the mem-initializer-id names a nonstatic data
1331 // member of the constructor’s class or a direct or virtual base
1332 // of that class, the mem-initializer is ill-formed. A
1333 // mem-initializer-list can initialize a base class using any
1334 // name that denotes that base class type.
1335
1336 // Check for direct and virtual base classes.
1337 const CXXBaseSpecifier *DirectBaseSpec = 0;
1338 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1339 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1340 VirtualBaseSpec);
1341
1342 // C++ [base.class.init]p2:
1343 // If a mem-initializer-id is ambiguous because it designates both
1344 // a direct non-virtual base class and an inherited virtual base
1345 // class, the mem-initializer is ill-formed.
1346 if (DirectBaseSpec && VirtualBaseSpec)
1347 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1348 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1349 // C++ [base.class.init]p2:
1350 // Unless the mem-initializer-id names a nonstatic data membeer of the
1351 // constructor's class ot a direst or virtual base of that class, the
1352 // mem-initializer is ill-formed.
1353 if (!DirectBaseSpec && !VirtualBaseSpec)
1354 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1355 << BaseType << ClassDecl->getNameAsCString()
1356 << BaseTInfo->getTypeLoc().getSourceRange();
1357
1358 CXXBaseSpecifier *BaseSpec
1359 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1360 if (!BaseSpec)
1361 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1362
1363 // Initialize the base.
1364 InitializedEntity BaseEntity =
1365 InitializedEntity::InitializeBase(Context, BaseSpec);
1366 InitializationKind Kind =
1367 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1368
1369 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1370
1371 OwningExprResult BaseInit =
1372 InitSeq.Perform(*this, BaseEntity, Kind,
1373 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1374 if (BaseInit.isInvalid())
1375 return true;
1376
1377 // C++0x [class.base.init]p7:
1378 // The initialization of each base and member constitutes a
1379 // full-expression.
1380 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1381 if (BaseInit.isInvalid())
1382 return true;
1383
1384 // If we are in a dependent context, template instantiation will
1385 // perform this type-checking again. Just save the arguments that we
1386 // received in a ParenListExpr.
1387 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1388 // of the information that we have about the base
1389 // initializer. However, deconstructing the ASTs is a dicey process,
1390 // and this approach is far more likely to get the corner cases right.
1391 if (CurContext->isDependentContext()) {
1392 // Bump the reference count of all of the arguments.
1393 for (unsigned I = 0; I != NumArgs; ++I)
1394 Args[I]->Retain();
1395
1396 OwningExprResult Init
1397 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1398 RParenLoc));
1399 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1400 LParenLoc,
1401 Init.takeAs<Expr>(),
1402 RParenLoc);
1403 }
1404
1405 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1406 LParenLoc,
1407 BaseInit.takeAs<Expr>(),
1408 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001409}
1410
Eli Friedman9cf6b592009-11-09 19:20:36 +00001411bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001412Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001413 CXXBaseOrMemberInitializer **Initializers,
1414 unsigned NumInitializers,
1415 bool IsImplicitConstructor,
1416 bool AnyErrors) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001417 // We need to build the initializer AST according to order of construction
1418 // and not what user specified in the Initializers list.
1419 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1420 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1421 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1422 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001423 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001424
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001425 for (unsigned i = 0; i < NumInitializers; i++) {
1426 CXXBaseOrMemberInitializer *Member = Initializers[i];
1427 if (Member->isBaseInitializer()) {
1428 if (Member->getBaseClass()->isDependentType())
1429 HasDependentBaseInit = true;
1430 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1431 } else {
1432 AllBaseFields[Member->getMember()] = Member;
1433 }
1434 }
Mike Stump11289f42009-09-09 15:08:12 +00001435
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001436 if (HasDependentBaseInit) {
1437 // FIXME. This does not preserve the ordering of the initializers.
1438 // Try (with -Wreorder)
1439 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001440 // template<class X> struct B : A<X> {
1441 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001442 // int x1;
1443 // };
1444 // B<int> x;
1445 // On seeing one dependent type, we should essentially exit this routine
1446 // while preserving user-declared initializer list. When this routine is
1447 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001448 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001449
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001450 // If we have a dependent base initialization, we can't determine the
1451 // association between initializers and bases; just dump the known
1452 // initializers into the list, and don't try to deal with other bases.
1453 for (unsigned i = 0; i < NumInitializers; i++) {
1454 CXXBaseOrMemberInitializer *Member = Initializers[i];
1455 if (Member->isBaseInitializer())
1456 AllToInit.push_back(Member);
1457 }
1458 } else {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001459 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1460
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001461 // Push virtual bases before others.
1462 for (CXXRecordDecl::base_class_iterator VBase =
1463 ClassDecl->vbases_begin(),
1464 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1465 if (VBase->getType()->isDependentType())
1466 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001467 if (CXXBaseOrMemberInitializer *Value
1468 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001469 AllToInit.push_back(Value);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001470 } else if (!AnyErrors) {
1471 InitializedEntity InitEntity
1472 = InitializedEntity::InitializeBase(Context, VBase);
1473 InitializationKind InitKind
1474 = InitializationKind::CreateDefault(Constructor->getLocation());
1475 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1476 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1477 MultiExprArg(*this, 0, 0));
1478 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1479 if (BaseInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001480 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001481 continue;
1482 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001483
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001484 // Don't attach synthesized base initializers in a dependent
1485 // context; they'll be checked again at template instantiation
1486 // time.
1487 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001488 continue;
1489
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001490 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001491 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001492 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001493 SourceLocation()),
Anders Carlsson561f7932009-10-29 15:46:07 +00001494 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001495 BaseInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001496 SourceLocation());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001497 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001498 }
1499 }
Mike Stump11289f42009-09-09 15:08:12 +00001500
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001501 for (CXXRecordDecl::base_class_iterator Base =
1502 ClassDecl->bases_begin(),
1503 E = ClassDecl->bases_end(); Base != E; ++Base) {
1504 // Virtuals are in the virtual base list and already constructed.
1505 if (Base->isVirtual())
1506 continue;
1507 // Skip dependent types.
1508 if (Base->getType()->isDependentType())
1509 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001510 if (CXXBaseOrMemberInitializer *Value
1511 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001512 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001513 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001514 else if (!AnyErrors) {
1515 InitializedEntity InitEntity
1516 = InitializedEntity::InitializeBase(Context, Base);
1517 InitializationKind InitKind
1518 = InitializationKind::CreateDefault(Constructor->getLocation());
1519 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1520 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1521 MultiExprArg(*this, 0, 0));
1522 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1523 if (BaseInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001524 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001525 continue;
1526 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001527
1528 // Don't attach synthesized base initializers in a dependent
1529 // context; they'll be regenerated at template instantiation
1530 // time.
1531 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001532 continue;
1533
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001534 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001535 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001536 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001537 SourceLocation()),
Anders Carlsson561f7932009-10-29 15:46:07 +00001538 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001539 BaseInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001540 SourceLocation());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001541 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001542 }
1543 }
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001546 // non-static data members.
1547 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1548 E = ClassDecl->field_end(); Field != E; ++Field) {
1549 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001550 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001551 Field->getType()->getAs<RecordType>()) {
1552 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001553 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001554 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001555 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1556 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1557 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1558 // set to the anonymous union data member used in the initializer
1559 // list.
1560 Value->setMember(*Field);
1561 Value->setAnonUnionMember(*FA);
1562 AllToInit.push_back(Value);
1563 break;
1564 }
1565 }
1566 }
1567 continue;
1568 }
1569 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1570 AllToInit.push_back(Value);
1571 continue;
1572 }
Mike Stump11289f42009-09-09 15:08:12 +00001573
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001574 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001575 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001576
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001577 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001578 if (FT->getAs<RecordType>()) {
1579 InitializedEntity InitEntity
1580 = InitializedEntity::InitializeMember(*Field);
1581 InitializationKind InitKind
1582 = InitializationKind::CreateDefault(Constructor->getLocation());
1583
1584 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1585 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1586 MultiExprArg(*this, 0, 0));
1587 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1588 if (MemberInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001589 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001590 continue;
1591 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001592
1593 // Don't attach synthesized member initializers in a dependent
1594 // context; they'll be regenerated a template instantiation
1595 // time.
1596 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001597 continue;
1598
Mike Stump11289f42009-09-09 15:08:12 +00001599 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001600 new (Context) CXXBaseOrMemberInitializer(Context,
1601 *Field, SourceLocation(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001602 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001603 MemberInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001604 SourceLocation());
1605
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001606 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001607 }
1608 else if (FT->isReferenceType()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001609 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001610 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1611 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001612 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001613 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001614 }
1615 else if (FT.isConstQualified()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001616 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001617 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1618 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001619 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001620 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001621 }
1622 }
Mike Stump11289f42009-09-09 15:08:12 +00001623
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001624 NumInitializers = AllToInit.size();
1625 if (NumInitializers > 0) {
1626 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1627 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1628 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001629
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001630 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1631 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1632 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1633 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001634
1635 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001636}
1637
Eli Friedman952c15d2009-07-21 19:28:10 +00001638static void *GetKeyForTopLevelField(FieldDecl *Field) {
1639 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001640 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001641 if (RT->getDecl()->isAnonymousStructOrUnion())
1642 return static_cast<void *>(RT->getDecl());
1643 }
1644 return static_cast<void *>(Field);
1645}
1646
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001647static void *GetKeyForBase(QualType BaseType) {
1648 if (const RecordType *RT = BaseType->getAs<RecordType>())
1649 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001650
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001651 assert(0 && "Unexpected base type!");
1652 return 0;
1653}
1654
Mike Stump11289f42009-09-09 15:08:12 +00001655static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001656 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001657 // For fields injected into the class via declaration of an anonymous union,
1658 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001659 if (Member->isMemberInitializer()) {
1660 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001661
Eli Friedmand7686ef2009-11-09 01:05:47 +00001662 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001663 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001664 // in AnonUnionMember field.
1665 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1666 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001667 if (Field->getDeclContext()->isRecord()) {
1668 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1669 if (RD->isAnonymousStructOrUnion())
1670 return static_cast<void *>(RD);
1671 }
1672 return static_cast<void *>(Field);
1673 }
Mike Stump11289f42009-09-09 15:08:12 +00001674
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001675 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001676}
1677
John McCallc90f6d72009-11-04 23:13:52 +00001678/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001679void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001680 SourceLocation ColonLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001681 MemInitTy **MemInits, unsigned NumMemInits,
1682 bool AnyErrors) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001683 if (!ConstructorDecl)
1684 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001685
1686 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001687
1688 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001689 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001690
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001691 if (!Constructor) {
1692 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1693 return;
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001696 if (!Constructor->isDependentContext()) {
1697 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1698 bool err = false;
1699 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001700 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001701 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1702 void *KeyToMember = GetKeyForMember(Member);
1703 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1704 if (!PrevMember) {
1705 PrevMember = Member;
1706 continue;
1707 }
1708 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001709 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001710 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001711 << Field->getNameAsString()
1712 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001713 else {
1714 Type *BaseClass = Member->getBaseClass();
1715 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001716 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001717 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001718 << QualType(BaseClass, 0)
1719 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001720 }
1721 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1722 << 0;
1723 err = true;
1724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001726 if (err)
1727 return;
1728 }
Mike Stump11289f42009-09-09 15:08:12 +00001729
Eli Friedmand7686ef2009-11-09 01:05:47 +00001730 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001731 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001732 NumMemInits, false, AnyErrors);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001734 if (Constructor->isDependentContext())
1735 return;
Mike Stump11289f42009-09-09 15:08:12 +00001736
1737 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001738 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001739 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001740 Diagnostic::Ignored)
1741 return;
Mike Stump11289f42009-09-09 15:08:12 +00001742
Anders Carlssone0eebb32009-08-27 05:45:01 +00001743 // Also issue warning if order of ctor-initializer list does not match order
1744 // of 1) base class declarations and 2) order of non-static data members.
1745 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001746
Anders Carlssone0eebb32009-08-27 05:45:01 +00001747 CXXRecordDecl *ClassDecl
1748 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1749 // Push virtual bases before others.
1750 for (CXXRecordDecl::base_class_iterator VBase =
1751 ClassDecl->vbases_begin(),
1752 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001753 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001754
Anders Carlssone0eebb32009-08-27 05:45:01 +00001755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1756 E = ClassDecl->bases_end(); Base != E; ++Base) {
1757 // Virtuals are alread in the virtual base list and are constructed
1758 // first.
1759 if (Base->isVirtual())
1760 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001761 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001762 }
Mike Stump11289f42009-09-09 15:08:12 +00001763
Anders Carlssone0eebb32009-08-27 05:45:01 +00001764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1765 E = ClassDecl->field_end(); Field != E; ++Field)
1766 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001767
Anders Carlssone0eebb32009-08-27 05:45:01 +00001768 int Last = AllBaseOrMembers.size();
1769 int curIndex = 0;
1770 CXXBaseOrMemberInitializer *PrevMember = 0;
1771 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001772 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001773 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1774 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001775
Anders Carlssone0eebb32009-08-27 05:45:01 +00001776 for (; curIndex < Last; curIndex++)
1777 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1778 break;
1779 if (curIndex == Last) {
1780 assert(PrevMember && "Member not in member list?!");
1781 // Initializer as specified in ctor-initializer list is out of order.
1782 // Issue a warning diagnostic.
1783 if (PrevMember->isBaseInitializer()) {
1784 // Diagnostics is for an initialized base class.
1785 Type *BaseClass = PrevMember->getBaseClass();
1786 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001787 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001788 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001789 } else {
1790 FieldDecl *Field = PrevMember->getMember();
1791 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001792 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001793 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001794 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001795 // Also the note!
1796 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001797 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001798 diag::note_fieldorbase_initialized_here) << 0
1799 << Field->getNameAsString();
1800 else {
1801 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001802 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001803 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001804 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001805 }
1806 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001807 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001808 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001809 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001810 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001811 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001812}
1813
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001814void
Anders Carlssondee9a302009-11-17 04:44:12 +00001815Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1816 // Ignore dependent destructors.
1817 if (Destructor->isDependentContext())
1818 return;
1819
1820 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001821
Anders Carlssondee9a302009-11-17 04:44:12 +00001822 // Non-static data members.
1823 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1824 E = ClassDecl->field_end(); I != E; ++I) {
1825 FieldDecl *Field = *I;
1826
1827 QualType FieldType = Context.getBaseElementType(Field->getType());
1828
1829 const RecordType* RT = FieldType->getAs<RecordType>();
1830 if (!RT)
1831 continue;
1832
1833 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1834 if (FieldClassDecl->hasTrivialDestructor())
1835 continue;
1836
1837 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1838 MarkDeclarationReferenced(Destructor->getLocation(),
1839 const_cast<CXXDestructorDecl*>(Dtor));
1840 }
1841
1842 // Bases.
1843 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1844 E = ClassDecl->bases_end(); Base != E; ++Base) {
1845 // Ignore virtual bases.
1846 if (Base->isVirtual())
1847 continue;
1848
1849 // Ignore trivial destructors.
1850 CXXRecordDecl *BaseClassDecl
1851 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1852 if (BaseClassDecl->hasTrivialDestructor())
1853 continue;
1854
1855 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1856 MarkDeclarationReferenced(Destructor->getLocation(),
1857 const_cast<CXXDestructorDecl*>(Dtor));
1858 }
1859
1860 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001861 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1862 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001863 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001864 CXXRecordDecl *BaseClassDecl
1865 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1866 if (BaseClassDecl->hasTrivialDestructor())
1867 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001868
1869 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1870 MarkDeclarationReferenced(Destructor->getLocation(),
1871 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001872 }
1873}
1874
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001875void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001876 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001877 return;
Mike Stump11289f42009-09-09 15:08:12 +00001878
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001879 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001880
1881 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001882 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001883 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001884}
1885
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001886namespace {
1887 /// PureVirtualMethodCollector - traverses a class and its superclasses
1888 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001889 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001890 ASTContext &Context;
1891
Sebastian Redlb7d64912009-03-22 21:28:55 +00001892 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001893 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001894
1895 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001896 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001897
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001898 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001900 public:
Mike Stump11289f42009-09-09 15:08:12 +00001901 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001902 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001903
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001904 MethodList List;
1905 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001906
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001907 // Copy the temporary list to methods, and make sure to ignore any
1908 // null entries.
1909 for (size_t i = 0, e = List.size(); i != e; ++i) {
1910 if (List[i])
1911 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001912 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001915 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001917 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1918 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001919 };
Mike Stump11289f42009-09-09 15:08:12 +00001920
1921 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001922 MethodList& Methods) {
1923 // First, collect the pure virtual methods for the base classes.
1924 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1925 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001926 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001927 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001928 if (BaseDecl && BaseDecl->isAbstract())
1929 Collect(BaseDecl, Methods);
1930 }
1931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001933 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001934 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001935
Anders Carlsson3c012712009-05-17 00:00:05 +00001936 MethodSetTy OverriddenMethods;
1937 size_t MethodsSize = Methods.size();
1938
Mike Stump11289f42009-09-09 15:08:12 +00001939 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001940 i != e; ++i) {
1941 // Traverse the record, looking for methods.
1942 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001943 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001944 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001945 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001946
Anders Carlsson700179432009-10-18 19:34:08 +00001947 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001948 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1949 E = MD->end_overridden_methods(); I != E; ++I) {
1950 // Keep track of the overridden methods.
1951 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001952 }
1953 }
1954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
1956 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001957 // overridden.
1958 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1959 if (OverriddenMethods.count(Methods[i]))
1960 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001963 }
1964}
Douglas Gregore8381c02008-11-05 04:29:56 +00001965
Anders Carlssoneabf7702009-08-27 00:13:57 +00001966
Mike Stump11289f42009-09-09 15:08:12 +00001967bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001968 unsigned DiagID, AbstractDiagSelID SelID,
1969 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001970 if (SelID == -1)
1971 return RequireNonAbstractType(Loc, T,
1972 PDiag(DiagID), CurrentRD);
1973 else
1974 return RequireNonAbstractType(Loc, T,
1975 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001976}
1977
Anders Carlssoneabf7702009-08-27 00:13:57 +00001978bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1979 const PartialDiagnostic &PD,
1980 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001981 if (!getLangOptions().CPlusPlus)
1982 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001983
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001984 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001985 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001986 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001987
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001988 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001989 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001990 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001991 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001992
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001993 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001994 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001997 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001998 if (!RT)
1999 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002001 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2002 if (!RD)
2003 return false;
2004
Anders Carlssonb57738b2009-03-24 17:23:42 +00002005 if (CurrentRD && CurrentRD != RD)
2006 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002007
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002008 if (!RD->isAbstract())
2009 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002010
Anders Carlssoneabf7702009-08-27 00:13:57 +00002011 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002012
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002013 // Check if we've already emitted the list of pure virtual functions for this
2014 // class.
2015 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2016 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002018 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00002019
2020 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002021 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2022 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002023
2024 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002025 MD->getDeclName();
2026 }
2027
2028 if (!PureVirtualClassDiagSet)
2029 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2030 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002031
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002032 return true;
2033}
2034
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002035namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002036 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002037 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2038 Sema &SemaRef;
2039 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002040
Anders Carlssonb57738b2009-03-24 17:23:42 +00002041 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002042 bool Invalid = false;
2043
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002044 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2045 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002046 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002047
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002048 return Invalid;
2049 }
Mike Stump11289f42009-09-09 15:08:12 +00002050
Anders Carlssonb57738b2009-03-24 17:23:42 +00002051 public:
2052 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2053 : SemaRef(SemaRef), AbstractClass(ac) {
2054 Visit(SemaRef.Context.getTranslationUnitDecl());
2055 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002056
Anders Carlssonb57738b2009-03-24 17:23:42 +00002057 bool VisitFunctionDecl(const FunctionDecl *FD) {
2058 if (FD->isThisDeclarationADefinition()) {
2059 // No need to do the check if we're in a definition, because it requires
2060 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002061 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002062 return VisitDeclContext(FD);
2063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Anders Carlssonb57738b2009-03-24 17:23:42 +00002065 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002066 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002067 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002068 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2069 diag::err_abstract_type_in_decl,
2070 Sema::AbstractReturnType,
2071 AbstractClass);
2072
Mike Stump11289f42009-09-09 15:08:12 +00002073 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002074 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002075 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002076 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002077 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002078 VD->getOriginalType(),
2079 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002080 Sema::AbstractParamType,
2081 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002082 }
2083
2084 return Invalid;
2085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Anders Carlssonb57738b2009-03-24 17:23:42 +00002087 bool VisitDecl(const Decl* D) {
2088 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2089 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002090
Anders Carlssonb57738b2009-03-24 17:23:42 +00002091 return false;
2092 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002093 };
2094}
2095
Douglas Gregorc99f1552009-12-03 18:33:45 +00002096/// \brief Perform semantic checks on a class definition that has been
2097/// completing, introducing implicitly-declared members, checking for
2098/// abstract types, etc.
2099void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2100 if (!Record || Record->isInvalidDecl())
2101 return;
2102
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002103 if (!Record->isDependentType())
2104 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002105
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002106 if (Record->isInvalidDecl())
2107 return;
2108
John McCall2cb94162010-01-28 07:38:46 +00002109 // Set access bits correctly on the directly-declared conversions.
2110 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2111 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2112 Convs->setAccess(I, (*I)->getAccess());
2113
Douglas Gregorc99f1552009-12-03 18:33:45 +00002114 if (!Record->isAbstract()) {
2115 // Collect all the pure virtual methods and see if this is an abstract
2116 // class after all.
2117 PureVirtualMethodCollector Collector(Context, Record);
2118 if (!Collector.empty())
2119 Record->setAbstract(true);
2120 }
2121
2122 if (Record->isAbstract())
2123 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002124}
2125
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002126void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002127 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002128 SourceLocation LBrac,
2129 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002130 if (!TagDecl)
2131 return;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002133 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002134
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002135 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002136 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00002137 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00002138
Douglas Gregorc99f1552009-12-03 18:33:45 +00002139 CheckCompletedCXXClass(
2140 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002141}
2142
Douglas Gregor05379422008-11-03 17:51:48 +00002143/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2144/// special functions, such as the default constructor, copy
2145/// constructor, or destructor, to the given C++ class (C++
2146/// [special]p1). This routine can only be executed just before the
2147/// definition of the class is complete.
2148void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002149 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002150 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002151
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002152 // FIXME: Implicit declarations have exception specifications, which are
2153 // the union of the specifications of the implicitly called functions.
2154
Douglas Gregor05379422008-11-03 17:51:48 +00002155 if (!ClassDecl->hasUserDeclaredConstructor()) {
2156 // C++ [class.ctor]p5:
2157 // A default constructor for a class X is a constructor of class X
2158 // that can be called without an argument. If there is no
2159 // user-declared constructor for class X, a default constructor is
2160 // implicitly declared. An implicitly-declared default constructor
2161 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002162 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002163 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002164 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002165 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002166 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002167 Context.getFunctionType(Context.VoidTy,
2168 0, 0, false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002169 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002170 /*isExplicit=*/false,
2171 /*isInline=*/true,
2172 /*isImplicitlyDeclared=*/true);
2173 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002174 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002175 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002176 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002177 }
2178
2179 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2180 // C++ [class.copy]p4:
2181 // If the class definition does not explicitly declare a copy
2182 // constructor, one is declared implicitly.
2183
2184 // C++ [class.copy]p5:
2185 // The implicitly-declared copy constructor for a class X will
2186 // have the form
2187 //
2188 // X::X(const X&)
2189 //
2190 // if
2191 bool HasConstCopyConstructor = true;
2192
2193 // -- each direct or virtual base class B of X has a copy
2194 // constructor whose first parameter is of type const B& or
2195 // const volatile B&, and
2196 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2197 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2198 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002199 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002200 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002201 = BaseClassDecl->hasConstCopyConstructor(Context);
2202 }
2203
2204 // -- for all the nonstatic data members of X that are of a
2205 // class type M (or array thereof), each such class type
2206 // has a copy constructor whose first parameter is of type
2207 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002208 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2209 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002210 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002211 QualType FieldType = (*Field)->getType();
2212 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2213 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002214 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002215 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002216 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002217 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002218 = FieldClassDecl->hasConstCopyConstructor(Context);
2219 }
2220 }
2221
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002222 // Otherwise, the implicitly declared copy constructor will have
2223 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002224 //
2225 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002226 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002227 if (HasConstCopyConstructor)
2228 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002229 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002230
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002231 // An implicitly-declared copy constructor is an inline public
2232 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002233 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002234 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002235 CXXConstructorDecl *CopyConstructor
2236 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002237 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002238 Context.getFunctionType(Context.VoidTy,
2239 &ArgType, 1,
2240 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002241 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002242 /*isExplicit=*/false,
2243 /*isInline=*/true,
2244 /*isImplicitlyDeclared=*/true);
2245 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002246 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002247 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002248
2249 // Add the parameter to the constructor.
2250 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2251 ClassDecl->getLocation(),
2252 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002253 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002254 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002255 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002256 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002257 }
2258
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002259 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2260 // Note: The following rules are largely analoguous to the copy
2261 // constructor rules. Note that virtual bases are not taken into account
2262 // for determining the argument type of the operator. Note also that
2263 // operators taking an object instead of a reference are allowed.
2264 //
2265 // C++ [class.copy]p10:
2266 // If the class definition does not explicitly declare a copy
2267 // assignment operator, one is declared implicitly.
2268 // The implicitly-defined copy assignment operator for a class X
2269 // will have the form
2270 //
2271 // X& X::operator=(const X&)
2272 //
2273 // if
2274 bool HasConstCopyAssignment = true;
2275
2276 // -- each direct base class B of X has a copy assignment operator
2277 // whose parameter is of type const B&, const volatile B& or B,
2278 // and
2279 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2280 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002281 assert(!Base->getType()->isDependentType() &&
2282 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002283 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002284 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002285 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002286 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002287 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002288 }
2289
2290 // -- for all the nonstatic data members of X that are of a class
2291 // type M (or array thereof), each such class type has a copy
2292 // assignment operator whose parameter is of type const M&,
2293 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002294 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2295 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002296 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002297 QualType FieldType = (*Field)->getType();
2298 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2299 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002300 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002301 const CXXRecordDecl *FieldClassDecl
2302 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002303 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002304 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002305 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002306 }
2307 }
2308
2309 // Otherwise, the implicitly declared copy assignment operator will
2310 // have the form
2311 //
2312 // X& X::operator=(X&)
2313 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002314 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002315 if (HasConstCopyAssignment)
2316 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002317 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002318
2319 // An implicitly-declared copy assignment operator is an inline public
2320 // member of its class.
2321 DeclarationName Name =
2322 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2323 CXXMethodDecl *CopyAssignment =
2324 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2325 Context.getFunctionType(RetType, &ArgType, 1,
2326 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002327 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002328 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002329 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002330 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002331 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002332
2333 // Add the parameter to the operator.
2334 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2335 ClassDecl->getLocation(),
2336 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002337 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002338 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002339 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002340
2341 // Don't call addedAssignmentOperator. There is no way to distinguish an
2342 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002343 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002344 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002345 }
2346
Douglas Gregor1349b452008-12-15 21:24:18 +00002347 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002348 // C++ [class.dtor]p2:
2349 // If a class has no user-declared destructor, a destructor is
2350 // declared implicitly. An implicitly-declared destructor is an
2351 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002352 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002353 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002354 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002355 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002356 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002357 Context.getFunctionType(Context.VoidTy,
2358 0, 0, false, 0),
2359 /*isInline=*/true,
2360 /*isImplicitlyDeclared=*/true);
2361 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002362 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002363 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002364 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002365
2366 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002367 }
Douglas Gregor05379422008-11-03 17:51:48 +00002368}
2369
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002370void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002371 Decl *D = TemplateD.getAs<Decl>();
2372 if (!D)
2373 return;
2374
2375 TemplateParameterList *Params = 0;
2376 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2377 Params = Template->getTemplateParameters();
2378 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2379 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2380 Params = PartialSpec->getTemplateParameters();
2381 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002382 return;
2383
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002384 for (TemplateParameterList::iterator Param = Params->begin(),
2385 ParamEnd = Params->end();
2386 Param != ParamEnd; ++Param) {
2387 NamedDecl *Named = cast<NamedDecl>(*Param);
2388 if (Named->getDeclName()) {
2389 S->AddDecl(DeclPtrTy::make(Named));
2390 IdResolver.AddDecl(Named);
2391 }
2392 }
2393}
2394
John McCall6df5fef2009-12-19 10:49:29 +00002395void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2396 if (!RecordD) return;
2397 AdjustDeclIfTemplate(RecordD);
2398 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2399 PushDeclContext(S, Record);
2400}
2401
2402void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2403 if (!RecordD) return;
2404 PopDeclContext();
2405}
2406
Douglas Gregor4d87df52008-12-16 21:30:33 +00002407/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2408/// parsing a top-level (non-nested) C++ class, and we are now
2409/// parsing those parts of the given Method declaration that could
2410/// not be parsed earlier (C++ [class.mem]p2), such as default
2411/// arguments. This action should enter the scope of the given
2412/// Method declaration as if we had just parsed the qualified method
2413/// name. However, it should not bring the parameters into scope;
2414/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002415void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002416}
2417
2418/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2419/// C++ method declaration. We're (re-)introducing the given
2420/// function parameter into scope for use in parsing later parts of
2421/// the method declaration. For example, we could see an
2422/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002423void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002424 if (!ParamD)
2425 return;
Mike Stump11289f42009-09-09 15:08:12 +00002426
Chris Lattner83f095c2009-03-28 19:18:32 +00002427 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002428
2429 // If this parameter has an unparsed default argument, clear it out
2430 // to make way for the parsed default argument.
2431 if (Param->hasUnparsedDefaultArg())
2432 Param->setDefaultArg(0);
2433
Chris Lattner83f095c2009-03-28 19:18:32 +00002434 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002435 if (Param->getDeclName())
2436 IdResolver.AddDecl(Param);
2437}
2438
2439/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2440/// processing the delayed method declaration for Method. The method
2441/// declaration is now considered finished. There may be a separate
2442/// ActOnStartOfFunctionDef action later (not necessarily
2443/// immediately!) for this method, if it was also defined inside the
2444/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002445void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002446 if (!MethodD)
2447 return;
Mike Stump11289f42009-09-09 15:08:12 +00002448
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002449 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002450
Chris Lattner83f095c2009-03-28 19:18:32 +00002451 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002452
2453 // Now that we have our default arguments, check the constructor
2454 // again. It could produce additional diagnostics or affect whether
2455 // the class has implicitly-declared destructors, among other
2456 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002457 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2458 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002459
2460 // Check the default arguments, which we may have added.
2461 if (!Method->isInvalidDecl())
2462 CheckCXXDefaultArguments(Method);
2463}
2464
Douglas Gregor831c93f2008-11-05 20:51:48 +00002465/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002466/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002467/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002468/// emit diagnostics and set the invalid bit to true. In any case, the type
2469/// will be updated to reflect a well-formed type for the constructor and
2470/// returned.
2471QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2472 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002473 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002474
2475 // C++ [class.ctor]p3:
2476 // A constructor shall not be virtual (10.3) or static (9.4). A
2477 // constructor can be invoked for a const, volatile or const
2478 // volatile object. A constructor shall not be declared const,
2479 // volatile, or const volatile (9.3.2).
2480 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002481 if (!D.isInvalidType())
2482 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2483 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2484 << SourceRange(D.getIdentifierLoc());
2485 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002486 }
2487 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002488 if (!D.isInvalidType())
2489 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2490 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2491 << SourceRange(D.getIdentifierLoc());
2492 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002493 SC = FunctionDecl::None;
2494 }
Mike Stump11289f42009-09-09 15:08:12 +00002495
Chris Lattner38378bf2009-04-25 08:28:21 +00002496 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2497 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002498 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002499 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2500 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002501 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002502 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2503 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002504 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2506 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Douglas Gregor831c93f2008-11-05 20:51:48 +00002509 // Rebuild the function type "R" without any type qualifiers (in
2510 // case any of the errors above fired) and with "void" as the
2511 // return type, since constructors don't have return types. We
2512 // *always* have to do this, because GetTypeForDeclarator will
2513 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002514 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002515 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2516 Proto->getNumArgs(),
2517 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002518}
2519
Douglas Gregor4d87df52008-12-16 21:30:33 +00002520/// CheckConstructor - Checks a fully-formed constructor for
2521/// well-formedness, issuing any diagnostics required. Returns true if
2522/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002523void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002524 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002525 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2526 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002527 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002528
2529 // C++ [class.copy]p3:
2530 // A declaration of a constructor for a class X is ill-formed if
2531 // its first parameter is of type (optionally cv-qualified) X and
2532 // either there are no other parameters or else all other
2533 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002534 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002535 ((Constructor->getNumParams() == 1) ||
2536 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002537 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2538 Constructor->getTemplateSpecializationKind()
2539 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002540 QualType ParamType = Constructor->getParamDecl(0)->getType();
2541 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2542 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002543 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2544 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002545 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002546
2547 // FIXME: Rather that making the constructor invalid, we should endeavor
2548 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002549 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002550 }
2551 }
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregor4d87df52008-12-16 21:30:33 +00002553 // Notify the class that we've added a constructor.
2554 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002555}
2556
Anders Carlsson26a807d2009-11-30 21:24:50 +00002557/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2558/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002559bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002560 CXXRecordDecl *RD = Destructor->getParent();
2561
2562 if (Destructor->isVirtual()) {
2563 SourceLocation Loc;
2564
2565 if (!Destructor->isImplicit())
2566 Loc = Destructor->getLocation();
2567 else
2568 Loc = RD->getLocation();
2569
2570 // If we have a virtual destructor, look up the deallocation function
2571 FunctionDecl *OperatorDelete = 0;
2572 DeclarationName Name =
2573 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002574 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002575 return true;
2576
2577 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002578 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002579
2580 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002581}
2582
Mike Stump11289f42009-09-09 15:08:12 +00002583static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002584FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2585 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2586 FTI.ArgInfo[0].Param &&
2587 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2588}
2589
Douglas Gregor831c93f2008-11-05 20:51:48 +00002590/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2591/// the well-formednes of the destructor declarator @p D with type @p
2592/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002593/// emit diagnostics and set the declarator to invalid. Even if this happens,
2594/// will be updated to reflect a well-formed type for the destructor and
2595/// returned.
2596QualType Sema::CheckDestructorDeclarator(Declarator &D,
2597 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002598 // C++ [class.dtor]p1:
2599 // [...] A typedef-name that names a class is a class-name
2600 // (7.1.3); however, a typedef-name that names a class shall not
2601 // be used as the identifier in the declarator for a destructor
2602 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002603 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002604 if (isa<TypedefType>(DeclaratorType)) {
2605 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002606 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002607 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002608 }
2609
2610 // C++ [class.dtor]p2:
2611 // A destructor is used to destroy objects of its class type. A
2612 // destructor takes no parameters, and no return type can be
2613 // specified for it (not even void). The address of a destructor
2614 // shall not be taken. A destructor shall not be static. A
2615 // destructor can be invoked for a const, volatile or const
2616 // volatile object. A destructor shall not be declared const,
2617 // volatile or const volatile (9.3.2).
2618 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002619 if (!D.isInvalidType())
2620 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2621 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2622 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002623 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002624 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002625 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002626 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002627 // Destructors don't have return types, but the parser will
2628 // happily parse something like:
2629 //
2630 // class X {
2631 // float ~X();
2632 // };
2633 //
2634 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002635 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2636 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2637 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002638 }
Mike Stump11289f42009-09-09 15:08:12 +00002639
Chris Lattner38378bf2009-04-25 08:28:21 +00002640 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2641 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002642 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002643 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2644 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002645 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002646 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2647 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002648 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002649 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2650 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002651 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002652 }
2653
2654 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002655 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002656 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2657
2658 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002659 FTI.freeArgs();
2660 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002661 }
2662
Mike Stump11289f42009-09-09 15:08:12 +00002663 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002664 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002665 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002666 D.setInvalidType();
2667 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002668
2669 // Rebuild the function type "R" without any type qualifiers or
2670 // parameters (in case any of the errors above fired) and with
2671 // "void" as the return type, since destructors don't have return
2672 // types. We *always* have to do this, because GetTypeForDeclarator
2673 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002674 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002675}
2676
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002677/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2678/// well-formednes of the conversion function declarator @p D with
2679/// type @p R. If there are any errors in the declarator, this routine
2680/// will emit diagnostics and return true. Otherwise, it will return
2681/// false. Either way, the type @p R will be updated to reflect a
2682/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002683void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002684 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002685 // C++ [class.conv.fct]p1:
2686 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002687 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002688 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002689 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002690 if (!D.isInvalidType())
2691 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2692 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2693 << SourceRange(D.getIdentifierLoc());
2694 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002695 SC = FunctionDecl::None;
2696 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002697 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002698 // Conversion functions don't have return types, but the parser will
2699 // happily parse something like:
2700 //
2701 // class X {
2702 // float operator bool();
2703 // };
2704 //
2705 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002706 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2707 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2708 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002709 }
2710
2711 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002712 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002713 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2714
2715 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002716 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002717 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002718 }
2719
Mike Stump11289f42009-09-09 15:08:12 +00002720 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002721 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002722 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002723 D.setInvalidType();
2724 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002725
2726 // C++ [class.conv.fct]p4:
2727 // The conversion-type-id shall not represent a function type nor
2728 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002729 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002730 if (ConvType->isArrayType()) {
2731 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2732 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002733 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002734 } else if (ConvType->isFunctionType()) {
2735 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2736 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002737 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002738 }
2739
2740 // Rebuild the function type "R" without any parameters (in case any
2741 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002742 // return type.
2743 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002744 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002745
Douglas Gregor5fb53972009-01-14 15:45:31 +00002746 // C++0x explicit conversion operators.
2747 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002748 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002749 diag::warn_explicit_conversion_functions)
2750 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002751}
2752
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002753/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2754/// the declaration of the given C++ conversion function. This routine
2755/// is responsible for recording the conversion function in the C++
2756/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002757Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002758 assert(Conversion && "Expected to receive a conversion function declaration");
2759
Douglas Gregor4287b372008-12-12 08:25:50 +00002760 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002761
2762 // Make sure we aren't redeclaring the conversion function.
2763 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002764
2765 // C++ [class.conv.fct]p1:
2766 // [...] A conversion function is never used to convert a
2767 // (possibly cv-qualified) object to the (possibly cv-qualified)
2768 // same object type (or a reference to it), to a (possibly
2769 // cv-qualified) base class of that type (or a reference to it),
2770 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002771 // FIXME: Suppress this warning if the conversion function ends up being a
2772 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002773 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002774 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002775 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002776 ConvType = ConvTypeRef->getPointeeType();
2777 if (ConvType->isRecordType()) {
2778 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2779 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002780 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002781 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002782 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002783 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002784 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002785 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002786 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002787 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002788 }
2789
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002790 if (Conversion->getPrimaryTemplate()) {
2791 // ignore specializations
2792 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00002793 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00002794 = Conversion->getDescribedFunctionTemplate()) {
2795 if (ClassDecl->replaceConversion(
2796 ConversionTemplate->getPreviousDeclaration(),
2797 ConversionTemplate))
2798 return DeclPtrTy::make(ConversionTemplate);
2799 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2800 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00002801 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002802 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002803 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002804 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002805 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002806 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002807 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002808
Chris Lattner83f095c2009-03-28 19:18:32 +00002809 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002810}
2811
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002812//===----------------------------------------------------------------------===//
2813// Namespace Handling
2814//===----------------------------------------------------------------------===//
2815
2816/// ActOnStartNamespaceDef - This is called at the start of a namespace
2817/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002818Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2819 SourceLocation IdentLoc,
2820 IdentifierInfo *II,
2821 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002822 NamespaceDecl *Namespc =
2823 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2824 Namespc->setLBracLoc(LBrace);
2825
2826 Scope *DeclRegionScope = NamespcScope->getParent();
2827
2828 if (II) {
2829 // C++ [namespace.def]p2:
2830 // The identifier in an original-namespace-definition shall not have been
2831 // previously defined in the declarative region in which the
2832 // original-namespace-definition appears. The identifier in an
2833 // original-namespace-definition is the name of the namespace. Subsequently
2834 // in that declarative region, it is treated as an original-namespace-name.
2835
John McCall9f3059a2009-10-09 21:13:30 +00002836 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002837 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002838 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002839
Douglas Gregor91f84212008-12-11 16:49:14 +00002840 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2841 // This is an extended namespace definition.
2842 // Attach this namespace decl to the chain of extended namespace
2843 // definitions.
2844 OrigNS->setNextNamespace(Namespc);
2845 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002846
Mike Stump11289f42009-09-09 15:08:12 +00002847 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002848 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002849 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002850 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002851 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002852 } else if (PrevDecl) {
2853 // This is an invalid name redefinition.
2854 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2855 << Namespc->getDeclName();
2856 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2857 Namespc->setInvalidDecl();
2858 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002859 } else if (II->isStr("std") &&
2860 CurContext->getLookupContext()->isTranslationUnit()) {
2861 // This is the first "real" definition of the namespace "std", so update
2862 // our cache of the "std" namespace to point at this definition.
2863 if (StdNamespace) {
2864 // We had already defined a dummy namespace "std". Link this new
2865 // namespace definition to the dummy namespace "std".
2866 StdNamespace->setNextNamespace(Namespc);
2867 StdNamespace->setLocation(IdentLoc);
2868 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2869 }
2870
2871 // Make our StdNamespace cache point at the first real definition of the
2872 // "std" namespace.
2873 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002874 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002875
2876 PushOnScopeChains(Namespc, DeclRegionScope);
2877 } else {
John McCall4fa53422009-10-01 00:25:31 +00002878 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00002879 assert(Namespc->isAnonymousNamespace());
2880 CurContext->addDecl(Namespc);
2881
2882 // Link the anonymous namespace into its parent.
2883 NamespaceDecl *PrevDecl;
2884 DeclContext *Parent = CurContext->getLookupContext();
2885 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2886 PrevDecl = TU->getAnonymousNamespace();
2887 TU->setAnonymousNamespace(Namespc);
2888 } else {
2889 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2890 PrevDecl = ND->getAnonymousNamespace();
2891 ND->setAnonymousNamespace(Namespc);
2892 }
2893
2894 // Link the anonymous namespace with its previous declaration.
2895 if (PrevDecl) {
2896 assert(PrevDecl->isAnonymousNamespace());
2897 assert(!PrevDecl->getNextNamespace());
2898 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2899 PrevDecl->setNextNamespace(Namespc);
2900 }
John McCall4fa53422009-10-01 00:25:31 +00002901
2902 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2903 // behaves as if it were replaced by
2904 // namespace unique { /* empty body */ }
2905 // using namespace unique;
2906 // namespace unique { namespace-body }
2907 // where all occurrences of 'unique' in a translation unit are
2908 // replaced by the same identifier and this identifier differs
2909 // from all other identifiers in the entire program.
2910
2911 // We just create the namespace with an empty name and then add an
2912 // implicit using declaration, just like the standard suggests.
2913 //
2914 // CodeGen enforces the "universally unique" aspect by giving all
2915 // declarations semantically contained within an anonymous
2916 // namespace internal linkage.
2917
John McCall0db42252009-12-16 02:06:49 +00002918 if (!PrevDecl) {
2919 UsingDirectiveDecl* UD
2920 = UsingDirectiveDecl::Create(Context, CurContext,
2921 /* 'using' */ LBrace,
2922 /* 'namespace' */ SourceLocation(),
2923 /* qualifier */ SourceRange(),
2924 /* NNS */ NULL,
2925 /* identifier */ SourceLocation(),
2926 Namespc,
2927 /* Ancestor */ CurContext);
2928 UD->setImplicit();
2929 CurContext->addDecl(UD);
2930 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002931 }
2932
2933 // Although we could have an invalid decl (i.e. the namespace name is a
2934 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002935 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2936 // for the namespace has the declarations that showed up in that particular
2937 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002938 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002939 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002940}
2941
Sebastian Redla6602e92009-11-23 15:34:23 +00002942/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2943/// is a namespace alias, returns the namespace it points to.
2944static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2945 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2946 return AD->getNamespace();
2947 return dyn_cast_or_null<NamespaceDecl>(D);
2948}
2949
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002950/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2951/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002952void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2953 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002954 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2955 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2956 Namespc->setRBracLoc(RBrace);
2957 PopDeclContext();
2958}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002959
Chris Lattner83f095c2009-03-28 19:18:32 +00002960Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2961 SourceLocation UsingLoc,
2962 SourceLocation NamespcLoc,
2963 const CXXScopeSpec &SS,
2964 SourceLocation IdentLoc,
2965 IdentifierInfo *NamespcName,
2966 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002967 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2968 assert(NamespcName && "Invalid NamespcName.");
2969 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002970 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002971
Douglas Gregor889ceb72009-02-03 19:21:40 +00002972 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002973
Douglas Gregor34074322009-01-14 22:20:51 +00002974 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002975 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2976 LookupParsedName(R, S, &SS);
2977 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002978 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002979
John McCall9f3059a2009-10-09 21:13:30 +00002980 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002981 NamedDecl *Named = R.getFoundDecl();
2982 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2983 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002984 // C++ [namespace.udir]p1:
2985 // A using-directive specifies that the names in the nominated
2986 // namespace can be used in the scope in which the
2987 // using-directive appears after the using-directive. During
2988 // unqualified name lookup (3.4.1), the names appear as if they
2989 // were declared in the nearest enclosing namespace which
2990 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002991 // namespace. [Note: in this context, "contains" means "contains
2992 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002993
2994 // Find enclosing context containing both using-directive and
2995 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002996 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002997 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2998 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2999 CommonAncestor = CommonAncestor->getParent();
3000
Sebastian Redla6602e92009-11-23 15:34:23 +00003001 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003002 SS.getRange(),
3003 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003004 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003005 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003006 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003007 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003008 }
3009
Douglas Gregor889ceb72009-02-03 19:21:40 +00003010 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003011 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003012 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003013}
3014
3015void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3016 // If scope has associated entity, then using directive is at namespace
3017 // or translation unit scope. We add UsingDirectiveDecls, into
3018 // it's lookup structure.
3019 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003020 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003021 else
3022 // Otherwise it is block-sope. using-directives will affect lookup
3023 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003024 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003025}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003026
Douglas Gregorfec52632009-06-20 00:51:54 +00003027
3028Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003029 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003030 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003031 SourceLocation UsingLoc,
3032 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003033 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003034 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003035 bool IsTypeName,
3036 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003037 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003038
Douglas Gregor220f4272009-11-04 16:30:06 +00003039 switch (Name.getKind()) {
3040 case UnqualifiedId::IK_Identifier:
3041 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003042 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003043 case UnqualifiedId::IK_ConversionFunctionId:
3044 break;
3045
3046 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003047 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003048 // C++0x inherited constructors.
3049 if (getLangOptions().CPlusPlus0x) break;
3050
Douglas Gregor220f4272009-11-04 16:30:06 +00003051 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3052 << SS.getRange();
3053 return DeclPtrTy();
3054
3055 case UnqualifiedId::IK_DestructorName:
3056 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3057 << SS.getRange();
3058 return DeclPtrTy();
3059
3060 case UnqualifiedId::IK_TemplateId:
3061 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3062 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3063 return DeclPtrTy();
3064 }
3065
3066 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003067 if (!TargetName)
3068 return DeclPtrTy();
3069
John McCalla0097262009-12-11 02:10:03 +00003070 // Warn about using declarations.
3071 // TODO: store that the declaration was written without 'using' and
3072 // talk about access decls instead of using decls in the
3073 // diagnostics.
3074 if (!HasUsingKeyword) {
3075 UsingLoc = Name.getSourceRange().getBegin();
3076
3077 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3078 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3079 "using ");
3080 }
3081
John McCall3f746822009-11-17 05:59:44 +00003082 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003083 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003084 TargetName, AttrList,
3085 /* IsInstantiation */ false,
3086 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003087 if (UD)
3088 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003089
Anders Carlsson696a3f12009-08-28 05:40:36 +00003090 return DeclPtrTy::make(UD);
3091}
3092
John McCall84d87672009-12-10 09:41:52 +00003093/// Determines whether to create a using shadow decl for a particular
3094/// decl, given the set of decls existing prior to this using lookup.
3095bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3096 const LookupResult &Previous) {
3097 // Diagnose finding a decl which is not from a base class of the
3098 // current class. We do this now because there are cases where this
3099 // function will silently decide not to build a shadow decl, which
3100 // will pre-empt further diagnostics.
3101 //
3102 // We don't need to do this in C++0x because we do the check once on
3103 // the qualifier.
3104 //
3105 // FIXME: diagnose the following if we care enough:
3106 // struct A { int foo; };
3107 // struct B : A { using A::foo; };
3108 // template <class T> struct C : A {};
3109 // template <class T> struct D : C<T> { using B::foo; } // <---
3110 // This is invalid (during instantiation) in C++03 because B::foo
3111 // resolves to the using decl in B, which is not a base class of D<T>.
3112 // We can't diagnose it immediately because C<T> is an unknown
3113 // specialization. The UsingShadowDecl in D<T> then points directly
3114 // to A::foo, which will look well-formed when we instantiate.
3115 // The right solution is to not collapse the shadow-decl chain.
3116 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3117 DeclContext *OrigDC = Orig->getDeclContext();
3118
3119 // Handle enums and anonymous structs.
3120 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3121 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3122 while (OrigRec->isAnonymousStructOrUnion())
3123 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3124
3125 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3126 if (OrigDC == CurContext) {
3127 Diag(Using->getLocation(),
3128 diag::err_using_decl_nested_name_specifier_is_current_class)
3129 << Using->getNestedNameRange();
3130 Diag(Orig->getLocation(), diag::note_using_decl_target);
3131 return true;
3132 }
3133
3134 Diag(Using->getNestedNameRange().getBegin(),
3135 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3136 << Using->getTargetNestedNameDecl()
3137 << cast<CXXRecordDecl>(CurContext)
3138 << Using->getNestedNameRange();
3139 Diag(Orig->getLocation(), diag::note_using_decl_target);
3140 return true;
3141 }
3142 }
3143
3144 if (Previous.empty()) return false;
3145
3146 NamedDecl *Target = Orig;
3147 if (isa<UsingShadowDecl>(Target))
3148 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3149
John McCalla17e83e2009-12-11 02:33:26 +00003150 // If the target happens to be one of the previous declarations, we
3151 // don't have a conflict.
3152 //
3153 // FIXME: but we might be increasing its access, in which case we
3154 // should redeclare it.
3155 NamedDecl *NonTag = 0, *Tag = 0;
3156 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3157 I != E; ++I) {
3158 NamedDecl *D = (*I)->getUnderlyingDecl();
3159 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3160 return false;
3161
3162 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3163 }
3164
John McCall84d87672009-12-10 09:41:52 +00003165 if (Target->isFunctionOrFunctionTemplate()) {
3166 FunctionDecl *FD;
3167 if (isa<FunctionTemplateDecl>(Target))
3168 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3169 else
3170 FD = cast<FunctionDecl>(Target);
3171
3172 NamedDecl *OldDecl = 0;
3173 switch (CheckOverload(FD, Previous, OldDecl)) {
3174 case Ovl_Overload:
3175 return false;
3176
3177 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003178 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003179 break;
3180
3181 // We found a decl with the exact signature.
3182 case Ovl_Match:
3183 if (isa<UsingShadowDecl>(OldDecl)) {
3184 // Silently ignore the possible conflict.
3185 return false;
3186 }
3187
3188 // If we're in a record, we want to hide the target, so we
3189 // return true (without a diagnostic) to tell the caller not to
3190 // build a shadow decl.
3191 if (CurContext->isRecord())
3192 return true;
3193
3194 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003195 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003196 break;
3197 }
3198
3199 Diag(Target->getLocation(), diag::note_using_decl_target);
3200 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3201 return true;
3202 }
3203
3204 // Target is not a function.
3205
John McCall84d87672009-12-10 09:41:52 +00003206 if (isa<TagDecl>(Target)) {
3207 // No conflict between a tag and a non-tag.
3208 if (!Tag) return false;
3209
John McCalle29c5cd2009-12-10 19:51:03 +00003210 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003211 Diag(Target->getLocation(), diag::note_using_decl_target);
3212 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3213 return true;
3214 }
3215
3216 // No conflict between a tag and a non-tag.
3217 if (!NonTag) return false;
3218
John McCalle29c5cd2009-12-10 19:51:03 +00003219 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003220 Diag(Target->getLocation(), diag::note_using_decl_target);
3221 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3222 return true;
3223}
3224
John McCall3f746822009-11-17 05:59:44 +00003225/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003226UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003227 UsingDecl *UD,
3228 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003229
3230 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003231 NamedDecl *Target = Orig;
3232 if (isa<UsingShadowDecl>(Target)) {
3233 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3234 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003235 }
3236
3237 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003238 = UsingShadowDecl::Create(Context, CurContext,
3239 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003240 UD->addShadowDecl(Shadow);
3241
3242 if (S)
John McCall3969e302009-12-08 07:46:18 +00003243 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003244 else
John McCall3969e302009-12-08 07:46:18 +00003245 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003246 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003247
John McCall3969e302009-12-08 07:46:18 +00003248 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3249 Shadow->setInvalidDecl();
3250
John McCall84d87672009-12-10 09:41:52 +00003251 return Shadow;
3252}
John McCall3969e302009-12-08 07:46:18 +00003253
John McCall84d87672009-12-10 09:41:52 +00003254/// Hides a using shadow declaration. This is required by the current
3255/// using-decl implementation when a resolvable using declaration in a
3256/// class is followed by a declaration which would hide or override
3257/// one or more of the using decl's targets; for example:
3258///
3259/// struct Base { void foo(int); };
3260/// struct Derived : Base {
3261/// using Base::foo;
3262/// void foo(int);
3263/// };
3264///
3265/// The governing language is C++03 [namespace.udecl]p12:
3266///
3267/// When a using-declaration brings names from a base class into a
3268/// derived class scope, member functions in the derived class
3269/// override and/or hide member functions with the same name and
3270/// parameter types in a base class (rather than conflicting).
3271///
3272/// There are two ways to implement this:
3273/// (1) optimistically create shadow decls when they're not hidden
3274/// by existing declarations, or
3275/// (2) don't create any shadow decls (or at least don't make them
3276/// visible) until we've fully parsed/instantiated the class.
3277/// The problem with (1) is that we might have to retroactively remove
3278/// a shadow decl, which requires several O(n) operations because the
3279/// decl structures are (very reasonably) not designed for removal.
3280/// (2) avoids this but is very fiddly and phase-dependent.
3281void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3282 // Remove it from the DeclContext...
3283 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003284
John McCall84d87672009-12-10 09:41:52 +00003285 // ...and the scope, if applicable...
3286 if (S) {
3287 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3288 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003289 }
3290
John McCall84d87672009-12-10 09:41:52 +00003291 // ...and the using decl.
3292 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3293
3294 // TODO: complain somehow if Shadow was used. It shouldn't
3295 // be possible for this to happen, because
John McCall3f746822009-11-17 05:59:44 +00003296}
3297
John McCalle61f2ba2009-11-18 02:36:19 +00003298/// Builds a using declaration.
3299///
3300/// \param IsInstantiation - Whether this call arises from an
3301/// instantiation of an unresolved using declaration. We treat
3302/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003303NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3304 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003305 const CXXScopeSpec &SS,
3306 SourceLocation IdentLoc,
3307 DeclarationName Name,
3308 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003309 bool IsInstantiation,
3310 bool IsTypeName,
3311 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003312 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3313 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003314
Anders Carlssonf038fc22009-08-28 05:49:21 +00003315 // FIXME: We ignore attributes for now.
3316 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003317
Anders Carlsson59140b32009-08-28 03:16:11 +00003318 if (SS.isEmpty()) {
3319 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003320 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003321 }
Mike Stump11289f42009-09-09 15:08:12 +00003322
John McCall84d87672009-12-10 09:41:52 +00003323 // Do the redeclaration lookup in the current scope.
3324 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3325 ForRedeclaration);
3326 Previous.setHideTags(false);
3327 if (S) {
3328 LookupName(Previous, S);
3329
3330 // It is really dumb that we have to do this.
3331 LookupResult::Filter F = Previous.makeFilter();
3332 while (F.hasNext()) {
3333 NamedDecl *D = F.next();
3334 if (!isDeclInScope(D, CurContext, S))
3335 F.erase();
3336 }
3337 F.done();
3338 } else {
3339 assert(IsInstantiation && "no scope in non-instantiation");
3340 assert(CurContext->isRecord() && "scope not record in instantiation");
3341 LookupQualifiedName(Previous, CurContext);
3342 }
3343
Mike Stump11289f42009-09-09 15:08:12 +00003344 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003345 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3346
John McCall84d87672009-12-10 09:41:52 +00003347 // Check for invalid redeclarations.
3348 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3349 return 0;
3350
3351 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003352 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3353 return 0;
3354
John McCall84c16cf2009-11-12 03:15:40 +00003355 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003356 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003357 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003358 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003359 // FIXME: not all declaration name kinds are legal here
3360 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3361 UsingLoc, TypenameLoc,
3362 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003363 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003364 } else {
3365 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3366 UsingLoc, SS.getRange(), NNS,
3367 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003368 }
John McCallb96ec562009-12-04 22:46:56 +00003369 } else {
3370 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3371 SS.getRange(), UsingLoc, NNS, Name,
3372 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003373 }
John McCallb96ec562009-12-04 22:46:56 +00003374 D->setAccess(AS);
3375 CurContext->addDecl(D);
3376
3377 if (!LookupContext) return D;
3378 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003379
John McCall3969e302009-12-08 07:46:18 +00003380 if (RequireCompleteDeclContext(SS)) {
3381 UD->setInvalidDecl();
3382 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003383 }
3384
John McCall3969e302009-12-08 07:46:18 +00003385 // Look up the target name.
3386
John McCall27b18f82009-11-17 02:14:36 +00003387 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003388
John McCall3969e302009-12-08 07:46:18 +00003389 // Unlike most lookups, we don't always want to hide tag
3390 // declarations: tag names are visible through the using declaration
3391 // even if hidden by ordinary names, *except* in a dependent context
3392 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003393 if (!IsInstantiation)
3394 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003395
John McCall27b18f82009-11-17 02:14:36 +00003396 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003397
John McCall9f3059a2009-10-09 21:13:30 +00003398 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003399 Diag(IdentLoc, diag::err_no_member)
3400 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003401 UD->setInvalidDecl();
3402 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003403 }
3404
John McCallb96ec562009-12-04 22:46:56 +00003405 if (R.isAmbiguous()) {
3406 UD->setInvalidDecl();
3407 return UD;
3408 }
Mike Stump11289f42009-09-09 15:08:12 +00003409
John McCalle61f2ba2009-11-18 02:36:19 +00003410 if (IsTypeName) {
3411 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003412 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003413 Diag(IdentLoc, diag::err_using_typename_non_type);
3414 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3415 Diag((*I)->getUnderlyingDecl()->getLocation(),
3416 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003417 UD->setInvalidDecl();
3418 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003419 }
3420 } else {
3421 // If we asked for a non-typename and we got a type, error out,
3422 // but only if this is an instantiation of an unresolved using
3423 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003424 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003425 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3426 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003427 UD->setInvalidDecl();
3428 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003429 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003430 }
3431
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003432 // C++0x N2914 [namespace.udecl]p6:
3433 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003434 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003435 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3436 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003437 UD->setInvalidDecl();
3438 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003439 }
Mike Stump11289f42009-09-09 15:08:12 +00003440
John McCall84d87672009-12-10 09:41:52 +00003441 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3442 if (!CheckUsingShadowDecl(UD, *I, Previous))
3443 BuildUsingShadowDecl(S, UD, *I);
3444 }
John McCall3f746822009-11-17 05:59:44 +00003445
3446 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003447}
3448
John McCall84d87672009-12-10 09:41:52 +00003449/// Checks that the given using declaration is not an invalid
3450/// redeclaration. Note that this is checking only for the using decl
3451/// itself, not for any ill-formedness among the UsingShadowDecls.
3452bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3453 bool isTypeName,
3454 const CXXScopeSpec &SS,
3455 SourceLocation NameLoc,
3456 const LookupResult &Prev) {
3457 // C++03 [namespace.udecl]p8:
3458 // C++0x [namespace.udecl]p10:
3459 // A using-declaration is a declaration and can therefore be used
3460 // repeatedly where (and only where) multiple declarations are
3461 // allowed.
3462 // That's only in file contexts.
3463 if (CurContext->getLookupContext()->isFileContext())
3464 return false;
3465
3466 NestedNameSpecifier *Qual
3467 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3468
3469 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3470 NamedDecl *D = *I;
3471
3472 bool DTypename;
3473 NestedNameSpecifier *DQual;
3474 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3475 DTypename = UD->isTypeName();
3476 DQual = UD->getTargetNestedNameDecl();
3477 } else if (UnresolvedUsingValueDecl *UD
3478 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3479 DTypename = false;
3480 DQual = UD->getTargetNestedNameSpecifier();
3481 } else if (UnresolvedUsingTypenameDecl *UD
3482 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3483 DTypename = true;
3484 DQual = UD->getTargetNestedNameSpecifier();
3485 } else continue;
3486
3487 // using decls differ if one says 'typename' and the other doesn't.
3488 // FIXME: non-dependent using decls?
3489 if (isTypeName != DTypename) continue;
3490
3491 // using decls differ if they name different scopes (but note that
3492 // template instantiation can cause this check to trigger when it
3493 // didn't before instantiation).
3494 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3495 Context.getCanonicalNestedNameSpecifier(DQual))
3496 continue;
3497
3498 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003499 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003500 return true;
3501 }
3502
3503 return false;
3504}
3505
John McCall3969e302009-12-08 07:46:18 +00003506
John McCallb96ec562009-12-04 22:46:56 +00003507/// Checks that the given nested-name qualifier used in a using decl
3508/// in the current context is appropriately related to the current
3509/// scope. If an error is found, diagnoses it and returns true.
3510bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3511 const CXXScopeSpec &SS,
3512 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003513 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003514
John McCall3969e302009-12-08 07:46:18 +00003515 if (!CurContext->isRecord()) {
3516 // C++03 [namespace.udecl]p3:
3517 // C++0x [namespace.udecl]p8:
3518 // A using-declaration for a class member shall be a member-declaration.
3519
3520 // If we weren't able to compute a valid scope, it must be a
3521 // dependent class scope.
3522 if (!NamedContext || NamedContext->isRecord()) {
3523 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3524 << SS.getRange();
3525 return true;
3526 }
3527
3528 // Otherwise, everything is known to be fine.
3529 return false;
3530 }
3531
3532 // The current scope is a record.
3533
3534 // If the named context is dependent, we can't decide much.
3535 if (!NamedContext) {
3536 // FIXME: in C++0x, we can diagnose if we can prove that the
3537 // nested-name-specifier does not refer to a base class, which is
3538 // still possible in some cases.
3539
3540 // Otherwise we have to conservatively report that things might be
3541 // okay.
3542 return false;
3543 }
3544
3545 if (!NamedContext->isRecord()) {
3546 // Ideally this would point at the last name in the specifier,
3547 // but we don't have that level of source info.
3548 Diag(SS.getRange().getBegin(),
3549 diag::err_using_decl_nested_name_specifier_is_not_class)
3550 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3551 return true;
3552 }
3553
3554 if (getLangOptions().CPlusPlus0x) {
3555 // C++0x [namespace.udecl]p3:
3556 // In a using-declaration used as a member-declaration, the
3557 // nested-name-specifier shall name a base class of the class
3558 // being defined.
3559
3560 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3561 cast<CXXRecordDecl>(NamedContext))) {
3562 if (CurContext == NamedContext) {
3563 Diag(NameLoc,
3564 diag::err_using_decl_nested_name_specifier_is_current_class)
3565 << SS.getRange();
3566 return true;
3567 }
3568
3569 Diag(SS.getRange().getBegin(),
3570 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3571 << (NestedNameSpecifier*) SS.getScopeRep()
3572 << cast<CXXRecordDecl>(CurContext)
3573 << SS.getRange();
3574 return true;
3575 }
3576
3577 return false;
3578 }
3579
3580 // C++03 [namespace.udecl]p4:
3581 // A using-declaration used as a member-declaration shall refer
3582 // to a member of a base class of the class being defined [etc.].
3583
3584 // Salient point: SS doesn't have to name a base class as long as
3585 // lookup only finds members from base classes. Therefore we can
3586 // diagnose here only if we can prove that that can't happen,
3587 // i.e. if the class hierarchies provably don't intersect.
3588
3589 // TODO: it would be nice if "definitely valid" results were cached
3590 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3591 // need to be repeated.
3592
3593 struct UserData {
3594 llvm::DenseSet<const CXXRecordDecl*> Bases;
3595
3596 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3597 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3598 Data->Bases.insert(Base);
3599 return true;
3600 }
3601
3602 bool hasDependentBases(const CXXRecordDecl *Class) {
3603 return !Class->forallBases(collect, this);
3604 }
3605
3606 /// Returns true if the base is dependent or is one of the
3607 /// accumulated base classes.
3608 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3609 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3610 return !Data->Bases.count(Base);
3611 }
3612
3613 bool mightShareBases(const CXXRecordDecl *Class) {
3614 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3615 }
3616 };
3617
3618 UserData Data;
3619
3620 // Returns false if we find a dependent base.
3621 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3622 return false;
3623
3624 // Returns false if the class has a dependent base or if it or one
3625 // of its bases is present in the base set of the current context.
3626 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3627 return false;
3628
3629 Diag(SS.getRange().getBegin(),
3630 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3631 << (NestedNameSpecifier*) SS.getScopeRep()
3632 << cast<CXXRecordDecl>(CurContext)
3633 << SS.getRange();
3634
3635 return true;
John McCallb96ec562009-12-04 22:46:56 +00003636}
3637
Mike Stump11289f42009-09-09 15:08:12 +00003638Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003639 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003640 SourceLocation AliasLoc,
3641 IdentifierInfo *Alias,
3642 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003643 SourceLocation IdentLoc,
3644 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003645
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003646 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003647 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3648 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003649
Anders Carlssondca83c42009-03-28 06:23:46 +00003650 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003651 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003652 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003653 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003654 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003655 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003656 if (!R.isAmbiguous() && !R.empty() &&
3657 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003658 return DeclPtrTy();
3659 }
Mike Stump11289f42009-09-09 15:08:12 +00003660
Anders Carlssondca83c42009-03-28 06:23:46 +00003661 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3662 diag::err_redefinition_different_kind;
3663 Diag(AliasLoc, DiagID) << Alias;
3664 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003665 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003666 }
3667
John McCall27b18f82009-11-17 02:14:36 +00003668 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003669 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003670
John McCall9f3059a2009-10-09 21:13:30 +00003671 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003672 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003673 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003674 }
Mike Stump11289f42009-09-09 15:08:12 +00003675
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003676 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003677 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3678 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003679 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003680 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003681
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003682 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003683 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003684}
3685
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003686void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3687 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003688 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3689 !Constructor->isUsed()) &&
3690 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003691
Eli Friedman9cf6b592009-11-09 19:20:36 +00003692 CXXRecordDecl *ClassDecl
3693 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3694 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003695
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003696 DeclContext *PreviousContext = CurContext;
3697 CurContext = Constructor;
3698 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003699 Diag(CurrentLocation, diag::note_member_synthesized_at)
3700 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003701 Constructor->setInvalidDecl();
3702 } else {
3703 Constructor->setUsed();
3704 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003705 CurContext = PreviousContext;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003706}
3707
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003708void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003709 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003710 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3711 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003712 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003713 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003714
3715 DeclContext *PreviousContext = CurContext;
3716 CurContext = Destructor;
3717
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003718 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003719 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003720 // implicitly defined, all the implicitly-declared default destructors
3721 // for its base class and its non-static data members shall have been
3722 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003723 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3724 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003725 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003726 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003727 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003728 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003729 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3730 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3731 else
Mike Stump11289f42009-09-09 15:08:12 +00003732 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003733 "DefineImplicitDestructor - missing dtor in a base class");
3734 }
3735 }
Mike Stump11289f42009-09-09 15:08:12 +00003736
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003737 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3738 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003739 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3740 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3741 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003742 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003743 CXXRecordDecl *FieldClassDecl
3744 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3745 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003746 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003747 const_cast<CXXDestructorDecl*>(
3748 FieldClassDecl->getDestructor(Context)))
3749 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3750 else
Mike Stump11289f42009-09-09 15:08:12 +00003751 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003752 "DefineImplicitDestructor - missing dtor in class of a data member");
3753 }
3754 }
3755 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003756
3757 // FIXME: If CheckDestructor fails, we should emit a note about where the
3758 // implicit destructor was needed.
3759 if (CheckDestructor(Destructor)) {
3760 Diag(CurrentLocation, diag::note_member_synthesized_at)
3761 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3762
3763 Destructor->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003764 CurContext = PreviousContext;
3765
Anders Carlsson26a807d2009-11-30 21:24:50 +00003766 return;
3767 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003768 CurContext = PreviousContext;
Anders Carlsson26a807d2009-11-30 21:24:50 +00003769
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003770 Destructor->setUsed();
3771}
3772
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003773void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3774 CXXMethodDecl *MethodDecl) {
3775 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3776 MethodDecl->getOverloadedOperator() == OO_Equal &&
3777 !MethodDecl->isUsed()) &&
3778 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003779
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003780 CXXRecordDecl *ClassDecl
3781 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003782
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003783 DeclContext *PreviousContext = CurContext;
3784 CurContext = MethodDecl;
3785
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003786 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003787 // Before the implicitly-declared copy assignment operator for a class is
3788 // implicitly defined, all implicitly-declared copy assignment operators
3789 // for its direct base classes and its nonstatic data members shall have
3790 // been implicitly defined.
3791 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3793 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003794 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003796 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003797 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3798 BaseClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003799 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3800 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003801 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3802 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003803 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3804 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3805 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003806 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003807 CXXRecordDecl *FieldClassDecl
3808 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003809 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003810 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3811 FieldClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003812 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003813 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003814 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003815 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3816 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003817 Diag(CurrentLocation, diag::note_first_required_here);
3818 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003819 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003820 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003821 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3822 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003823 Diag(CurrentLocation, diag::note_first_required_here);
3824 err = true;
3825 }
3826 }
3827 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003828 MethodDecl->setUsed();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003829
3830 CurContext = PreviousContext;
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003831}
3832
3833CXXMethodDecl *
Anders Carlssonefa47322009-12-09 03:01:51 +00003834Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3835 ParmVarDecl *ParmDecl,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003836 CXXRecordDecl *ClassDecl) {
3837 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3838 QualType RHSType(LHSType);
3839 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003840 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003841 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003842 RHSType = Context.getCVRQualifiedType(RHSType,
3843 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003844 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003845 LHSType,
3846 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003847 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003848 RHSType,
3849 CurrentLocation));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003850 Expr *Args[2] = { &*LHS, &*RHS };
3851 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003852 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003853 CandidateSet);
3854 OverloadCandidateSet::iterator Best;
Anders Carlssonefa47322009-12-09 03:01:51 +00003855 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003856 return cast<CXXMethodDecl>(Best->Function);
3857 assert(false &&
3858 "getAssignOperatorMethod - copy assignment operator method not found");
3859 return 0;
3860}
3861
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003862void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3863 CXXConstructorDecl *CopyConstructor,
3864 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003865 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00003866 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003867 !CopyConstructor->isUsed()) &&
3868 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003869
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003870 CXXRecordDecl *ClassDecl
3871 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3872 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003873
3874 DeclContext *PreviousContext = CurContext;
3875 CurContext = CopyConstructor;
3876
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003877 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003878 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003879 // implicitly defined, all the implicitly-declared copy constructors
3880 // for its base class and its non-static data members shall have been
3881 // implicitly defined.
3882 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3883 Base != ClassDecl->bases_end(); ++Base) {
3884 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003885 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003886 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003887 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003888 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003889 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003890 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3891 FieldEnd = ClassDecl->field_end();
3892 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003893 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3894 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3895 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003896 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003897 CXXRecordDecl *FieldClassDecl
3898 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003899 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003900 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003901 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003902 }
3903 }
3904 CopyConstructor->setUsed();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003905
3906 CurContext = PreviousContext;
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003907}
3908
Anders Carlsson6eb55572009-08-25 05:12:04 +00003909Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003910Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003911 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003912 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003913 bool RequiresZeroInit,
3914 bool BaseInitialization) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003915 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003916
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003917 // C++ [class.copy]p15:
3918 // Whenever a temporary class object is copied using a copy constructor, and
3919 // this object and the copy have the same cv-unqualified type, an
3920 // implementation is permitted to treat the original and the copy as two
3921 // different ways of referring to the same object and not perform a copy at
3922 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003923
Anders Carlsson250aada2009-08-16 05:13:48 +00003924 // FIXME: Is this enough?
Douglas Gregor507eb872009-12-22 00:34:07 +00003925 if (Constructor->isCopyConstructor()) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003926 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregore1314a62009-12-18 05:02:21 +00003927 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3928 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3929 E = ICE->getSubExpr();
Eli Friedmanfddc26c2009-12-24 23:33:34 +00003930 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3931 E = FCE->getSubExpr();
Anders Carlsson250aada2009-08-16 05:13:48 +00003932 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3933 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3935 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3936 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00003937
3938 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3939 Elidable = !CE->getCallReturnType()->isReferenceType();
3940 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00003941 Elidable = true;
Eli Friedmanfddc26c2009-12-24 23:33:34 +00003942 else if (isa<CXXConstructExpr>(E))
3943 Elidable = true;
Anders Carlsson250aada2009-08-16 05:13:48 +00003944 }
Mike Stump11289f42009-09-09 15:08:12 +00003945
3946 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003947 Elidable, move(ExprArgs), RequiresZeroInit,
3948 BaseInitialization);
Anders Carlsson250aada2009-08-16 05:13:48 +00003949}
3950
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003951/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3952/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003953Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003954Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3955 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003956 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003957 bool RequiresZeroInit,
3958 bool BaseInitialization) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003959 unsigned NumExprs = ExprArgs.size();
3960 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003961
Douglas Gregor27381f32009-11-23 12:27:39 +00003962 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003963 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003964 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003965 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003966}
3967
Mike Stump11289f42009-09-09 15:08:12 +00003968bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003969 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003970 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003971 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003972 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003973 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003974 if (TempResult.isInvalid())
3975 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003976
Anders Carlsson6eb55572009-08-25 05:12:04 +00003977 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003978 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00003979 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003980 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003981
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003982 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003983}
3984
John McCall03c48482010-02-02 09:10:11 +00003985void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
3986 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
John McCall6781b052010-02-02 08:45:54 +00003987 if (!ClassDecl->hasTrivialDestructor()) {
3988 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
3989 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall03c48482010-02-02 09:10:11 +00003990 CheckDestructorAccess(VD->getLocation(), Record);
John McCall6781b052010-02-02 08:45:54 +00003991 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003992}
3993
Mike Stump11289f42009-09-09 15:08:12 +00003994/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003995/// ActOnDeclarator, when a C++ direct initializer is present.
3996/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003997void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3998 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003999 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004000 SourceLocation *CommaLocs,
4001 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004002 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004003 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004004
4005 // If there is no declaration, there was an error parsing it. Just ignore
4006 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004007 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004008 return;
Mike Stump11289f42009-09-09 15:08:12 +00004009
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004010 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4011 if (!VDecl) {
4012 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4013 RealDecl->setInvalidDecl();
4014 return;
4015 }
4016
Douglas Gregor402250f2009-08-26 21:14:46 +00004017 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004018 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004019 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4020 //
4021 // Clients that want to distinguish between the two forms, can check for
4022 // direct initializer using VarDecl::hasCXXDirectInitializer().
4023 // A major benefit is that clients that don't particularly care about which
4024 // exactly form was it (like the CodeGen) can handle both cases without
4025 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004026
Douglas Gregor402250f2009-08-26 21:14:46 +00004027 // If either the declaration has a dependent type or if any of the expressions
4028 // is type-dependent, we represent the initialization via a ParenListExpr for
4029 // later use during template instantiation.
4030 if (VDecl->getType()->isDependentType() ||
4031 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4032 // Let clients know that initialization was done with a direct initializer.
4033 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00004034
Douglas Gregor402250f2009-08-26 21:14:46 +00004035 // Store the initialization expressions as a ParenListExpr.
4036 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00004037 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00004038 new (Context) ParenListExpr(Context, LParenLoc,
4039 (Expr **)Exprs.release(),
4040 NumExprs, RParenLoc));
4041 return;
4042 }
Mike Stump11289f42009-09-09 15:08:12 +00004043
Douglas Gregor402250f2009-08-26 21:14:46 +00004044
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004045 // C++ 8.5p11:
4046 // The form of initialization (using parentheses or '=') is generally
4047 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004048 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004049 QualType DeclInitType = VDecl->getType();
4050 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004051 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004052
Douglas Gregor4044d992009-03-24 16:43:20 +00004053 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4054 diag::err_typecheck_decl_incomplete_type)) {
4055 VDecl->setInvalidDecl();
4056 return;
4057 }
4058
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004059 // The variable can not have an abstract class type.
4060 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4061 diag::err_abstract_type_in_decl,
4062 AbstractVariableType))
4063 VDecl->setInvalidDecl();
4064
Sebastian Redl5ca79842010-02-01 20:16:42 +00004065 const VarDecl *Def;
4066 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004067 Diag(VDecl->getLocation(), diag::err_redefinition)
4068 << VDecl->getDeclName();
4069 Diag(Def->getLocation(), diag::note_previous_definition);
4070 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004071 return;
4072 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004073
4074 // Capture the variable that is being initialized and the style of
4075 // initialization.
4076 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4077
4078 // FIXME: Poor source location information.
4079 InitializationKind Kind
4080 = InitializationKind::CreateDirect(VDecl->getLocation(),
4081 LParenLoc, RParenLoc);
4082
4083 InitializationSequence InitSeq(*this, Entity, Kind,
4084 (Expr**)Exprs.get(), Exprs.size());
4085 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4086 if (Result.isInvalid()) {
4087 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004088 return;
4089 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004090
4091 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4092 VDecl->setInit(Context, Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004093 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004094
John McCall03c48482010-02-02 09:10:11 +00004095 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4096 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004097}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004098
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004099/// \brief Add the applicable constructor candidates for an initialization
4100/// by constructor.
4101static void AddConstructorInitializationCandidates(Sema &SemaRef,
4102 QualType ClassType,
4103 Expr **Args,
4104 unsigned NumArgs,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004105 InitializationKind Kind,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004106 OverloadCandidateSet &CandidateSet) {
4107 // C++ [dcl.init]p14:
4108 // If the initialization is direct-initialization, or if it is
4109 // copy-initialization where the cv-unqualified version of the
4110 // source type is the same class as, or a derived class of, the
4111 // class of the destination, constructors are considered. The
4112 // applicable constructors are enumerated (13.3.1.3), and the
4113 // best one is chosen through overload resolution (13.3). The
4114 // constructor so selected is called to initialize the object,
4115 // with the initializer expression(s) as its argument(s). If no
4116 // constructor applies, or the overload resolution is ambiguous,
4117 // the initialization is ill-formed.
4118 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4119 assert(ClassRec && "Can only initialize a class type here");
4120
4121 // FIXME: When we decide not to synthesize the implicitly-declared
4122 // constructors, we'll need to make them appear here.
4123
4124 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4125 DeclarationName ConstructorName
4126 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4127 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4128 DeclContext::lookup_const_iterator Con, ConEnd;
4129 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4130 Con != ConEnd; ++Con) {
4131 // Find the constructor (which may be a template).
4132 CXXConstructorDecl *Constructor = 0;
4133 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4134 if (ConstructorTmpl)
4135 Constructor
4136 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4137 else
4138 Constructor = cast<CXXConstructorDecl>(*Con);
4139
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004140 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4141 (Kind.getKind() == InitializationKind::IK_Value) ||
4142 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004143 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004144 ((Kind.getKind() == InitializationKind::IK_Default) &&
4145 Constructor->isDefaultConstructor())) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004146 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00004147 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCallb89836b2010-01-26 01:37:31 +00004148 ConstructorTmpl->getAccess(),
John McCall6b51f282009-11-23 01:53:49 +00004149 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004150 Args, NumArgs, CandidateSet);
4151 else
John McCallb89836b2010-01-26 01:37:31 +00004152 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4153 Args, NumArgs, CandidateSet);
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004154 }
4155 }
4156}
4157
4158/// \brief Attempt to perform initialization by constructor
4159/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4160/// copy-initialization.
4161///
4162/// This routine determines whether initialization by constructor is possible,
4163/// but it does not emit any diagnostics in the case where the initialization
4164/// is ill-formed.
4165///
4166/// \param ClassType the type of the object being initialized, which must have
4167/// class type.
4168///
4169/// \param Args the arguments provided to initialize the object
4170///
4171/// \param NumArgs the number of arguments provided to initialize the object
4172///
4173/// \param Kind the type of initialization being performed
4174///
4175/// \returns the constructor used to initialize the object, if successful.
4176/// Otherwise, emits a diagnostic and returns NULL.
4177CXXConstructorDecl *
4178Sema::TryInitializationByConstructor(QualType ClassType,
4179 Expr **Args, unsigned NumArgs,
4180 SourceLocation Loc,
4181 InitializationKind Kind) {
4182 // Build the overload candidate set
4183 OverloadCandidateSet CandidateSet;
4184 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4185 CandidateSet);
4186
4187 // Determine whether we found a constructor we can use.
4188 OverloadCandidateSet::iterator Best;
4189 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4190 case OR_Success:
4191 case OR_Deleted:
4192 // We found a constructor. Return it.
4193 return cast<CXXConstructorDecl>(Best->Function);
4194
4195 case OR_No_Viable_Function:
4196 case OR_Ambiguous:
4197 // Overload resolution failed. Return nothing.
4198 return 0;
4199 }
4200
4201 // Silence GCC warning
4202 return 0;
4203}
4204
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004205/// \brief Given a constructor and the set of arguments provided for the
4206/// constructor, convert the arguments and add any required default arguments
4207/// to form a proper call to this constructor.
4208///
4209/// \returns true if an error occurred, false otherwise.
4210bool
4211Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4212 MultiExprArg ArgsPtr,
4213 SourceLocation Loc,
4214 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4215 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4216 unsigned NumArgs = ArgsPtr.size();
4217 Expr **Args = (Expr **)ArgsPtr.get();
4218
4219 const FunctionProtoType *Proto
4220 = Constructor->getType()->getAs<FunctionProtoType>();
4221 assert(Proto && "Constructor without a prototype?");
4222 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004223
4224 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004225 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004226 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004227 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004228 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004229
4230 VariadicCallType CallType =
4231 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4232 llvm::SmallVector<Expr *, 8> AllArgs;
4233 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4234 Proto, 0, Args, NumArgs, AllArgs,
4235 CallType);
4236 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4237 ConvertedArgs.push_back(AllArgs[i]);
4238 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004239}
4240
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004241/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4242/// determine whether they are reference-related,
4243/// reference-compatible, reference-compatible with added
4244/// qualification, or incompatible, for use in C++ initialization by
4245/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4246/// type, and the first type (T1) is the pointee type of the reference
4247/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00004248Sema::ReferenceCompareResult
Chandler Carruth607f38e2009-12-29 07:16:59 +00004249Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004250 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00004251 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004252 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004253 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004254 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004255
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004256 QualType T1 = Context.getCanonicalType(OrigT1);
4257 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004258 Qualifiers T1Quals, T2Quals;
4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004261
4262 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00004264 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004265 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00004266 if (UnqualT1 == UnqualT2)
4267 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004268 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4269 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4270 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00004271 DerivedToBase = true;
4272 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004273 return Ref_Incompatible;
4274
4275 // At this point, we know that T1 and T2 are reference-related (at
4276 // least).
4277
Chandler Carruth607f38e2009-12-29 07:16:59 +00004278 // If the type is an array type, promote the element qualifiers to the type
4279 // for comparison.
4280 if (isa<ArrayType>(T1) && T1Quals)
4281 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4282 if (isa<ArrayType>(T2) && T2Quals)
4283 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4284
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004285 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004286 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004287 // reference-related to T2 and cv1 is the same cv-qualification
4288 // as, or greater cv-qualification than, cv2. For purposes of
4289 // overload resolution, cases for which cv1 is greater
4290 // cv-qualification than cv2 are identified as
4291 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth607f38e2009-12-29 07:16:59 +00004292 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004293 return Ref_Compatible;
4294 else if (T1.isMoreQualifiedThan(T2))
4295 return Ref_Compatible_With_Added_Qualification;
4296 else
4297 return Ref_Related;
4298}
4299
4300/// CheckReferenceInit - Check the initialization of a reference
4301/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4302/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00004303/// list), and DeclType is the type of the declaration. When ICS is
4304/// non-null, this routine will compute the implicit conversion
4305/// sequence according to C++ [over.ics.ref] and will not produce any
4306/// diagnostics; when ICS is null, it will emit diagnostics when any
4307/// errors are found. Either way, a return value of true indicates
4308/// that there was a failure, a return value of false indicates that
4309/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00004310///
4311/// When @p SuppressUserConversions, user-defined conversions are
4312/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004313/// When @p AllowExplicit, we also permit explicit user-defined
4314/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00004315/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00004316/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4317/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00004318bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00004319Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00004320 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004321 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00004322 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00004323 ImplicitConversionSequence *ICS,
4324 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004325 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4326
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004327 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004328 QualType T2 = Init->getType();
4329
Douglas Gregorcd695e52008-11-10 20:40:00 +00004330 // If the initializer is the address of an overloaded function, try
4331 // to resolve the overloaded function. If all goes well, T2 is the
4332 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004333 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00004334 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004335 ICS != 0);
4336 if (Fn) {
4337 // Since we're performing this reference-initialization for
4338 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004339 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00004340 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004341 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004342
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00004343 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004344 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004345
4346 T2 = Fn->getType();
4347 }
4348 }
4349
Douglas Gregor786ab212008-10-29 02:00:59 +00004350 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004351 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00004352 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00004353 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4354 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00004355 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004356 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00004357
4358 // Most paths end in a failed conversion.
John McCall6a61b522010-01-13 09:16:55 +00004359 if (ICS) {
4360 ICS->setBad();
4361 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4362 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004363
4364 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004365 // A reference to type "cv1 T1" is initialized by an expression
4366 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004367
4368 // -- If the initializer expression
4369
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004370 // Rvalue references cannot bind to lvalues (N2812).
4371 // There is absolutely no situation where they can. In particular, note that
4372 // this is ill-formed, even if B has a user-defined conversion to A&&:
4373 // B b;
4374 // A&& r = b;
4375 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4376 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004377 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004378 << Init->getSourceRange();
4379 return true;
4380 }
4381
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004382 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00004383 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4384 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00004385 //
4386 // Note that the bit-field check is skipped if we are just computing
4387 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00004388 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004389 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004390 BindsDirectly = true;
4391
Douglas Gregor786ab212008-10-29 02:00:59 +00004392 if (ICS) {
4393 // C++ [over.ics.ref]p1:
4394 // When a parameter of reference type binds directly (8.5.3)
4395 // to an argument expression, the implicit conversion sequence
4396 // is the identity conversion, unless the argument expression
4397 // has a type that is a derived class of the parameter type,
4398 // in which case the implicit conversion sequence is a
4399 // derived-to-base Conversion (13.3.3.1).
John McCall0d1da222010-01-12 00:44:57 +00004400 ICS->setStandard();
Douglas Gregor786ab212008-10-29 02:00:59 +00004401 ICS->Standard.First = ICK_Identity;
4402 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4403 ICS->Standard.Third = ICK_Identity;
4404 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004405 ICS->Standard.setToType(0, T2);
4406 ICS->Standard.setToType(1, T1);
4407 ICS->Standard.setToType(2, T1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004408 ICS->Standard.ReferenceBinding = true;
4409 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004410 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004411 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004412
4413 // Nothing more to do: the inaccessibility/ambiguity check for
4414 // derived-to-base conversions is suppressed when we're
4415 // computing the implicit conversion sequence (C++
4416 // [over.best.ics]p2).
4417 return false;
4418 } else {
4419 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004420 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4421 if (DerivedToBase)
4422 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004423 else if(CheckExceptionSpecCompatibility(Init, T1))
4424 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004425 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004426 }
4427 }
4428
4429 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00004430 // implicitly converted to an lvalue of type "cv3 T3,"
4431 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004432 // 92) (this conversion is selected by enumerating the
4433 // applicable conversion functions (13.3.1.6) and choosing
4434 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004435 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004436 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00004437 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004438 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004439
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004440 OverloadCandidateSet CandidateSet;
John McCallad371252010-01-20 00:46:10 +00004441 const UnresolvedSetImpl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004442 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004443 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004444 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00004445 NamedDecl *D = *I;
4446 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4447 if (isa<UsingShadowDecl>(D))
4448 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4449
Mike Stump11289f42009-09-09 15:08:12 +00004450 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00004451 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00004452 CXXConversionDecl *Conv;
4453 if (ConvTemplate)
4454 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4455 else
John McCall6e9f8f62009-12-03 04:06:58 +00004456 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004457
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004458 // If the conversion function doesn't return a reference type,
4459 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004460 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00004461 (AllowExplicit || !Conv->isExplicit())) {
4462 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00004463 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall6e9f8f62009-12-03 04:06:58 +00004464 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004465 else
John McCallb89836b2010-01-26 01:37:31 +00004466 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4467 DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004468 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004469 }
4470
4471 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00004472 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004473 case OR_Success:
4474 // This is a direct binding.
4475 BindsDirectly = true;
4476
4477 if (ICS) {
4478 // C++ [over.ics.ref]p1:
4479 //
4480 // [...] If the parameter binds directly to the result of
4481 // applying a conversion function to the argument
4482 // expression, the implicit conversion sequence is a
4483 // user-defined conversion sequence (13.3.3.1.2), with the
4484 // second standard conversion sequence either an identity
4485 // conversion or, if the conversion function returns an
4486 // entity of a type that is a derived class of the parameter
4487 // type, a derived-to-base Conversion.
John McCall0d1da222010-01-12 00:44:57 +00004488 ICS->setUserDefined();
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004489 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4490 ICS->UserDefined.After = Best->FinalConversion;
4491 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004492 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004493 assert(ICS->UserDefined.After.ReferenceBinding &&
4494 ICS->UserDefined.After.DirectBinding &&
4495 "Expected a direct reference binding!");
4496 return false;
4497 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004498 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004499 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004500 CastExpr::CK_UserDefinedConversion,
4501 cast<CXXMethodDecl>(Best->Function),
4502 Owned(Init));
4503 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004504
4505 if (CheckExceptionSpecCompatibility(Init, T1))
4506 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004507 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4508 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004509 }
4510 break;
4511
4512 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004513 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004514 ICS->setAmbiguous();
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004515 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4516 Cand != CandidateSet.end(); ++Cand)
4517 if (Cand->Viable)
John McCall0d1da222010-01-12 00:44:57 +00004518 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004519 break;
4520 }
4521 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4522 << Init->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00004523 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004524 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004525
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004526 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004527 case OR_Deleted:
4528 // There was no suitable conversion, or we found a deleted
4529 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004530 break;
4531 }
4532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004534 if (BindsDirectly) {
4535 // C++ [dcl.init.ref]p4:
4536 // [...] In all cases where the reference-related or
4537 // reference-compatible relationship of two types is used to
4538 // establish the validity of a reference binding, and T1 is a
4539 // base class of T2, a program that necessitates such a binding
4540 // is ill-formed if T1 is an inaccessible (clause 11) or
4541 // ambiguous (10.2) base class of T2.
4542 //
4543 // Note that we only check this condition when we're allowed to
4544 // complain about errors, because we should not be checking for
4545 // ambiguity (or inaccessibility) unless the reference binding
4546 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004547 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004548 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004549 Init->getSourceRange(),
4550 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004551 else
4552 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004553 }
4554
4555 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004556 // type (i.e., cv1 shall be const), or the reference shall be an
4557 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004558 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004559 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004560 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregord1e08642010-01-29 19:39:15 +00004561 << T1.isVolatileQualified()
Douglas Gregor906db8a2009-12-15 16:44:32 +00004562 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004563 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004564 return true;
4565 }
4566
4567 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004568 // class type, and "cv1 T1" is reference-compatible with
4569 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004570 // following ways (the choice is implementation-defined):
4571 //
4572 // -- The reference is bound to the object represented by
4573 // the rvalue (see 3.10) or to a sub-object within that
4574 // object.
4575 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004576 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004577 // a constructor is called to copy the entire rvalue
4578 // object into the temporary. The reference is bound to
4579 // the temporary or to a sub-object within the
4580 // temporary.
4581 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004582 // The constructor that would be used to make the copy
4583 // shall be callable whether or not the copy is actually
4584 // done.
4585 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004586 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004587 // freedom, so we will always take the first option and never build
4588 // a temporary in this case. FIXME: We will, however, have to check
4589 // for the presence of a copy constructor in C++98/03 mode.
4590 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004591 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4592 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004593 ICS->setStandard();
Douglas Gregor786ab212008-10-29 02:00:59 +00004594 ICS->Standard.First = ICK_Identity;
4595 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4596 ICS->Standard.Third = ICK_Identity;
4597 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004598 ICS->Standard.setToType(0, T2);
4599 ICS->Standard.setToType(1, T1);
4600 ICS->Standard.setToType(2, T1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004601 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004602 ICS->Standard.DirectBinding = false;
4603 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004604 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004605 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004606 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4607 if (DerivedToBase)
4608 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004609 else if(CheckExceptionSpecCompatibility(Init, T1))
4610 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004611 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004612 }
4613 return false;
4614 }
4615
Eli Friedman44b83ee2009-08-05 19:21:58 +00004616 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004617 // initialized from the initializer expression using the
4618 // rules for a non-reference copy initialization (8.5). The
4619 // reference is then bound to the temporary. If T1 is
4620 // reference-related to T2, cv1 must be the same
4621 // cv-qualification as, or greater cv-qualification than,
4622 // cv2; otherwise, the program is ill-formed.
4623 if (RefRelationship == Ref_Related) {
4624 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4625 // we would be reference-compatible or reference-compatible with
4626 // added qualification. But that wasn't the case, so the reference
4627 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004628 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004629 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor906db8a2009-12-15 16:44:32 +00004630 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004631 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004632 return true;
4633 }
4634
Douglas Gregor576e98c2009-01-30 23:27:23 +00004635 // If at least one of the types is a class type, the types are not
4636 // related, and we aren't allowed any user conversions, the
4637 // reference binding fails. This case is important for breaking
4638 // recursion, since TryImplicitConversion below will attempt to
4639 // create a temporary through the use of a copy constructor.
4640 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4641 (T1->isRecordType() || T2->isRecordType())) {
4642 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004643 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004644 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor576e98c2009-01-30 23:27:23 +00004645 return true;
4646 }
4647
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004648 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004649 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004650 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004651 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004652 // When a parameter of reference type is not bound directly to
4653 // an argument expression, the conversion sequence is the one
4654 // required to convert the argument expression to the
4655 // underlying type of the reference according to
4656 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4657 // to copy-initializing a temporary of the underlying type with
4658 // the argument expression. Any difference in top-level
4659 // cv-qualification is subsumed by the initialization itself
4660 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004661 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4662 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004663 /*ForceRValue=*/false,
4664 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004665
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004666 // Of course, that's still a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004667 if (ICS->isStandard()) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004668 ICS->Standard.ReferenceBinding = true;
4669 ICS->Standard.RRefBinding = isRValRef;
John McCall0d1da222010-01-12 00:44:57 +00004670 } else if (ICS->isUserDefined()) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004671 ICS->UserDefined.After.ReferenceBinding = true;
4672 ICS->UserDefined.After.RRefBinding = isRValRef;
4673 }
John McCall0d1da222010-01-12 00:44:57 +00004674 return ICS->isBad();
Douglas Gregor786ab212008-10-29 02:00:59 +00004675 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004676 ImplicitConversionSequence Conversions;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004677 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004678 false, false,
4679 Conversions);
4680 if (badConversion) {
John McCall0d1da222010-01-12 00:44:57 +00004681 if (Conversions.isAmbiguous()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004682 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004683 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall0d1da222010-01-12 00:44:57 +00004684 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004685 j >= 0; j--) {
John McCall0d1da222010-01-12 00:44:57 +00004686 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallfd0b2f82010-01-06 09:43:14 +00004687 NoteOverloadCandidate(Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004688 }
4689 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004690 else {
4691 if (isRValRef)
4692 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4693 << Init->getSourceRange();
4694 else
4695 Diag(DeclLoc, diag::err_invalid_initialization)
4696 << DeclType << Init->getType() << Init->getSourceRange();
4697 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004698 }
4699 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004700 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004701}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004702
Anders Carlssone363c8e2009-12-12 00:32:00 +00004703static inline bool
4704CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4705 const FunctionDecl *FnDecl) {
4706 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4707 if (isa<NamespaceDecl>(DC)) {
4708 return SemaRef.Diag(FnDecl->getLocation(),
4709 diag::err_operator_new_delete_declared_in_namespace)
4710 << FnDecl->getDeclName();
4711 }
4712
4713 if (isa<TranslationUnitDecl>(DC) &&
4714 FnDecl->getStorageClass() == FunctionDecl::Static) {
4715 return SemaRef.Diag(FnDecl->getLocation(),
4716 diag::err_operator_new_delete_declared_static)
4717 << FnDecl->getDeclName();
4718 }
4719
Anders Carlsson60659a82009-12-12 02:43:16 +00004720 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004721}
4722
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004723static inline bool
4724CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4725 CanQualType ExpectedResultType,
4726 CanQualType ExpectedFirstParamType,
4727 unsigned DependentParamTypeDiag,
4728 unsigned InvalidParamTypeDiag) {
4729 QualType ResultType =
4730 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4731
4732 // Check that the result type is not dependent.
4733 if (ResultType->isDependentType())
4734 return SemaRef.Diag(FnDecl->getLocation(),
4735 diag::err_operator_new_delete_dependent_result_type)
4736 << FnDecl->getDeclName() << ExpectedResultType;
4737
4738 // Check that the result type is what we expect.
4739 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4740 return SemaRef.Diag(FnDecl->getLocation(),
4741 diag::err_operator_new_delete_invalid_result_type)
4742 << FnDecl->getDeclName() << ExpectedResultType;
4743
4744 // A function template must have at least 2 parameters.
4745 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4746 return SemaRef.Diag(FnDecl->getLocation(),
4747 diag::err_operator_new_delete_template_too_few_parameters)
4748 << FnDecl->getDeclName();
4749
4750 // The function decl must have at least 1 parameter.
4751 if (FnDecl->getNumParams() == 0)
4752 return SemaRef.Diag(FnDecl->getLocation(),
4753 diag::err_operator_new_delete_too_few_parameters)
4754 << FnDecl->getDeclName();
4755
4756 // Check the the first parameter type is not dependent.
4757 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4758 if (FirstParamType->isDependentType())
4759 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4760 << FnDecl->getDeclName() << ExpectedFirstParamType;
4761
4762 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004763 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004764 ExpectedFirstParamType)
4765 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4766 << FnDecl->getDeclName() << ExpectedFirstParamType;
4767
4768 return false;
4769}
4770
Anders Carlsson12308f42009-12-11 23:23:22 +00004771static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004772CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004773 // C++ [basic.stc.dynamic.allocation]p1:
4774 // A program is ill-formed if an allocation function is declared in a
4775 // namespace scope other than global scope or declared static in global
4776 // scope.
4777 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4778 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004779
4780 CanQualType SizeTy =
4781 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4782
4783 // C++ [basic.stc.dynamic.allocation]p1:
4784 // The return type shall be void*. The first parameter shall have type
4785 // std::size_t.
4786 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4787 SizeTy,
4788 diag::err_operator_new_dependent_param_type,
4789 diag::err_operator_new_param_type))
4790 return true;
4791
4792 // C++ [basic.stc.dynamic.allocation]p1:
4793 // The first parameter shall not have an associated default argument.
4794 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004795 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004796 diag::err_operator_new_default_arg)
4797 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4798
4799 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004800}
4801
4802static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004803CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4804 // C++ [basic.stc.dynamic.deallocation]p1:
4805 // A program is ill-formed if deallocation functions are declared in a
4806 // namespace scope other than global scope or declared static in global
4807 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004808 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4809 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004810
4811 // C++ [basic.stc.dynamic.deallocation]p2:
4812 // Each deallocation function shall return void and its first parameter
4813 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004814 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4815 SemaRef.Context.VoidPtrTy,
4816 diag::err_operator_delete_dependent_param_type,
4817 diag::err_operator_delete_param_type))
4818 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004819
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004820 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4821 if (FirstParamType->isDependentType())
4822 return SemaRef.Diag(FnDecl->getLocation(),
4823 diag::err_operator_delete_dependent_param_type)
4824 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4825
4826 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4827 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00004828 return SemaRef.Diag(FnDecl->getLocation(),
4829 diag::err_operator_delete_param_type)
4830 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00004831
4832 return false;
4833}
4834
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004835/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4836/// of this overloaded operator is well-formed. If so, returns false;
4837/// otherwise, emits appropriate diagnostics and returns true.
4838bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004839 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004840 "Expected an overloaded operator declaration");
4841
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004842 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4843
Mike Stump11289f42009-09-09 15:08:12 +00004844 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004845 // The allocation and deallocation functions, operator new,
4846 // operator new[], operator delete and operator delete[], are
4847 // described completely in 3.7.3. The attributes and restrictions
4848 // found in the rest of this subclause do not apply to them unless
4849 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00004850 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00004851 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004852
Anders Carlsson22f443f2009-12-12 00:26:23 +00004853 if (Op == OO_New || Op == OO_Array_New)
4854 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004855
4856 // C++ [over.oper]p6:
4857 // An operator function shall either be a non-static member
4858 // function or be a non-member function and have at least one
4859 // parameter whose type is a class, a reference to a class, an
4860 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004861 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4862 if (MethodDecl->isStatic())
4863 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004864 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004865 } else {
4866 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004867 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4868 ParamEnd = FnDecl->param_end();
4869 Param != ParamEnd; ++Param) {
4870 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004871 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4872 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004873 ClassOrEnumParam = true;
4874 break;
4875 }
4876 }
4877
Douglas Gregord69246b2008-11-17 16:14:12 +00004878 if (!ClassOrEnumParam)
4879 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004880 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004881 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004882 }
4883
4884 // C++ [over.oper]p8:
4885 // An operator function cannot have default arguments (8.3.6),
4886 // except where explicitly stated below.
4887 //
Mike Stump11289f42009-09-09 15:08:12 +00004888 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004889 // (C++ [over.call]p1).
4890 if (Op != OO_Call) {
4891 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4892 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004893 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004894 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004895 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004896 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004897 }
4898 }
4899
Douglas Gregor6cf08062008-11-10 13:38:07 +00004900 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4901 { false, false, false }
4902#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4903 , { Unary, Binary, MemberOnly }
4904#include "clang/Basic/OperatorKinds.def"
4905 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004906
Douglas Gregor6cf08062008-11-10 13:38:07 +00004907 bool CanBeUnaryOperator = OperatorUses[Op][0];
4908 bool CanBeBinaryOperator = OperatorUses[Op][1];
4909 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004910
4911 // C++ [over.oper]p8:
4912 // [...] Operator functions cannot have more or fewer parameters
4913 // than the number required for the corresponding operator, as
4914 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004915 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004916 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004917 if (Op != OO_Call &&
4918 ((NumParams == 1 && !CanBeUnaryOperator) ||
4919 (NumParams == 2 && !CanBeBinaryOperator) ||
4920 (NumParams < 1) || (NumParams > 2))) {
4921 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004922 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004923 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004924 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004925 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004926 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004927 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004928 assert(CanBeBinaryOperator &&
4929 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004930 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004931 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004932
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004933 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004934 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004935 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004936
Douglas Gregord69246b2008-11-17 16:14:12 +00004937 // Overloaded operators other than operator() cannot be variadic.
4938 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004939 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004940 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004941 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004942 }
4943
4944 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004945 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4946 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004947 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004948 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004949 }
4950
4951 // C++ [over.inc]p1:
4952 // The user-defined function called operator++ implements the
4953 // prefix and postfix ++ operator. If this function is a member
4954 // function with no parameters, or a non-member function with one
4955 // parameter of class or enumeration type, it defines the prefix
4956 // increment operator ++ for objects of that type. If the function
4957 // is a member function with one parameter (which shall be of type
4958 // int) or a non-member function with two parameters (the second
4959 // of which shall be of type int), it defines the postfix
4960 // increment operator ++ for objects of that type.
4961 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4962 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4963 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004964 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004965 ParamIsInt = BT->getKind() == BuiltinType::Int;
4966
Chris Lattner2b786902008-11-21 07:50:02 +00004967 if (!ParamIsInt)
4968 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004969 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004970 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004971 }
4972
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004973 // Notify the class if it got an assignment operator.
4974 if (Op == OO_Equal) {
4975 // Would have returned earlier otherwise.
4976 assert(isa<CXXMethodDecl>(FnDecl) &&
4977 "Overloaded = not member, but not filtered.");
4978 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4979 Method->getParent()->addedAssignmentOperator(Context, Method);
4980 }
4981
Douglas Gregord69246b2008-11-17 16:14:12 +00004982 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004983}
Chris Lattner3b024a32008-12-17 07:09:26 +00004984
Alexis Huntc88db062010-01-13 09:01:02 +00004985/// CheckLiteralOperatorDeclaration - Check whether the declaration
4986/// of this literal operator function is well-formed. If so, returns
4987/// false; otherwise, emits appropriate diagnostics and returns true.
4988bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4989 DeclContext *DC = FnDecl->getDeclContext();
4990 Decl::Kind Kind = DC->getDeclKind();
4991 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4992 Kind != Decl::LinkageSpec) {
4993 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4994 << FnDecl->getDeclName();
4995 return true;
4996 }
4997
4998 bool Valid = false;
4999
5000 // FIXME: Check for the one valid template signature
5001 // template <char...> type operator "" name();
5002
5003 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5004 // Check the first parameter
5005 QualType T = (*Param)->getType();
5006
5007 // unsigned long long int and long double are allowed, but only
5008 // alone.
5009 // We also allow any character type; their omission seems to be a bug
5010 // in n3000
5011 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5012 Context.hasSameType(T, Context.LongDoubleTy) ||
5013 Context.hasSameType(T, Context.CharTy) ||
5014 Context.hasSameType(T, Context.WCharTy) ||
5015 Context.hasSameType(T, Context.Char16Ty) ||
5016 Context.hasSameType(T, Context.Char32Ty)) {
5017 if (++Param == FnDecl->param_end())
5018 Valid = true;
5019 goto FinishedParams;
5020 }
5021
5022 // Otherwise it must be a pointer to const; let's strip those.
5023 const PointerType *PT = T->getAs<PointerType>();
5024 if (!PT)
5025 goto FinishedParams;
5026 T = PT->getPointeeType();
5027 if (!T.isConstQualified())
5028 goto FinishedParams;
5029 T = T.getUnqualifiedType();
5030
5031 // Move on to the second parameter;
5032 ++Param;
5033
5034 // If there is no second parameter, the first must be a const char *
5035 if (Param == FnDecl->param_end()) {
5036 if (Context.hasSameType(T, Context.CharTy))
5037 Valid = true;
5038 goto FinishedParams;
5039 }
5040
5041 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5042 // are allowed as the first parameter to a two-parameter function
5043 if (!(Context.hasSameType(T, Context.CharTy) ||
5044 Context.hasSameType(T, Context.WCharTy) ||
5045 Context.hasSameType(T, Context.Char16Ty) ||
5046 Context.hasSameType(T, Context.Char32Ty)))
5047 goto FinishedParams;
5048
5049 // The second and final parameter must be an std::size_t
5050 T = (*Param)->getType().getUnqualifiedType();
5051 if (Context.hasSameType(T, Context.getSizeType()) &&
5052 ++Param == FnDecl->param_end())
5053 Valid = true;
5054 }
5055
5056 // FIXME: This diagnostic is absolutely terrible.
5057FinishedParams:
5058 if (!Valid) {
5059 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5060 << FnDecl->getDeclName();
5061 return true;
5062 }
5063
5064 return false;
5065}
5066
Douglas Gregor07665a62009-01-05 19:45:36 +00005067/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5068/// linkage specification, including the language and (if present)
5069/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5070/// the location of the language string literal, which is provided
5071/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5072/// the '{' brace. Otherwise, this linkage specification does not
5073/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005074Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5075 SourceLocation ExternLoc,
5076 SourceLocation LangLoc,
5077 const char *Lang,
5078 unsigned StrSize,
5079 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005080 LinkageSpecDecl::LanguageIDs Language;
5081 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5082 Language = LinkageSpecDecl::lang_c;
5083 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5084 Language = LinkageSpecDecl::lang_cxx;
5085 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005086 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005087 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005088 }
Mike Stump11289f42009-09-09 15:08:12 +00005089
Chris Lattner438e5012008-12-17 07:13:27 +00005090 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005091
Douglas Gregor07665a62009-01-05 19:45:36 +00005092 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005093 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005094 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005095 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005096 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005097 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005098}
5099
Douglas Gregor07665a62009-01-05 19:45:36 +00005100/// ActOnFinishLinkageSpecification - Completely the definition of
5101/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5102/// valid, it's the position of the closing '}' brace in a linkage
5103/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005104Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5105 DeclPtrTy LinkageSpec,
5106 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005107 if (LinkageSpec)
5108 PopDeclContext();
5109 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005110}
5111
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005112/// \brief Perform semantic analysis for the variable declaration that
5113/// occurs within a C++ catch clause, returning the newly-created
5114/// variable.
5115VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005116 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005117 IdentifierInfo *Name,
5118 SourceLocation Loc,
5119 SourceRange Range) {
5120 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005121
5122 // Arrays and functions decay.
5123 if (ExDeclType->isArrayType())
5124 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5125 else if (ExDeclType->isFunctionType())
5126 ExDeclType = Context.getPointerType(ExDeclType);
5127
5128 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5129 // The exception-declaration shall not denote a pointer or reference to an
5130 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005131 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005132 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005133 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005134 Invalid = true;
5135 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005136
Sebastian Redl54c04d42008-12-22 19:15:10 +00005137 QualType BaseType = ExDeclType;
5138 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005139 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005140 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005141 BaseType = Ptr->getPointeeType();
5142 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00005143 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00005144 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005145 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005146 BaseType = Ref->getPointeeType();
5147 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00005148 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005149 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005150 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005151 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00005152 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005153
Mike Stump11289f42009-09-09 15:08:12 +00005154 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005155 RequireNonAbstractType(Loc, ExDeclType,
5156 diag::err_abstract_type_in_decl,
5157 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005158 Invalid = true;
5159
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005160 // FIXME: Need to test for ability to copy-construct and destroy the
5161 // exception variable.
5162
Sebastian Redl9b244a82008-12-22 21:35:02 +00005163 // FIXME: Need to check for abstract classes.
5164
Mike Stump11289f42009-09-09 15:08:12 +00005165 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00005166 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005167
5168 if (Invalid)
5169 ExDecl->setInvalidDecl();
5170
5171 return ExDecl;
5172}
5173
5174/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5175/// handler.
5176Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005177 TypeSourceInfo *TInfo = 0;
5178 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005179
5180 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005181 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00005182 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005183 // The scope should be freshly made just for us. There is just no way
5184 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005185 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005186 if (PrevDecl->isTemplateParameter()) {
5187 // Maybe we will complain about the shadowed template parameter.
5188 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005189 }
5190 }
5191
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005192 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005193 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5194 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005195 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005196 }
5197
John McCallbcd03502009-12-07 02:54:59 +00005198 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005199 D.getIdentifier(),
5200 D.getIdentifierLoc(),
5201 D.getDeclSpec().getSourceRange());
5202
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005203 if (Invalid)
5204 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005205
Sebastian Redl54c04d42008-12-22 19:15:10 +00005206 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005207 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005208 PushOnScopeChains(ExDecl, S);
5209 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005210 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005211
Douglas Gregor758a8692009-06-17 21:51:59 +00005212 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005213 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005214}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005215
Mike Stump11289f42009-09-09 15:08:12 +00005216Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005217 ExprArg assertexpr,
5218 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005219 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005220 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005221 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5222
Anders Carlsson54b26982009-03-14 00:33:21 +00005223 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5224 llvm::APSInt Value(32);
5225 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5226 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5227 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005228 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005229 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005230
Anders Carlsson54b26982009-03-14 00:33:21 +00005231 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005232 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005233 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005234 }
5235 }
Mike Stump11289f42009-09-09 15:08:12 +00005236
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005237 assertexpr.release();
5238 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005239 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005240 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005241
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005242 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005243 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005244}
Sebastian Redlf769df52009-03-24 22:27:57 +00005245
John McCall11083da2009-09-16 22:47:08 +00005246/// Handle a friend type declaration. This works in tandem with
5247/// ActOnTag.
5248///
5249/// Notes on friend class templates:
5250///
5251/// We generally treat friend class declarations as if they were
5252/// declaring a class. So, for example, the elaborated type specifier
5253/// in a friend declaration is required to obey the restrictions of a
5254/// class-head (i.e. no typedefs in the scope chain), template
5255/// parameters are required to match up with simple template-ids, &c.
5256/// However, unlike when declaring a template specialization, it's
5257/// okay to refer to a template specialization without an empty
5258/// template parameter declaration, e.g.
5259/// friend class A<T>::B<unsigned>;
5260/// We permit this as a special case; if there are any template
5261/// parameters present at all, require proper matching, i.e.
5262/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005263Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005264 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005265 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005266
5267 assert(DS.isFriendSpecified());
5268 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5269
John McCall11083da2009-09-16 22:47:08 +00005270 // Try to convert the decl specifier to a type. This works for
5271 // friend templates because ActOnTag never produces a ClassTemplateDecl
5272 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005273 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005274 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5275 if (TheDeclarator.isInvalidType())
5276 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005277
John McCall11083da2009-09-16 22:47:08 +00005278 // This is definitely an error in C++98. It's probably meant to
5279 // be forbidden in C++0x, too, but the specification is just
5280 // poorly written.
5281 //
5282 // The problem is with declarations like the following:
5283 // template <T> friend A<T>::foo;
5284 // where deciding whether a class C is a friend or not now hinges
5285 // on whether there exists an instantiation of A that causes
5286 // 'foo' to equal C. There are restrictions on class-heads
5287 // (which we declare (by fiat) elaborated friend declarations to
5288 // be) that makes this tractable.
5289 //
5290 // FIXME: handle "template <> friend class A<T>;", which
5291 // is possibly well-formed? Who even knows?
5292 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5293 Diag(Loc, diag::err_tagless_friend_type_template)
5294 << DS.getSourceRange();
5295 return DeclPtrTy();
5296 }
5297
John McCallaa74a0c2009-08-28 07:59:38 +00005298 // C++ [class.friend]p2:
5299 // An elaborated-type-specifier shall be used in a friend declaration
5300 // for a class.*
5301 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00005302 // This is one of the rare places in Clang where it's legitimate to
5303 // ask about the "spelling" of the type.
5304 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5305 // If we evaluated the type to a record type, suggest putting
5306 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00005307 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00005308 RecordDecl *RD = RT->getDecl();
5309
5310 std::string InsertionText = std::string(" ") + RD->getKindName();
5311
John McCallc3987482009-10-07 23:34:25 +00005312 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5313 << (unsigned) RD->getTagKind()
5314 << T
5315 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00005316 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5317 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00005318 return DeclPtrTy();
5319 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00005320 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5321 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005322 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00005323 }
5324 }
5325
John McCallc3987482009-10-07 23:34:25 +00005326 // Enum types cannot be friends.
5327 if (T->getAs<EnumType>()) {
5328 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5329 << SourceRange(DS.getFriendSpecLoc());
5330 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00005331 }
John McCallaa74a0c2009-08-28 07:59:38 +00005332
John McCallaa74a0c2009-08-28 07:59:38 +00005333 // C++98 [class.friend]p1: A friend of a class is a function
5334 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005335 // This is fixed in DR77, which just barely didn't make the C++03
5336 // deadline. It's also a very silly restriction that seriously
5337 // affects inner classes and which nobody else seems to implement;
5338 // thus we never diagnose it, not even in -pedantic.
John McCallaa74a0c2009-08-28 07:59:38 +00005339
John McCall11083da2009-09-16 22:47:08 +00005340 Decl *D;
5341 if (TempParams.size())
5342 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5343 TempParams.size(),
5344 (TemplateParameterList**) TempParams.release(),
5345 T.getTypePtr(),
5346 DS.getFriendSpecLoc());
5347 else
5348 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5349 DS.getFriendSpecLoc());
5350 D->setAccess(AS_public);
5351 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005352
John McCall11083da2009-09-16 22:47:08 +00005353 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005354}
5355
John McCall2f212b32009-09-11 21:02:39 +00005356Sema::DeclPtrTy
5357Sema::ActOnFriendFunctionDecl(Scope *S,
5358 Declarator &D,
5359 bool IsDefinition,
5360 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005361 const DeclSpec &DS = D.getDeclSpec();
5362
5363 assert(DS.isFriendSpecified());
5364 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5365
5366 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005367 TypeSourceInfo *TInfo = 0;
5368 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005369
5370 // C++ [class.friend]p1
5371 // A friend of a class is a function or class....
5372 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005373 // It *doesn't* see through dependent types, which is correct
5374 // according to [temp.arg.type]p3:
5375 // If a declaration acquires a function type through a
5376 // type dependent on a template-parameter and this causes
5377 // a declaration that does not use the syntactic form of a
5378 // function declarator to have a function type, the program
5379 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005380 if (!T->isFunctionType()) {
5381 Diag(Loc, diag::err_unexpected_friend);
5382
5383 // It might be worthwhile to try to recover by creating an
5384 // appropriate declaration.
5385 return DeclPtrTy();
5386 }
5387
5388 // C++ [namespace.memdef]p3
5389 // - If a friend declaration in a non-local class first declares a
5390 // class or function, the friend class or function is a member
5391 // of the innermost enclosing namespace.
5392 // - The name of the friend is not found by simple name lookup
5393 // until a matching declaration is provided in that namespace
5394 // scope (either before or after the class declaration granting
5395 // friendship).
5396 // - If a friend function is called, its name may be found by the
5397 // name lookup that considers functions from namespaces and
5398 // classes associated with the types of the function arguments.
5399 // - When looking for a prior declaration of a class or a function
5400 // declared as a friend, scopes outside the innermost enclosing
5401 // namespace scope are not considered.
5402
John McCallaa74a0c2009-08-28 07:59:38 +00005403 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5404 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005405 assert(Name);
5406
John McCall07e91c02009-08-06 02:15:43 +00005407 // The context we found the declaration in, or in which we should
5408 // create the declaration.
5409 DeclContext *DC;
5410
5411 // FIXME: handle local classes
5412
5413 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005414 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5415 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005416 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005417 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00005418 DC = computeDeclContext(ScopeQual);
5419
5420 // FIXME: handle dependent contexts
5421 if (!DC) return DeclPtrTy();
5422
John McCall1f82f242009-11-18 22:49:29 +00005423 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005424
5425 // If searching in that context implicitly found a declaration in
5426 // a different context, treat it like it wasn't found at all.
5427 // TODO: better diagnostics for this case. Suggesting the right
5428 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005429 // FIXME: getRepresentativeDecl() is not right here at all
5430 if (Previous.empty() ||
5431 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005432 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005433 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5434 return DeclPtrTy();
5435 }
5436
5437 // C++ [class.friend]p1: A friend of a class is a function or
5438 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005439 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005440 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5441
John McCall07e91c02009-08-06 02:15:43 +00005442 // Otherwise walk out to the nearest namespace scope looking for matches.
5443 } else {
5444 // TODO: handle local class contexts.
5445
5446 DC = CurContext;
5447 while (true) {
5448 // Skip class contexts. If someone can cite chapter and verse
5449 // for this behavior, that would be nice --- it's what GCC and
5450 // EDG do, and it seems like a reasonable intent, but the spec
5451 // really only says that checks for unqualified existing
5452 // declarations should stop at the nearest enclosing namespace,
5453 // not that they should only consider the nearest enclosing
5454 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005455 while (DC->isRecord())
5456 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005457
John McCall1f82f242009-11-18 22:49:29 +00005458 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005459
5460 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005461 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005462 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005463
John McCall07e91c02009-08-06 02:15:43 +00005464 if (DC->isFileContext()) break;
5465 DC = DC->getParent();
5466 }
5467
5468 // C++ [class.friend]p1: A friend of a class is a function or
5469 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005470 // C++0x changes this for both friend types and functions.
5471 // Most C++ 98 compilers do seem to give an error here, so
5472 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005473 if (!Previous.empty() && DC->Equals(CurContext)
5474 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005475 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5476 }
5477
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005478 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005479 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005480 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5481 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5482 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005483 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005484 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5485 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005486 return DeclPtrTy();
5487 }
John McCall07e91c02009-08-06 02:15:43 +00005488 }
5489
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005490 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005491 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005492 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005493 IsDefinition,
5494 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005495 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005496
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005497 assert(ND->getDeclContext() == DC);
5498 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005499
John McCall759e32b2009-08-31 22:39:49 +00005500 // Add the function declaration to the appropriate lookup tables,
5501 // adjusting the redeclarations list as necessary. We don't
5502 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005503 //
John McCall759e32b2009-08-31 22:39:49 +00005504 // Also update the scope-based lookup if the target context's
5505 // lookup context is in lexical scope.
5506 if (!CurContext->isDependentContext()) {
5507 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005508 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005509 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005510 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005511 }
John McCallaa74a0c2009-08-28 07:59:38 +00005512
5513 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005514 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005515 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005516 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005517 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005518
Douglas Gregor33636e62009-12-24 20:56:24 +00005519 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5520 FrD->setSpecialization(true);
5521
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005522 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005523}
5524
Chris Lattner83f095c2009-03-28 19:18:32 +00005525void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005526 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005527
Chris Lattner83f095c2009-03-28 19:18:32 +00005528 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005529 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5530 if (!Fn) {
5531 Diag(DelLoc, diag::err_deleted_non_function);
5532 return;
5533 }
5534 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5535 Diag(DelLoc, diag::err_deleted_decl_not_first);
5536 Diag(Prev->getLocation(), diag::note_previous_declaration);
5537 // If the declaration wasn't the first, we delete the function anyway for
5538 // recovery.
5539 }
5540 Fn->setDeleted();
5541}
Sebastian Redl4c018662009-04-27 21:33:24 +00005542
5543static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5544 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5545 ++CI) {
5546 Stmt *SubStmt = *CI;
5547 if (!SubStmt)
5548 continue;
5549 if (isa<ReturnStmt>(SubStmt))
5550 Self.Diag(SubStmt->getSourceRange().getBegin(),
5551 diag::err_return_in_constructor_handler);
5552 if (!isa<Expr>(SubStmt))
5553 SearchForReturnInStmt(Self, SubStmt);
5554 }
5555}
5556
5557void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5558 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5559 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5560 SearchForReturnInStmt(*this, Handler);
5561 }
5562}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005563
Mike Stump11289f42009-09-09 15:08:12 +00005564bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005565 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005566 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5567 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005568
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005569 if (Context.hasSameType(NewTy, OldTy))
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005570 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005571
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005572 // Check if the return types are covariant
5573 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005574
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005575 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005576 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5577 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005578 NewClassTy = NewPT->getPointeeType();
5579 OldClassTy = OldPT->getPointeeType();
5580 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005581 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5582 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5583 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5584 NewClassTy = NewRT->getPointeeType();
5585 OldClassTy = OldRT->getPointeeType();
5586 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005587 }
5588 }
Mike Stump11289f42009-09-09 15:08:12 +00005589
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005590 // The return types aren't either both pointers or references to a class type.
5591 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005592 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005593 diag::err_different_return_type_for_overriding_virtual_function)
5594 << New->getDeclName() << NewTy << OldTy;
5595 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005596
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005597 return true;
5598 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005599
Anders Carlssone60365b2009-12-31 18:34:24 +00005600 // C++ [class.virtual]p6:
5601 // If the return type of D::f differs from the return type of B::f, the
5602 // class type in the return type of D::f shall be complete at the point of
5603 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005604 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5605 if (!RT->isBeingDefined() &&
5606 RequireCompleteType(New->getLocation(), NewClassTy,
5607 PDiag(diag::err_covariant_return_incomplete)
5608 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005609 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005610 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005611
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005612 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005613 // Check if the new class derives from the old class.
5614 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5615 Diag(New->getLocation(),
5616 diag::err_covariant_return_not_derived)
5617 << New->getDeclName() << NewTy << OldTy;
5618 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5619 return true;
5620 }
Mike Stump11289f42009-09-09 15:08:12 +00005621
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005622 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00005623 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005624 diag::err_covariant_return_inaccessible_base,
5625 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5626 // FIXME: Should this point to the return type?
5627 New->getLocation(), SourceRange(), New->getDeclName())) {
5628 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5629 return true;
5630 }
5631 }
Mike Stump11289f42009-09-09 15:08:12 +00005632
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005633 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005634 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005635 Diag(New->getLocation(),
5636 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005637 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005638 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5639 return true;
5640 };
Mike Stump11289f42009-09-09 15:08:12 +00005641
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005642
5643 // The new class type must have the same or less qualifiers as the old type.
5644 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5645 Diag(New->getLocation(),
5646 diag::err_covariant_return_type_class_type_more_qualified)
5647 << New->getDeclName() << NewTy << OldTy;
5648 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5649 return true;
5650 };
Mike Stump11289f42009-09-09 15:08:12 +00005651
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005652 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005653}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005654
Alexis Hunt96d5c762009-11-21 08:43:09 +00005655bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5656 const CXXMethodDecl *Old)
5657{
5658 if (Old->hasAttr<FinalAttr>()) {
5659 Diag(New->getLocation(), diag::err_final_function_overridden)
5660 << New->getDeclName();
5661 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5662 return true;
5663 }
5664
5665 return false;
5666}
5667
Douglas Gregor21920e372009-12-01 17:24:26 +00005668/// \brief Mark the given method pure.
5669///
5670/// \param Method the method to be marked pure.
5671///
5672/// \param InitRange the source range that covers the "0" initializer.
5673bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5674 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5675 Method->setPure();
5676
5677 // A class is abstract if at least one function is pure virtual.
5678 Method->getParent()->setAbstract(true);
5679 return false;
5680 }
5681
5682 if (!Method->isInvalidDecl())
5683 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5684 << Method->getDeclName() << InitRange;
5685 return true;
5686}
5687
John McCall1f4ee7b2009-12-19 09:28:58 +00005688/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5689/// an initializer for the out-of-line declaration 'Dcl'. The scope
5690/// is a fresh scope pushed for just this purpose.
5691///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005692/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5693/// static data member of class X, names should be looked up in the scope of
5694/// class X.
5695void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005696 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005697 Decl *D = Dcl.getAs<Decl>();
5698 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005699
John McCall1f4ee7b2009-12-19 09:28:58 +00005700 // We should only get called for declarations with scope specifiers, like:
5701 // int foo::bar;
5702 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005703 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005704}
5705
5706/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005707/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005708void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005709 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005710 Decl *D = Dcl.getAs<Decl>();
5711 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005712
John McCall1f4ee7b2009-12-19 09:28:58 +00005713 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005714 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005715}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005716
5717/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5718/// C++ if/switch/while/for statement.
5719/// e.g: "if (int x = f()) {...}"
5720Action::DeclResult
5721Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5722 // C++ 6.4p2:
5723 // The declarator shall not specify a function or an array.
5724 // The type-specifier-seq shall not contain typedef and shall not declare a
5725 // new class or enumeration.
5726 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5727 "Parser allowed 'typedef' as storage class of condition decl.");
5728
John McCallbcd03502009-12-07 02:54:59 +00005729 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005730 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005731 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005732
5733 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5734 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5735 // would be created and CXXConditionDeclExpr wants a VarDecl.
5736 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5737 << D.getSourceRange();
5738 return DeclResult();
5739 } else if (OwnedTag && OwnedTag->isDefinition()) {
5740 // The type-specifier-seq shall not declare a new class or enumeration.
5741 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5742 }
5743
5744 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5745 if (!Dcl)
5746 return DeclResult();
5747
5748 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5749 VD->setDeclaredInCondition(true);
5750 return Dcl;
5751}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005752
Anders Carlsson82fccd02009-12-07 08:24:59 +00005753void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5754 CXXMethodDecl *MD) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005755 // Ignore dependent types.
5756 if (MD->isDependentContext())
5757 return;
5758
5759 CXXRecordDecl *RD = MD->getParent();
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005760
5761 // Ignore classes without a vtable.
5762 if (!RD->isDynamicClass())
5763 return;
5764
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005765 // Ignore declarations that are not definitions.
5766 if (!MD->isThisDeclarationADefinition())
Anders Carlsson82fccd02009-12-07 08:24:59 +00005767 return;
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005768
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005769 if (isa<CXXConstructorDecl>(MD)) {
5770 switch (MD->getParent()->getTemplateSpecializationKind()) {
5771 case TSK_Undeclared:
5772 case TSK_ExplicitSpecialization:
5773 // Classes that aren't instantiations of templates don't need their
5774 // virtual methods marked until we see the definition of the key
5775 // function.
5776 return;
5777
5778 case TSK_ImplicitInstantiation:
5779 case TSK_ExplicitInstantiationDeclaration:
5780 case TSK_ExplicitInstantiationDefinition:
5781 // This is a constructor of a class template; mark all of the virtual
5782 // members as referenced to ensure that they get instantiatied.
5783 break;
5784 }
5785 } else if (!MD->isOutOfLine()) {
5786 // Consider only out-of-line definitions of member functions. When we see
5787 // an inline definition, it's too early to compute the key function.
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005788 return;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005789 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5790 // If this is not the key function, we don't need to mark virtual members.
5791 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5792 return;
5793 } else {
5794 // The class has no key function, so we've already noted that we need to
5795 // mark the virtual members of this class.
5796 return;
5797 }
5798
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005799 // We will need to mark all of the virtual members as referenced to build the
5800 // vtable.
5801 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlsson82fccd02009-12-07 08:24:59 +00005802}
5803
5804bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5805 if (ClassesWithUnmarkedVirtualMembers.empty())
5806 return false;
5807
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005808 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5809 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5810 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5811 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00005812 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005813 }
5814
Anders Carlsson82fccd02009-12-07 08:24:59 +00005815 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00005816}
Anders Carlsson82fccd02009-12-07 08:24:59 +00005817
5818void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5819 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5820 e = RD->method_end(); i != e; ++i) {
5821 CXXMethodDecl *MD = *i;
5822
5823 // C++ [basic.def.odr]p2:
5824 // [...] A virtual member function is used if it is not pure. [...]
5825 if (MD->isVirtual() && !MD->isPure())
5826 MarkDeclarationReferenced(Loc, MD);
5827 }
5828}
5829