blob: e32d14e1c87c353dc740b7c9b2a2ca863d2c6159 [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
Douglas Gregorf40863c2010-02-12 07:32:17 +0000359 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000360 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000361
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000362 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000363}
364
365/// CheckCXXDefaultArguments - Verify that the default arguments for a
366/// function declaration are well-formed according to C++
367/// [dcl.fct.default].
368void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
369 unsigned NumParams = FD->getNumParams();
370 unsigned p;
371
372 // Find first parameter with a default argument
373 for (p = 0; p < NumParams; ++p) {
374 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000375 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000376 break;
377 }
378
379 // C++ [dcl.fct.default]p4:
380 // In a given function declaration, all parameters
381 // subsequent to a parameter with a default argument shall
382 // have default arguments supplied in this or previous
383 // declarations. A default argument shall not be redefined
384 // by a later declaration (not even to the same value).
385 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000386 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000387 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000388 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 if (Param->isInvalidDecl())
390 /* We already complained about this parameter. */;
391 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000392 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000393 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000394 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000395 else
Mike Stump11289f42009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 LastMissingDefaultArg = p;
400 }
401 }
402
403 if (LastMissingDefaultArg > 0) {
404 // Some default arguments were missing. Clear out all of the
405 // default arguments up to (and including) the last missing
406 // default argument, so that we leave the function parameters
407 // in a semantically valid state.
408 for (p = 0; p <= LastMissingDefaultArg; ++p) {
409 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000410 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000411 if (!Param->hasUnparsedDefaultArg())
412 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000413 Param->setDefaultArg(0);
414 }
415 }
416 }
417}
Douglas Gregor556877c2008-04-13 21:30:24 +0000418
Douglas Gregor61956c42008-10-31 09:07:45 +0000419/// isCurrentClassName - Determine whether the identifier II is the
420/// name of the class type currently being defined. In the case of
421/// nested classes, this will only return true if II is the name of
422/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000423bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
424 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000425 assert(getLangOptions().CPlusPlus && "No class names in C!");
426
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000434 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump11289f42009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000448 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000449 SourceLocation BaseLoc) {
450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000460 Class->getTagKind() == RecordDecl::TK_class,
461 Access, BaseType);
462
463 // Base specifiers must be record types.
464 if (!BaseType->isRecordType()) {
465 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466 return 0;
467 }
468
469 // C++ [class.union]p1:
470 // A union shall not be used as a base class.
471 if (BaseType->isUnionType()) {
472 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473 return 0;
474 }
475
476 // C++ [class.derived]p2:
477 // The class-name in a base-specifier shall not be an incompletely
478 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000479 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000480 PDiag(diag::err_incomplete_base_class)
481 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000482 return 0;
483
Eli Friedmanc96d4962009-08-15 21:55:26 +0000484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000487 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000489 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000491
Alexis Hunt96d5c762009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000497 return 0;
498 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000499
Eli Friedman89c038e2009-12-05 23:03:49 +0000500 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000501
502 // Create the base specifier.
503 // FIXME: Allocate via ASTContext?
504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505 Class->getTagKind() == RecordDecl::TK_class,
506 Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510 const CXXRecordDecl *BaseClass,
511 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000512 // A class with a non-empty base class is not empty.
513 // FIXME: Standard ref?
514 if (!BaseClass->isEmpty())
515 Class->setEmpty(false);
516
517 // C++ [class.virtual]p1:
518 // A class that [...] inherits a virtual function is called a polymorphic
519 // class.
520 if (BaseClass->isPolymorphic())
521 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000522
Douglas Gregor463421d2009-03-03 04:44:36 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is [...] a class with [...] no base classes [...].
525 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000526
527 // C++ [class]p4:
528 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000529 Class->setPOD(false);
530
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000531 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000532 // C++ [class.ctor]p5:
533 // A constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000535
536 // C++ [class.copy]p6:
537 // A copy constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialCopyConstructor(false);
539
540 // C++ [class.copy]p11:
541 // A copy assignment operator is trivial if its class has no virtual
542 // base classes.
543 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000544
545 // C++0x [meta.unary.prop] is_empty:
546 // T is a class type, but not a union type, with ... no virtual base
547 // classes
548 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000549 } else {
550 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000551 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000552 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000553 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000554 Class->setHasTrivialConstructor(false);
555
556 // C++ [class.copy]p6:
557 // A copy constructor is trivial if all the direct base classes of its
558 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000560 Class->setHasTrivialCopyConstructor(false);
561
562 // C++ [class.copy]p11:
563 // A copy assignment operator is trivial if all the direct base classes
564 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000567 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000568
569 // C++ [class.ctor]p3:
570 // A destructor is trivial if all the direct base classes of its class
571 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000572 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000573 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000574}
575
Douglas Gregor556877c2008-04-13 21:30:24 +0000576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000578/// example:
579/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000580/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000581Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000583 bool Virtual, AccessSpecifier Access,
584 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000585 if (!classdecl)
586 return true;
587
Douglas Gregorc40290e2009-03-09 23:48:35 +0000588 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000589 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
590 if (!Class)
591 return true;
592
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000593 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000594 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
595 Virtual, Access,
596 BaseType, BaseLoc))
597 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000598
Douglas Gregor463421d2009-03-03 04:44:36 +0000599 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000600}
Douglas Gregor556877c2008-04-13 21:30:24 +0000601
Douglas Gregor463421d2009-03-03 04:44:36 +0000602/// \brief Performs the actual work of attaching the given base class
603/// specifiers to a C++ class.
604bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
605 unsigned NumBases) {
606 if (NumBases == 0)
607 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000608
609 // Used to keep track of which base types we have already seen, so
610 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000611 // that the key is always the unqualified canonical type of the base
612 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000613 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
614
615 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000616 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000617 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000618 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000619 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000620 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000621 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000622
Douglas Gregor29a92472008-10-22 17:49:05 +0000623 if (KnownBaseTypes[NewBaseType]) {
624 // C++ [class.mi]p3:
625 // A class shall not be specified as a direct base class of a
626 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000627 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000628 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000629 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000630 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000631
632 // Delete the duplicate base class specifier; we're going to
633 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000634 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000635
636 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000637 } else {
638 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000639 KnownBaseTypes[NewBaseType] = Bases[idx];
640 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000641 }
642 }
643
644 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000645 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000646
647 // Delete the remaining (good) base class specifiers, since their
648 // data has been copied into the CXXRecordDecl.
649 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000650 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000651
652 return Invalid;
653}
654
655/// ActOnBaseSpecifiers - Attach the given base specifiers to the
656/// class, after checking whether there are any duplicate base
657/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000658void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000659 unsigned NumBases) {
660 if (!ClassDecl || !Bases || !NumBases)
661 return;
662
663 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000664 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000665 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000666}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000667
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668/// \brief Determine whether the type \p Derived is a C++ class that is
669/// derived from the type \p Base.
670bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
671 if (!getLangOptions().CPlusPlus)
672 return false;
673
674 const RecordType *DerivedRT = Derived->getAs<RecordType>();
675 if (!DerivedRT)
676 return false;
677
678 const RecordType *BaseRT = Base->getAs<RecordType>();
679 if (!BaseRT)
680 return false;
681
682 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
683 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall67da35c2010-02-04 22:26:26 +0000684 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
685 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686}
687
688/// \brief Determine whether the type \p Derived is a C++ class that is
689/// derived from the type \p Base.
690bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
691 if (!getLangOptions().CPlusPlus)
692 return false;
693
694 const RecordType *DerivedRT = Derived->getAs<RecordType>();
695 if (!DerivedRT)
696 return false;
697
698 const RecordType *BaseRT = Base->getAs<RecordType>();
699 if (!BaseRT)
700 return false;
701
702 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
703 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
704 return DerivedRD->isDerivedFrom(BaseRD, Paths);
705}
706
707/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
708/// conversion (where Derived and Base are class types) is
709/// well-formed, meaning that the conversion is unambiguous (and
710/// that all of the base classes are accessible). Returns true
711/// and emits a diagnostic if the code is ill-formed, returns false
712/// otherwise. Loc is the location where this routine should point to
713/// if there is an error, and Range is the source range to highlight
714/// if there is an error.
715bool
716Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall5b0829a2010-02-10 09:31:12 +0000717 AccessDiagnosticsKind ADK,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000718 unsigned AmbigiousBaseConvID,
719 SourceLocation Loc, SourceRange Range,
720 DeclarationName Name) {
721 // First, determine whether the path from Derived to Base is
722 // ambiguous. This is slightly more expensive than checking whether
723 // the Derived to Base conversion exists, because here we need to
724 // explore multiple paths to determine if there is an ambiguity.
725 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
726 /*DetectVirtual=*/false);
727 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
728 assert(DerivationOkay &&
729 "Can only be used with a derived-to-base conversion");
730 (void)DerivationOkay;
731
732 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall5b0829a2010-02-10 09:31:12 +0000733 if (ADK == ADK_quiet)
Sebastian Redl7c353682009-11-14 21:15:49 +0000734 return false;
John McCall5b0829a2010-02-10 09:31:12 +0000735
Douglas Gregor36d1b142009-10-06 17:59:45 +0000736 // Check that the base class can be accessed.
John McCall5b0829a2010-02-10 09:31:12 +0000737 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
738 Base, Derived, Paths.front(),
739 /*force*/ false,
740 /*unprivileged*/ false,
741 ADK)) {
742 case AR_accessible: return false;
743 case AR_inaccessible: return true;
744 case AR_dependent: return false;
745 case AR_delayed: return false;
746 }
Douglas Gregor36d1b142009-10-06 17:59:45 +0000747 }
748
749 // We know that the derived-to-base conversion is ambiguous, and
750 // we're going to produce a diagnostic. Perform the derived-to-base
751 // search just one more time to compute all of the possible paths so
752 // that we can print them out. This is more expensive than any of
753 // the previous derived-to-base checks we've done, but at this point
754 // performance isn't as much of an issue.
755 Paths.clear();
756 Paths.setRecordingPaths(true);
757 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
758 assert(StillOkay && "Can only be used with a derived-to-base conversion");
759 (void)StillOkay;
760
761 // Build up a textual representation of the ambiguous paths, e.g.,
762 // D -> B -> A, that will be used to illustrate the ambiguous
763 // conversions in the diagnostic. We only print one of the paths
764 // to each base class subobject.
765 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
766
767 Diag(Loc, AmbigiousBaseConvID)
768 << Derived << Base << PathDisplayStr << Range << Name;
769 return true;
770}
771
772bool
773Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000774 SourceLocation Loc, SourceRange Range,
775 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000776 return CheckDerivedToBaseConversion(Derived, Base,
John McCall5b0829a2010-02-10 09:31:12 +0000777 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000778 diag::err_ambiguous_derived_to_base_conv,
779 Loc, Range, DeclarationName());
780}
781
782
783/// @brief Builds a string representing ambiguous paths from a
784/// specific derived class to different subobjects of the same base
785/// class.
786///
787/// This function builds a string that can be used in error messages
788/// to show the different paths that one can take through the
789/// inheritance hierarchy to go from the derived class to different
790/// subobjects of a base class. The result looks something like this:
791/// @code
792/// struct D -> struct B -> struct A
793/// struct D -> struct C -> struct A
794/// @endcode
795std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
796 std::string PathDisplayStr;
797 std::set<unsigned> DisplayedPaths;
798 for (CXXBasePaths::paths_iterator Path = Paths.begin();
799 Path != Paths.end(); ++Path) {
800 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
801 // We haven't displayed a path to this particular base
802 // class subobject yet.
803 PathDisplayStr += "\n ";
804 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
805 for (CXXBasePath::const_iterator Element = Path->begin();
806 Element != Path->end(); ++Element)
807 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
808 }
809 }
810
811 return PathDisplayStr;
812}
813
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000814//===----------------------------------------------------------------------===//
815// C++ class member Handling
816//===----------------------------------------------------------------------===//
817
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000818/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
819/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
820/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000821/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000822Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000823Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000824 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000825 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
826 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000827 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000828 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000829 Expr *BitWidth = static_cast<Expr*>(BW);
830 Expr *Init = static_cast<Expr*>(InitExpr);
831 SourceLocation Loc = D.getIdentifierLoc();
832
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000833 bool isFunc = D.isFunctionDeclarator();
834
John McCall07e91c02009-08-06 02:15:43 +0000835 assert(!DS.isFriendSpecified());
836
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000837 // C++ 9.2p6: A member shall not be declared to have automatic storage
838 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000839 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
840 // data members and cannot be applied to names declared const or static,
841 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000842 switch (DS.getStorageClassSpec()) {
843 case DeclSpec::SCS_unspecified:
844 case DeclSpec::SCS_typedef:
845 case DeclSpec::SCS_static:
846 // FALL THROUGH.
847 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000848 case DeclSpec::SCS_mutable:
849 if (isFunc) {
850 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000851 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000852 else
Chris Lattner3b054132008-11-19 05:08:23 +0000853 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000854
Sebastian Redl8071edb2008-11-17 23:24:37 +0000855 // FIXME: It would be nicer if the keyword was ignored only for this
856 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000857 D.getMutableDeclSpec().ClearStorageClassSpecs();
858 } else {
859 QualType T = GetTypeForDeclarator(D, S);
860 diag::kind err = static_cast<diag::kind>(0);
861 if (T->isReferenceType())
862 err = diag::err_mutable_reference;
863 else if (T.isConstQualified())
864 err = diag::err_mutable_const;
865 if (err != 0) {
866 if (DS.getStorageClassSpecLoc().isValid())
867 Diag(DS.getStorageClassSpecLoc(), err);
868 else
869 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000870 // FIXME: It would be nicer if the keyword was ignored only for this
871 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000872 D.getMutableDeclSpec().ClearStorageClassSpecs();
873 }
874 }
875 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876 default:
877 if (DS.getStorageClassSpecLoc().isValid())
878 Diag(DS.getStorageClassSpecLoc(),
879 diag::err_storageclass_invalid_for_member);
880 else
881 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
882 D.getMutableDeclSpec().ClearStorageClassSpecs();
883 }
884
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000885 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000886 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000887 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000888 // Check also for this case:
889 //
890 // typedef int f();
891 // f a;
892 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000893 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000894 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000895 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000896
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000897 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
898 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000899 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000900
901 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000902 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000903 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000904 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
905 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000906 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000907 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000908 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000909 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000910 if (!Member) {
911 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000912 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000913 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000914
915 // Non-instance-fields can't have a bitfield.
916 if (BitWidth) {
917 if (Member->isInvalidDecl()) {
918 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000919 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000920 // C++ 9.6p3: A bit-field shall not be a static member.
921 // "static member 'A' cannot be a bit-field"
922 Diag(Loc, diag::err_static_not_bitfield)
923 << Name << BitWidth->getSourceRange();
924 } else if (isa<TypedefDecl>(Member)) {
925 // "typedef member 'x' cannot be a bit-field"
926 Diag(Loc, diag::err_typedef_not_bitfield)
927 << Name << BitWidth->getSourceRange();
928 } else {
929 // A function typedef ("typedef int f(); f a;").
930 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
931 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000932 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000933 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000934 }
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattnerd26760a2009-03-05 23:01:03 +0000936 DeleteExpr(BitWidth);
937 BitWidth = 0;
938 Member->setInvalidDecl();
939 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000940
941 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Douglas Gregor3447e762009-08-20 22:52:58 +0000943 // If we have declared a member function template, set the access of the
944 // templated declaration as well.
945 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
946 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000947 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000948
Douglas Gregor92751d42008-11-17 22:58:34 +0000949 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000950
Douglas Gregor0c880302009-03-11 23:00:04 +0000951 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000952 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000953 if (Deleted) // FIXME: Source location is not very good.
954 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000955
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000956 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000957 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000958 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000959 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000960 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000961}
962
Douglas Gregor15e77a22009-12-31 09:10:24 +0000963/// \brief Find the direct and/or virtual base specifiers that
964/// correspond to the given base type, for use in base initialization
965/// within a constructor.
966static bool FindBaseInitializer(Sema &SemaRef,
967 CXXRecordDecl *ClassDecl,
968 QualType BaseType,
969 const CXXBaseSpecifier *&DirectBaseSpec,
970 const CXXBaseSpecifier *&VirtualBaseSpec) {
971 // First, check for a direct base class.
972 DirectBaseSpec = 0;
973 for (CXXRecordDecl::base_class_const_iterator Base
974 = ClassDecl->bases_begin();
975 Base != ClassDecl->bases_end(); ++Base) {
976 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
977 // We found a direct base of this type. That's what we're
978 // initializing.
979 DirectBaseSpec = &*Base;
980 break;
981 }
982 }
983
984 // Check for a virtual base class.
985 // FIXME: We might be able to short-circuit this if we know in advance that
986 // there are no virtual bases.
987 VirtualBaseSpec = 0;
988 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
989 // We haven't found a base yet; search the class hierarchy for a
990 // virtual base class.
991 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
992 /*DetectVirtual=*/false);
993 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
994 BaseType, Paths)) {
995 for (CXXBasePaths::paths_iterator Path = Paths.begin();
996 Path != Paths.end(); ++Path) {
997 if (Path->back().Base->isVirtual()) {
998 VirtualBaseSpec = Path->back().Base;
999 break;
1000 }
1001 }
1002 }
1003 }
1004
1005 return DirectBaseSpec || VirtualBaseSpec;
1006}
1007
Douglas Gregore8381c02008-11-05 04:29:56 +00001008/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001009Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001010Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001011 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001012 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001013 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001014 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001015 SourceLocation IdLoc,
1016 SourceLocation LParenLoc,
1017 ExprTy **Args, unsigned NumArgs,
1018 SourceLocation *CommaLocs,
1019 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001020 if (!ConstructorD)
1021 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001023 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001024
1025 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001026 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001027 if (!Constructor) {
1028 // The user wrote a constructor initializer on a function that is
1029 // not a C++ constructor. Ignore the error for now, because we may
1030 // have more member initializers coming; we'll diagnose it just
1031 // once in ActOnMemInitializers.
1032 return true;
1033 }
1034
1035 CXXRecordDecl *ClassDecl = Constructor->getParent();
1036
1037 // C++ [class.base.init]p2:
1038 // Names in a mem-initializer-id are looked up in the scope of the
1039 // constructor’s class and, if not found in that scope, are looked
1040 // up in the scope containing the constructor’s
1041 // definition. [Note: if the constructor’s class contains a member
1042 // with the same name as a direct or virtual base class of the
1043 // class, a mem-initializer-id naming the member or base class and
1044 // composed of a single identifier refers to the class member. A
1045 // mem-initializer-id for the hidden base class may be specified
1046 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001047 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001048 // Look for a member, first.
1049 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001050 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001051 = ClassDecl->lookup(MemberOrBase);
1052 if (Result.first != Result.second)
1053 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001054
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001055 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001056
Eli Friedman8e1433b2009-07-29 19:44:27 +00001057 if (Member)
1058 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001059 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001060 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001061 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001062 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001063 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001064
1065 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001066 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001067 } else {
1068 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1069 LookupParsedName(R, S, &SS);
1070
1071 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1072 if (!TyD) {
1073 if (R.isAmbiguous()) return true;
1074
Douglas Gregora3b624a2010-01-19 06:46:48 +00001075 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1076 bool NotUnknownSpecialization = false;
1077 DeclContext *DC = computeDeclContext(SS, false);
1078 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1079 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1080
1081 if (!NotUnknownSpecialization) {
1082 // When the scope specifier can refer to a member of an unknown
1083 // specialization, we take it as a type name.
1084 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1085 *MemberOrBase, SS.getRange());
Douglas Gregor281c4862010-03-07 23:26:22 +00001086 if (BaseType.isNull())
1087 return true;
1088
Douglas Gregora3b624a2010-01-19 06:46:48 +00001089 R.clear();
1090 }
1091 }
1092
Douglas Gregor15e77a22009-12-31 09:10:24 +00001093 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001094 if (R.empty() && BaseType.isNull() &&
Douglas Gregor15e77a22009-12-31 09:10:24 +00001095 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1096 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1097 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1098 // We have found a non-static data member with a similar
1099 // name to what was typed; complain and initialize that
1100 // member.
1101 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1102 << MemberOrBase << true << R.getLookupName()
1103 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1104 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001105 Diag(Member->getLocation(), diag::note_previous_decl)
1106 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001107
1108 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1109 LParenLoc, RParenLoc);
1110 }
1111 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1112 const CXXBaseSpecifier *DirectBaseSpec;
1113 const CXXBaseSpecifier *VirtualBaseSpec;
1114 if (FindBaseInitializer(*this, ClassDecl,
1115 Context.getTypeDeclType(Type),
1116 DirectBaseSpec, VirtualBaseSpec)) {
1117 // We have found a direct or virtual base class with a
1118 // similar name to what was typed; complain and initialize
1119 // that base class.
1120 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1121 << MemberOrBase << false << R.getLookupName()
1122 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1123 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001124
1125 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1126 : VirtualBaseSpec;
1127 Diag(BaseSpec->getSourceRange().getBegin(),
1128 diag::note_base_class_specified_here)
1129 << BaseSpec->getType()
1130 << BaseSpec->getSourceRange();
1131
Douglas Gregor15e77a22009-12-31 09:10:24 +00001132 TyD = Type;
1133 }
1134 }
1135 }
1136
Douglas Gregora3b624a2010-01-19 06:46:48 +00001137 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001138 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1139 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1140 return true;
1141 }
John McCallb5a0d312009-12-21 10:41:20 +00001142 }
1143
Douglas Gregora3b624a2010-01-19 06:46:48 +00001144 if (BaseType.isNull()) {
1145 BaseType = Context.getTypeDeclType(TyD);
1146 if (SS.isSet()) {
1147 NestedNameSpecifier *Qualifier =
1148 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001149
Douglas Gregora3b624a2010-01-19 06:46:48 +00001150 // FIXME: preserve source range information
1151 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1152 }
John McCallb5a0d312009-12-21 10:41:20 +00001153 }
1154 }
Mike Stump11289f42009-09-09 15:08:12 +00001155
John McCallbcd03502009-12-07 02:54:59 +00001156 if (!TInfo)
1157 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001158
John McCallbcd03502009-12-07 02:54:59 +00001159 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001160 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001161}
1162
John McCalle22a04a2009-11-04 23:02:40 +00001163/// Checks an initializer expression for use of uninitialized fields, such as
1164/// containing the field that is being initialized. Returns true if there is an
1165/// uninitialized field was used an updates the SourceLocation parameter; false
1166/// otherwise.
1167static bool InitExprContainsUninitializedFields(const Stmt* S,
1168 const FieldDecl* LhsField,
1169 SourceLocation* L) {
1170 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1171 if (ME) {
1172 const NamedDecl* RhsField = ME->getMemberDecl();
1173 if (RhsField == LhsField) {
1174 // Initializing a field with itself. Throw a warning.
1175 // But wait; there are exceptions!
1176 // Exception #1: The field may not belong to this record.
1177 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1178 const Expr* base = ME->getBase();
1179 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1180 // Even though the field matches, it does not belong to this record.
1181 return false;
1182 }
1183 // None of the exceptions triggered; return true to indicate an
1184 // uninitialized field was used.
1185 *L = ME->getMemberLoc();
1186 return true;
1187 }
1188 }
1189 bool found = false;
1190 for (Stmt::const_child_iterator it = S->child_begin();
1191 it != S->child_end() && found == false;
1192 ++it) {
1193 if (isa<CallExpr>(S)) {
1194 // Do not descend into function calls or constructors, as the use
1195 // of an uninitialized field may be valid. One would have to inspect
1196 // the contents of the function/ctor to determine if it is safe or not.
1197 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1198 // may be safe, depending on what the function/ctor does.
1199 continue;
1200 }
1201 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1202 }
1203 return found;
1204}
1205
Eli Friedman8e1433b2009-07-29 19:44:27 +00001206Sema::MemInitResult
1207Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1208 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001209 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001210 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001211 // Diagnose value-uses of fields to initialize themselves, e.g.
1212 // foo(foo)
1213 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001214 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001215 for (unsigned i = 0; i < NumArgs; ++i) {
1216 SourceLocation L;
1217 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1218 // FIXME: Return true in the case when other fields are used before being
1219 // uninitialized. For example, let this field be the i'th field. When
1220 // initializing the i'th field, throw a warning if any of the >= i'th
1221 // fields are used, as they are not yet initialized.
1222 // Right now we are only handling the case where the i'th field uses
1223 // itself in its initializer.
1224 Diag(L, diag::warn_field_is_uninit);
1225 }
1226 }
1227
Eli Friedman8e1433b2009-07-29 19:44:27 +00001228 bool HasDependentArg = false;
1229 for (unsigned i = 0; i < NumArgs; i++)
1230 HasDependentArg |= Args[i]->isTypeDependent();
1231
Eli Friedman8e1433b2009-07-29 19:44:27 +00001232 QualType FieldType = Member->getType();
1233 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1234 FieldType = Array->getElementType();
Eli Friedman11c7b152009-12-25 23:59:21 +00001235 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001236 if (FieldType->isDependentType() || HasDependentArg) {
1237 // Can't check initialization for a member of dependent type or when
1238 // any of the arguments are type-dependent expressions.
1239 OwningExprResult Init
1240 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1241 RParenLoc));
1242
1243 // Erase any temporaries within this evaluation context; we're not
1244 // going to track them in the AST, since we'll be rebuilding the
1245 // ASTs during template instantiation.
1246 ExprTemporaries.erase(
1247 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1248 ExprTemporaries.end());
1249
1250 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1251 LParenLoc,
1252 Init.takeAs<Expr>(),
1253 RParenLoc);
1254
Douglas Gregore8381c02008-11-05 04:29:56 +00001255 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001256
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001257 if (Member->isInvalidDecl())
1258 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001259
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001260 // Initialize the member.
1261 InitializedEntity MemberEntity =
1262 InitializedEntity::InitializeMember(Member, 0);
1263 InitializationKind Kind =
1264 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1265
1266 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1267
1268 OwningExprResult MemberInit =
1269 InitSeq.Perform(*this, MemberEntity, Kind,
1270 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1271 if (MemberInit.isInvalid())
1272 return true;
1273
1274 // C++0x [class.base.init]p7:
1275 // The initialization of each base and member constitutes a
1276 // full-expression.
1277 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1278 if (MemberInit.isInvalid())
1279 return true;
1280
1281 // If we are in a dependent context, template instantiation will
1282 // perform this type-checking again. Just save the arguments that we
1283 // received in a ParenListExpr.
1284 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1285 // of the information that we have about the member
1286 // initializer. However, deconstructing the ASTs is a dicey process,
1287 // and this approach is far more likely to get the corner cases right.
1288 if (CurContext->isDependentContext()) {
1289 // Bump the reference count of all of the arguments.
1290 for (unsigned I = 0; I != NumArgs; ++I)
1291 Args[I]->Retain();
1292
1293 OwningExprResult Init
1294 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1295 RParenLoc));
1296 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1297 LParenLoc,
1298 Init.takeAs<Expr>(),
1299 RParenLoc);
1300 }
1301
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001302 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001303 LParenLoc,
1304 MemberInit.takeAs<Expr>(),
1305 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001306}
1307
1308Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001309Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001310 Expr **Args, unsigned NumArgs,
1311 SourceLocation LParenLoc, SourceLocation RParenLoc,
1312 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001313 bool HasDependentArg = false;
1314 for (unsigned i = 0; i < NumArgs; i++)
1315 HasDependentArg |= Args[i]->isTypeDependent();
1316
John McCallbcd03502009-12-07 02:54:59 +00001317 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001318 if (BaseType->isDependentType() || HasDependentArg) {
1319 // Can't check initialization for a base of dependent type or when
1320 // any of the arguments are type-dependent expressions.
1321 OwningExprResult BaseInit
1322 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1323 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001324
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001325 // Erase any temporaries within this evaluation context; we're not
1326 // going to track them in the AST, since we'll be rebuilding the
1327 // ASTs during template instantiation.
1328 ExprTemporaries.erase(
1329 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1330 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001332 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1333 LParenLoc,
1334 BaseInit.takeAs<Expr>(),
1335 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001336 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001337
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001338 if (!BaseType->isRecordType())
1339 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1340 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1341
1342 // C++ [class.base.init]p2:
1343 // [...] Unless the mem-initializer-id names a nonstatic data
1344 // member of the constructor’s class or a direct or virtual base
1345 // of that class, the mem-initializer is ill-formed. A
1346 // mem-initializer-list can initialize a base class using any
1347 // name that denotes that base class type.
1348
1349 // Check for direct and virtual base classes.
1350 const CXXBaseSpecifier *DirectBaseSpec = 0;
1351 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1352 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1353 VirtualBaseSpec);
1354
1355 // C++ [base.class.init]p2:
1356 // If a mem-initializer-id is ambiguous because it designates both
1357 // a direct non-virtual base class and an inherited virtual base
1358 // class, the mem-initializer is ill-formed.
1359 if (DirectBaseSpec && VirtualBaseSpec)
1360 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1361 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1362 // C++ [base.class.init]p2:
1363 // Unless the mem-initializer-id names a nonstatic data membeer of the
1364 // constructor's class ot a direst or virtual base of that class, the
1365 // mem-initializer is ill-formed.
1366 if (!DirectBaseSpec && !VirtualBaseSpec)
1367 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1368 << BaseType << ClassDecl->getNameAsCString()
1369 << BaseTInfo->getTypeLoc().getSourceRange();
1370
1371 CXXBaseSpecifier *BaseSpec
1372 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1373 if (!BaseSpec)
1374 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1375
1376 // Initialize the base.
1377 InitializedEntity BaseEntity =
1378 InitializedEntity::InitializeBase(Context, BaseSpec);
1379 InitializationKind Kind =
1380 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1381
1382 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1383
1384 OwningExprResult BaseInit =
1385 InitSeq.Perform(*this, BaseEntity, Kind,
1386 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1387 if (BaseInit.isInvalid())
1388 return true;
1389
1390 // C++0x [class.base.init]p7:
1391 // The initialization of each base and member constitutes a
1392 // full-expression.
1393 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1394 if (BaseInit.isInvalid())
1395 return true;
1396
1397 // If we are in a dependent context, template instantiation will
1398 // perform this type-checking again. Just save the arguments that we
1399 // received in a ParenListExpr.
1400 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1401 // of the information that we have about the base
1402 // initializer. However, deconstructing the ASTs is a dicey process,
1403 // and this approach is far more likely to get the corner cases right.
1404 if (CurContext->isDependentContext()) {
1405 // Bump the reference count of all of the arguments.
1406 for (unsigned I = 0; I != NumArgs; ++I)
1407 Args[I]->Retain();
1408
1409 OwningExprResult Init
1410 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1411 RParenLoc));
1412 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1413 LParenLoc,
1414 Init.takeAs<Expr>(),
1415 RParenLoc);
1416 }
1417
1418 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1419 LParenLoc,
1420 BaseInit.takeAs<Expr>(),
1421 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001422}
1423
Eli Friedman9cf6b592009-11-09 19:20:36 +00001424bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001425Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001426 CXXBaseOrMemberInitializer **Initializers,
1427 unsigned NumInitializers,
1428 bool IsImplicitConstructor,
1429 bool AnyErrors) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001430 // We need to build the initializer AST according to order of construction
1431 // and not what user specified in the Initializers list.
1432 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1433 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1434 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1435 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001436 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001437
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001438 for (unsigned i = 0; i < NumInitializers; i++) {
1439 CXXBaseOrMemberInitializer *Member = Initializers[i];
1440 if (Member->isBaseInitializer()) {
1441 if (Member->getBaseClass()->isDependentType())
1442 HasDependentBaseInit = true;
1443 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1444 } else {
1445 AllBaseFields[Member->getMember()] = Member;
1446 }
1447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001449 if (HasDependentBaseInit) {
1450 // FIXME. This does not preserve the ordering of the initializers.
1451 // Try (with -Wreorder)
1452 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001453 // template<class X> struct B : A<X> {
1454 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001455 // int x1;
1456 // };
1457 // B<int> x;
1458 // On seeing one dependent type, we should essentially exit this routine
1459 // while preserving user-declared initializer list. When this routine is
1460 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001461 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001462
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001463 // If we have a dependent base initialization, we can't determine the
1464 // association between initializers and bases; just dump the known
1465 // initializers into the list, and don't try to deal with other bases.
1466 for (unsigned i = 0; i < NumInitializers; i++) {
1467 CXXBaseOrMemberInitializer *Member = Initializers[i];
1468 if (Member->isBaseInitializer())
1469 AllToInit.push_back(Member);
1470 }
1471 } else {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001472 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1473
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001474 // Push virtual bases before others.
1475 for (CXXRecordDecl::base_class_iterator VBase =
1476 ClassDecl->vbases_begin(),
1477 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1478 if (VBase->getType()->isDependentType())
1479 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001480 if (CXXBaseOrMemberInitializer *Value
1481 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001482 AllToInit.push_back(Value);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001483 } else if (!AnyErrors) {
1484 InitializedEntity InitEntity
1485 = InitializedEntity::InitializeBase(Context, VBase);
1486 InitializationKind InitKind
1487 = InitializationKind::CreateDefault(Constructor->getLocation());
1488 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1489 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1490 MultiExprArg(*this, 0, 0));
1491 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1492 if (BaseInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001493 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001494 continue;
1495 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001496
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001497 // Don't attach synthesized base initializers in a dependent
1498 // context; they'll be checked again at template instantiation
1499 // time.
1500 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001501 continue;
1502
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001503 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001504 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001505 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001506 SourceLocation()),
Anders Carlsson561f7932009-10-29 15:46:07 +00001507 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001508 BaseInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001509 SourceLocation());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001510 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001511 }
1512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001514 for (CXXRecordDecl::base_class_iterator Base =
1515 ClassDecl->bases_begin(),
1516 E = ClassDecl->bases_end(); Base != E; ++Base) {
1517 // Virtuals are in the virtual base list and already constructed.
1518 if (Base->isVirtual())
1519 continue;
1520 // Skip dependent types.
1521 if (Base->getType()->isDependentType())
1522 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001523 if (CXXBaseOrMemberInitializer *Value
1524 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001525 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001526 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001527 else if (!AnyErrors) {
1528 InitializedEntity InitEntity
1529 = InitializedEntity::InitializeBase(Context, Base);
1530 InitializationKind InitKind
1531 = InitializationKind::CreateDefault(Constructor->getLocation());
1532 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1533 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1534 MultiExprArg(*this, 0, 0));
1535 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1536 if (BaseInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001537 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001538 continue;
1539 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001540
1541 // Don't attach synthesized base initializers in a dependent
1542 // context; they'll be regenerated at template instantiation
1543 // time.
1544 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001545 continue;
1546
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001547 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001548 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001549 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001550 SourceLocation()),
Anders Carlsson561f7932009-10-29 15:46:07 +00001551 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001552 BaseInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001553 SourceLocation());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001554 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001555 }
1556 }
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001559 // non-static data members.
1560 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1561 E = ClassDecl->field_end(); Field != E; ++Field) {
1562 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001563 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001564 Field->getType()->getAs<RecordType>()) {
1565 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001566 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001567 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001568 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1569 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1570 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1571 // set to the anonymous union data member used in the initializer
1572 // list.
1573 Value->setMember(*Field);
1574 Value->setAnonUnionMember(*FA);
1575 AllToInit.push_back(Value);
1576 break;
1577 }
1578 }
1579 }
1580 continue;
1581 }
1582 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1583 AllToInit.push_back(Value);
1584 continue;
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001587 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001588 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001589
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001590 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001591 if (FT->getAs<RecordType>()) {
1592 InitializedEntity InitEntity
1593 = InitializedEntity::InitializeMember(*Field);
1594 InitializationKind InitKind
1595 = InitializationKind::CreateDefault(Constructor->getLocation());
1596
1597 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1598 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1599 MultiExprArg(*this, 0, 0));
1600 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1601 if (MemberInit.isInvalid()) {
Eli Friedman9cf6b592009-11-09 19:20:36 +00001602 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001603 continue;
1604 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001605
1606 // Don't attach synthesized member initializers in a dependent
1607 // context; they'll be regenerated a template instantiation
1608 // time.
1609 if (CurContext->isDependentContext())
Anders Carlsson561f7932009-10-29 15:46:07 +00001610 continue;
1611
Mike Stump11289f42009-09-09 15:08:12 +00001612 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001613 new (Context) CXXBaseOrMemberInitializer(Context,
1614 *Field, SourceLocation(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001615 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001616 MemberInit.takeAs<Expr>(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001617 SourceLocation());
1618
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001619 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001620 }
1621 else if (FT->isReferenceType()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001622 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001623 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1624 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001625 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001626 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001627 }
1628 else if (FT.isConstQualified()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001629 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001630 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1631 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001632 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001633 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001634 }
1635 }
Mike Stump11289f42009-09-09 15:08:12 +00001636
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001637 NumInitializers = AllToInit.size();
1638 if (NumInitializers > 0) {
1639 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1640 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1641 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001642
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001643 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola70e040d2010-03-02 21:28:26 +00001644 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1645 CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1646 baseOrMemberInitializers[Idx] = Member;
1647 if (!Member->isBaseInitializer())
1648 continue;
1649 const Type *BaseType = Member->getBaseClass();
1650 const RecordType *RT = BaseType->getAs<RecordType>();
1651 if (!RT)
1652 continue;
1653 CXXRecordDecl *BaseClassDecl =
1654 cast<CXXRecordDecl>(RT->getDecl());
1655 if (BaseClassDecl->hasTrivialDestructor())
1656 continue;
1657 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1658 MarkDeclarationReferenced(Constructor->getLocation(), DD);
1659 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001660 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001661
1662 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001663}
1664
Eli Friedman952c15d2009-07-21 19:28:10 +00001665static void *GetKeyForTopLevelField(FieldDecl *Field) {
1666 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001667 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001668 if (RT->getDecl()->isAnonymousStructOrUnion())
1669 return static_cast<void *>(RT->getDecl());
1670 }
1671 return static_cast<void *>(Field);
1672}
1673
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001674static void *GetKeyForBase(QualType BaseType) {
1675 if (const RecordType *RT = BaseType->getAs<RecordType>())
1676 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001677
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001678 assert(0 && "Unexpected base type!");
1679 return 0;
1680}
1681
Mike Stump11289f42009-09-09 15:08:12 +00001682static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001683 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001684 // For fields injected into the class via declaration of an anonymous union,
1685 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001686 if (Member->isMemberInitializer()) {
1687 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001688
Eli Friedmand7686ef2009-11-09 01:05:47 +00001689 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001690 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001691 // in AnonUnionMember field.
1692 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1693 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001694 if (Field->getDeclContext()->isRecord()) {
1695 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1696 if (RD->isAnonymousStructOrUnion())
1697 return static_cast<void *>(RD);
1698 }
1699 return static_cast<void *>(Field);
1700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001702 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001703}
1704
John McCallc90f6d72009-11-04 23:13:52 +00001705/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001706void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001707 SourceLocation ColonLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001708 MemInitTy **MemInits, unsigned NumMemInits,
1709 bool AnyErrors) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001710 if (!ConstructorDecl)
1711 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001712
1713 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001714
1715 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001716 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001717
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001718 if (!Constructor) {
1719 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1720 return;
1721 }
Mike Stump11289f42009-09-09 15:08:12 +00001722
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001723 if (!Constructor->isDependentContext()) {
1724 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1725 bool err = false;
1726 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001727 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001728 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1729 void *KeyToMember = GetKeyForMember(Member);
1730 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1731 if (!PrevMember) {
1732 PrevMember = Member;
1733 continue;
1734 }
1735 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001736 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001737 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001738 << Field->getNameAsString()
1739 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001740 else {
1741 Type *BaseClass = Member->getBaseClass();
1742 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001743 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001744 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001745 << QualType(BaseClass, 0)
1746 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001747 }
1748 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1749 << 0;
1750 err = true;
1751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001753 if (err)
1754 return;
1755 }
Mike Stump11289f42009-09-09 15:08:12 +00001756
Eli Friedmand7686ef2009-11-09 01:05:47 +00001757 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001758 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001759 NumMemInits, false, AnyErrors);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001761 if (Constructor->isDependentContext())
1762 return;
Mike Stump11289f42009-09-09 15:08:12 +00001763
1764 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001765 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001766 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001767 Diagnostic::Ignored)
1768 return;
Mike Stump11289f42009-09-09 15:08:12 +00001769
Anders Carlssone0eebb32009-08-27 05:45:01 +00001770 // Also issue warning if order of ctor-initializer list does not match order
1771 // of 1) base class declarations and 2) order of non-static data members.
1772 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001773
Anders Carlssone0eebb32009-08-27 05:45:01 +00001774 CXXRecordDecl *ClassDecl
1775 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1776 // Push virtual bases before others.
1777 for (CXXRecordDecl::base_class_iterator VBase =
1778 ClassDecl->vbases_begin(),
1779 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001780 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001781
Anders Carlssone0eebb32009-08-27 05:45:01 +00001782 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1783 E = ClassDecl->bases_end(); Base != E; ++Base) {
1784 // Virtuals are alread in the virtual base list and are constructed
1785 // first.
1786 if (Base->isVirtual())
1787 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001788 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Anders Carlssone0eebb32009-08-27 05:45:01 +00001791 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1792 E = ClassDecl->field_end(); Field != E; ++Field)
1793 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001794
Anders Carlssone0eebb32009-08-27 05:45:01 +00001795 int Last = AllBaseOrMembers.size();
1796 int curIndex = 0;
1797 CXXBaseOrMemberInitializer *PrevMember = 0;
1798 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001799 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001800 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1801 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001802
Anders Carlssone0eebb32009-08-27 05:45:01 +00001803 for (; curIndex < Last; curIndex++)
1804 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1805 break;
1806 if (curIndex == Last) {
1807 assert(PrevMember && "Member not in member list?!");
1808 // Initializer as specified in ctor-initializer list is out of order.
1809 // Issue a warning diagnostic.
1810 if (PrevMember->isBaseInitializer()) {
1811 // Diagnostics is for an initialized base class.
1812 Type *BaseClass = PrevMember->getBaseClass();
1813 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001814 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001815 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001816 } else {
1817 FieldDecl *Field = PrevMember->getMember();
1818 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001819 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001820 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001821 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001822 // Also the note!
1823 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001824 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001825 diag::note_fieldorbase_initialized_here) << 0
1826 << Field->getNameAsString();
1827 else {
1828 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001829 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001830 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001831 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001832 }
1833 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001834 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001835 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001836 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001837 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001838 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001839}
1840
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001841void
Anders Carlssondee9a302009-11-17 04:44:12 +00001842Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1843 // Ignore dependent destructors.
1844 if (Destructor->isDependentContext())
1845 return;
1846
1847 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001848
Anders Carlssondee9a302009-11-17 04:44:12 +00001849 // Non-static data members.
1850 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1851 E = ClassDecl->field_end(); I != E; ++I) {
1852 FieldDecl *Field = *I;
1853
1854 QualType FieldType = Context.getBaseElementType(Field->getType());
1855
1856 const RecordType* RT = FieldType->getAs<RecordType>();
1857 if (!RT)
1858 continue;
1859
1860 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1861 if (FieldClassDecl->hasTrivialDestructor())
1862 continue;
1863
1864 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1865 MarkDeclarationReferenced(Destructor->getLocation(),
1866 const_cast<CXXDestructorDecl*>(Dtor));
1867 }
1868
1869 // Bases.
1870 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1871 E = ClassDecl->bases_end(); Base != E; ++Base) {
1872 // Ignore virtual bases.
1873 if (Base->isVirtual())
1874 continue;
1875
1876 // Ignore trivial destructors.
1877 CXXRecordDecl *BaseClassDecl
1878 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1879 if (BaseClassDecl->hasTrivialDestructor())
1880 continue;
1881
1882 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1883 MarkDeclarationReferenced(Destructor->getLocation(),
1884 const_cast<CXXDestructorDecl*>(Dtor));
1885 }
1886
1887 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001888 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1889 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001890 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001891 CXXRecordDecl *BaseClassDecl
1892 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1893 if (BaseClassDecl->hasTrivialDestructor())
1894 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001895
1896 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1897 MarkDeclarationReferenced(Destructor->getLocation(),
1898 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001899 }
1900}
1901
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001902void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001903 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001904 return;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001906 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001907
1908 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001909 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001910 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001911}
1912
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001913namespace {
1914 /// PureVirtualMethodCollector - traverses a class and its superclasses
1915 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001916 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001917 ASTContext &Context;
1918
Sebastian Redlb7d64912009-03-22 21:28:55 +00001919 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001920 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001921
1922 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001923 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001924
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001925 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001926
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001927 public:
Mike Stump11289f42009-09-09 15:08:12 +00001928 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001929 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001930
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001931 MethodList List;
1932 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001933
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001934 // Copy the temporary list to methods, and make sure to ignore any
1935 // null entries.
1936 for (size_t i = 0, e = List.size(); i != e; ++i) {
1937 if (List[i])
1938 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001939 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001942 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001943
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001944 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1945 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001946 };
Mike Stump11289f42009-09-09 15:08:12 +00001947
1948 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001949 MethodList& Methods) {
1950 // First, collect the pure virtual methods for the base classes.
1951 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1952 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001953 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001954 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001955 if (BaseDecl && BaseDecl->isAbstract())
1956 Collect(BaseDecl, Methods);
1957 }
1958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001960 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001961 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001962
Anders Carlsson3c012712009-05-17 00:00:05 +00001963 MethodSetTy OverriddenMethods;
1964 size_t MethodsSize = Methods.size();
1965
Mike Stump11289f42009-09-09 15:08:12 +00001966 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001967 i != e; ++i) {
1968 // Traverse the record, looking for methods.
1969 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001970 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001971 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001972 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001973
Anders Carlsson700179432009-10-18 19:34:08 +00001974 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001975 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1976 E = MD->end_overridden_methods(); I != E; ++I) {
1977 // Keep track of the overridden methods.
1978 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001979 }
1980 }
1981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
1983 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001984 // overridden.
1985 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1986 if (OverriddenMethods.count(Methods[i]))
1987 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001988 }
Mike Stump11289f42009-09-09 15:08:12 +00001989
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001990 }
1991}
Douglas Gregore8381c02008-11-05 04:29:56 +00001992
Anders Carlssoneabf7702009-08-27 00:13:57 +00001993
Mike Stump11289f42009-09-09 15:08:12 +00001994bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001995 unsigned DiagID, AbstractDiagSelID SelID,
1996 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001997 if (SelID == -1)
1998 return RequireNonAbstractType(Loc, T,
1999 PDiag(DiagID), CurrentRD);
2000 else
2001 return RequireNonAbstractType(Loc, T,
2002 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002003}
2004
Anders Carlssoneabf7702009-08-27 00:13:57 +00002005bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2006 const PartialDiagnostic &PD,
2007 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002008 if (!getLangOptions().CPlusPlus)
2009 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002010
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002011 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002012 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002013 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002014
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002015 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002016 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002017 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002018 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002020 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002021 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002025 if (!RT)
2026 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002027
John McCall67da35c2010-02-04 22:26:26 +00002028 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002029
Anders Carlssonb57738b2009-03-24 17:23:42 +00002030 if (CurrentRD && CurrentRD != RD)
2031 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002032
John McCall67da35c2010-02-04 22:26:26 +00002033 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002034 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002035 return false;
2036
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002037 if (!RD->isAbstract())
2038 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002039
Anders Carlssoneabf7702009-08-27 00:13:57 +00002040 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002041
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002042 // Check if we've already emitted the list of pure virtual functions for this
2043 // class.
2044 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2045 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002046
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002047 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00002048
2049 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002050 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2051 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002052
2053 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002054 MD->getDeclName();
2055 }
2056
2057 if (!PureVirtualClassDiagSet)
2058 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2059 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002060
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002061 return true;
2062}
2063
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002064namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002065 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002066 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2067 Sema &SemaRef;
2068 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002069
Anders Carlssonb57738b2009-03-24 17:23:42 +00002070 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002071 bool Invalid = false;
2072
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002073 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2074 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002075 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002076
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002077 return Invalid;
2078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Anders Carlssonb57738b2009-03-24 17:23:42 +00002080 public:
2081 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2082 : SemaRef(SemaRef), AbstractClass(ac) {
2083 Visit(SemaRef.Context.getTranslationUnitDecl());
2084 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002085
Anders Carlssonb57738b2009-03-24 17:23:42 +00002086 bool VisitFunctionDecl(const FunctionDecl *FD) {
2087 if (FD->isThisDeclarationADefinition()) {
2088 // No need to do the check if we're in a definition, because it requires
2089 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002090 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002091 return VisitDeclContext(FD);
2092 }
Mike Stump11289f42009-09-09 15:08:12 +00002093
Anders Carlssonb57738b2009-03-24 17:23:42 +00002094 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002095 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002096 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002097 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2098 diag::err_abstract_type_in_decl,
2099 Sema::AbstractReturnType,
2100 AbstractClass);
2101
Mike Stump11289f42009-09-09 15:08:12 +00002102 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002103 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002104 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002105 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002106 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002107 VD->getOriginalType(),
2108 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002109 Sema::AbstractParamType,
2110 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002111 }
2112
2113 return Invalid;
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
Anders Carlssonb57738b2009-03-24 17:23:42 +00002116 bool VisitDecl(const Decl* D) {
2117 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2118 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002119
Anders Carlssonb57738b2009-03-24 17:23:42 +00002120 return false;
2121 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002122 };
2123}
2124
Douglas Gregorc99f1552009-12-03 18:33:45 +00002125/// \brief Perform semantic checks on a class definition that has been
2126/// completing, introducing implicitly-declared members, checking for
2127/// abstract types, etc.
2128void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2129 if (!Record || Record->isInvalidDecl())
2130 return;
2131
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002132 if (!Record->isDependentType())
2133 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002134
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002135 if (Record->isInvalidDecl())
2136 return;
2137
John McCall2cb94162010-01-28 07:38:46 +00002138 // Set access bits correctly on the directly-declared conversions.
2139 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2140 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2141 Convs->setAccess(I, (*I)->getAccess());
2142
Douglas Gregorc99f1552009-12-03 18:33:45 +00002143 if (!Record->isAbstract()) {
2144 // Collect all the pure virtual methods and see if this is an abstract
2145 // class after all.
2146 PureVirtualMethodCollector Collector(Context, Record);
2147 if (!Collector.empty())
2148 Record->setAbstract(true);
2149 }
2150
2151 if (Record->isAbstract())
2152 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002153}
2154
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002155void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002156 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002157 SourceLocation LBrac,
2158 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002159 if (!TagDecl)
2160 return;
Mike Stump11289f42009-09-09 15:08:12 +00002161
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002162 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002163
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002164 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002165 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00002166 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00002167
Douglas Gregorc99f1552009-12-03 18:33:45 +00002168 CheckCompletedCXXClass(
2169 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002170}
2171
Douglas Gregor05379422008-11-03 17:51:48 +00002172/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2173/// special functions, such as the default constructor, copy
2174/// constructor, or destructor, to the given C++ class (C++
2175/// [special]p1). This routine can only be executed just before the
2176/// definition of the class is complete.
2177void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002178 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002179 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002180
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002181 // FIXME: Implicit declarations have exception specifications, which are
2182 // the union of the specifications of the implicitly called functions.
2183
Douglas Gregor05379422008-11-03 17:51:48 +00002184 if (!ClassDecl->hasUserDeclaredConstructor()) {
2185 // C++ [class.ctor]p5:
2186 // A default constructor for a class X is a constructor of class X
2187 // that can be called without an argument. If there is no
2188 // user-declared constructor for class X, a default constructor is
2189 // implicitly declared. An implicitly-declared default constructor
2190 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002191 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002192 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002193 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002194 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002195 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002196 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002197 0, 0, false, 0,
2198 /*FIXME*/false, false,
2199 0, 0, false,
2200 CC_Default),
John McCallbcd03502009-12-07 02:54:59 +00002201 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002202 /*isExplicit=*/false,
2203 /*isInline=*/true,
2204 /*isImplicitlyDeclared=*/true);
2205 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002206 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002207 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002208 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002209 }
2210
2211 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2212 // C++ [class.copy]p4:
2213 // If the class definition does not explicitly declare a copy
2214 // constructor, one is declared implicitly.
2215
2216 // C++ [class.copy]p5:
2217 // The implicitly-declared copy constructor for a class X will
2218 // have the form
2219 //
2220 // X::X(const X&)
2221 //
2222 // if
2223 bool HasConstCopyConstructor = true;
2224
2225 // -- each direct or virtual base class B of X has a copy
2226 // constructor whose first parameter is of type const B& or
2227 // const volatile B&, and
2228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2229 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2230 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002231 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002232 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002233 = BaseClassDecl->hasConstCopyConstructor(Context);
2234 }
2235
2236 // -- for all the nonstatic data members of X that are of a
2237 // class type M (or array thereof), each such class type
2238 // has a copy constructor whose first parameter is of type
2239 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002240 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2241 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002242 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002243 QualType FieldType = (*Field)->getType();
2244 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2245 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002246 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002247 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002248 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002249 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002250 = FieldClassDecl->hasConstCopyConstructor(Context);
2251 }
2252 }
2253
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002254 // Otherwise, the implicitly declared copy constructor will have
2255 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002256 //
2257 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002258 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002259 if (HasConstCopyConstructor)
2260 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002261 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002262
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002263 // An implicitly-declared copy constructor is an inline public
2264 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002265 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002266 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002267 CXXConstructorDecl *CopyConstructor
2268 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002269 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002270 Context.getFunctionType(Context.VoidTy,
2271 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002272 false, 0,
2273 /*FIXME:*/false,
2274 false, 0, 0, false,
2275 CC_Default),
John McCallbcd03502009-12-07 02:54:59 +00002276 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002277 /*isExplicit=*/false,
2278 /*isInline=*/true,
2279 /*isImplicitlyDeclared=*/true);
2280 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002281 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002282 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002283
2284 // Add the parameter to the constructor.
2285 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2286 ClassDecl->getLocation(),
2287 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002288 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002289 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002290 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002291 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002292 }
2293
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002294 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2295 // Note: The following rules are largely analoguous to the copy
2296 // constructor rules. Note that virtual bases are not taken into account
2297 // for determining the argument type of the operator. Note also that
2298 // operators taking an object instead of a reference are allowed.
2299 //
2300 // C++ [class.copy]p10:
2301 // If the class definition does not explicitly declare a copy
2302 // assignment operator, one is declared implicitly.
2303 // The implicitly-defined copy assignment operator for a class X
2304 // will have the form
2305 //
2306 // X& X::operator=(const X&)
2307 //
2308 // if
2309 bool HasConstCopyAssignment = true;
2310
2311 // -- each direct base class B of X has a copy assignment operator
2312 // whose parameter is of type const B&, const volatile B& or B,
2313 // and
2314 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2315 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002316 assert(!Base->getType()->isDependentType() &&
2317 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002318 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002319 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002320 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002321 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002322 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002323 }
2324
2325 // -- for all the nonstatic data members of X that are of a class
2326 // type M (or array thereof), each such class type has a copy
2327 // assignment operator whose parameter is of type const M&,
2328 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002329 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2330 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002331 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002332 QualType FieldType = (*Field)->getType();
2333 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2334 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002335 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002336 const CXXRecordDecl *FieldClassDecl
2337 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002338 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002339 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002340 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002341 }
2342 }
2343
2344 // Otherwise, the implicitly declared copy assignment operator will
2345 // have the form
2346 //
2347 // X& X::operator=(X&)
2348 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002349 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002350 if (HasConstCopyAssignment)
2351 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002352 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002353
2354 // An implicitly-declared copy assignment operator is an inline public
2355 // member of its class.
2356 DeclarationName Name =
2357 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2358 CXXMethodDecl *CopyAssignment =
2359 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2360 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002361 false, 0,
2362 /*FIXME:*/false,
2363 false, 0, 0, false,
2364 CC_Default),
John McCallbcd03502009-12-07 02:54:59 +00002365 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002366 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002367 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002368 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002369 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002370
2371 // Add the parameter to the operator.
2372 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2373 ClassDecl->getLocation(),
2374 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002375 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002376 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002377 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002378
2379 // Don't call addedAssignmentOperator. There is no way to distinguish an
2380 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002381 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002382 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002383 }
2384
Douglas Gregor1349b452008-12-15 21:24:18 +00002385 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002386 // C++ [class.dtor]p2:
2387 // If a class has no user-declared destructor, a destructor is
2388 // declared implicitly. An implicitly-declared destructor is an
2389 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002390 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002391 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002392 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002393 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002394 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002395 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002396 0, 0, false, 0,
2397 /*FIXME:*/false,
2398 false, 0, 0, false,
2399 CC_Default),
Douglas Gregor831c93f2008-11-05 20:51:48 +00002400 /*isInline=*/true,
2401 /*isImplicitlyDeclared=*/true);
2402 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002403 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002404 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002405 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002406
2407 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002408 }
Douglas Gregor05379422008-11-03 17:51:48 +00002409}
2410
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002411void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002412 Decl *D = TemplateD.getAs<Decl>();
2413 if (!D)
2414 return;
2415
2416 TemplateParameterList *Params = 0;
2417 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2418 Params = Template->getTemplateParameters();
2419 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2420 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2421 Params = PartialSpec->getTemplateParameters();
2422 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002423 return;
2424
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002425 for (TemplateParameterList::iterator Param = Params->begin(),
2426 ParamEnd = Params->end();
2427 Param != ParamEnd; ++Param) {
2428 NamedDecl *Named = cast<NamedDecl>(*Param);
2429 if (Named->getDeclName()) {
2430 S->AddDecl(DeclPtrTy::make(Named));
2431 IdResolver.AddDecl(Named);
2432 }
2433 }
2434}
2435
John McCall6df5fef2009-12-19 10:49:29 +00002436void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2437 if (!RecordD) return;
2438 AdjustDeclIfTemplate(RecordD);
2439 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2440 PushDeclContext(S, Record);
2441}
2442
2443void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2444 if (!RecordD) return;
2445 PopDeclContext();
2446}
2447
Douglas Gregor4d87df52008-12-16 21:30:33 +00002448/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2449/// parsing a top-level (non-nested) C++ class, and we are now
2450/// parsing those parts of the given Method declaration that could
2451/// not be parsed earlier (C++ [class.mem]p2), such as default
2452/// arguments. This action should enter the scope of the given
2453/// Method declaration as if we had just parsed the qualified method
2454/// name. However, it should not bring the parameters into scope;
2455/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002456void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002457}
2458
2459/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2460/// C++ method declaration. We're (re-)introducing the given
2461/// function parameter into scope for use in parsing later parts of
2462/// the method declaration. For example, we could see an
2463/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002464void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002465 if (!ParamD)
2466 return;
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattner83f095c2009-03-28 19:18:32 +00002468 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002469
2470 // If this parameter has an unparsed default argument, clear it out
2471 // to make way for the parsed default argument.
2472 if (Param->hasUnparsedDefaultArg())
2473 Param->setDefaultArg(0);
2474
Chris Lattner83f095c2009-03-28 19:18:32 +00002475 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002476 if (Param->getDeclName())
2477 IdResolver.AddDecl(Param);
2478}
2479
2480/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2481/// processing the delayed method declaration for Method. The method
2482/// declaration is now considered finished. There may be a separate
2483/// ActOnStartOfFunctionDef action later (not necessarily
2484/// immediately!) for this method, if it was also defined inside the
2485/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002486void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002487 if (!MethodD)
2488 return;
Mike Stump11289f42009-09-09 15:08:12 +00002489
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002490 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Chris Lattner83f095c2009-03-28 19:18:32 +00002492 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002493
2494 // Now that we have our default arguments, check the constructor
2495 // again. It could produce additional diagnostics or affect whether
2496 // the class has implicitly-declared destructors, among other
2497 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002498 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2499 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002500
2501 // Check the default arguments, which we may have added.
2502 if (!Method->isInvalidDecl())
2503 CheckCXXDefaultArguments(Method);
2504}
2505
Douglas Gregor831c93f2008-11-05 20:51:48 +00002506/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002507/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002508/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002509/// emit diagnostics and set the invalid bit to true. In any case, the type
2510/// will be updated to reflect a well-formed type for the constructor and
2511/// returned.
2512QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2513 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002514 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002515
2516 // C++ [class.ctor]p3:
2517 // A constructor shall not be virtual (10.3) or static (9.4). A
2518 // constructor can be invoked for a const, volatile or const
2519 // volatile object. A constructor shall not be declared const,
2520 // volatile, or const volatile (9.3.2).
2521 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002522 if (!D.isInvalidType())
2523 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2524 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2525 << SourceRange(D.getIdentifierLoc());
2526 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002527 }
2528 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002529 if (!D.isInvalidType())
2530 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2531 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2532 << SourceRange(D.getIdentifierLoc());
2533 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002534 SC = FunctionDecl::None;
2535 }
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chris Lattner38378bf2009-04-25 08:28:21 +00002537 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2538 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002539 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002540 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2541 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002542 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002543 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2544 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002545 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002546 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2547 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002548 }
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregor831c93f2008-11-05 20:51:48 +00002550 // Rebuild the function type "R" without any type qualifiers (in
2551 // case any of the errors above fired) and with "void" as the
2552 // return type, since constructors don't have return types. We
2553 // *always* have to do this, because GetTypeForDeclarator will
2554 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002555 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002556 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2557 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002558 Proto->isVariadic(), 0,
2559 Proto->hasExceptionSpec(),
2560 Proto->hasAnyExceptionSpec(),
2561 Proto->getNumExceptions(),
2562 Proto->exception_begin(),
2563 Proto->getNoReturnAttr(),
2564 Proto->getCallConv());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002565}
2566
Douglas Gregor4d87df52008-12-16 21:30:33 +00002567/// CheckConstructor - Checks a fully-formed constructor for
2568/// well-formedness, issuing any diagnostics required. Returns true if
2569/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002570void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002571 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002572 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2573 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002574 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002575
2576 // C++ [class.copy]p3:
2577 // A declaration of a constructor for a class X is ill-formed if
2578 // its first parameter is of type (optionally cv-qualified) X and
2579 // either there are no other parameters or else all other
2580 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002581 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002582 ((Constructor->getNumParams() == 1) ||
2583 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002584 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2585 Constructor->getTemplateSpecializationKind()
2586 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002587 QualType ParamType = Constructor->getParamDecl(0)->getType();
2588 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2589 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002590 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2591 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002592 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002593
2594 // FIXME: Rather that making the constructor invalid, we should endeavor
2595 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002596 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002597 }
2598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Douglas Gregor4d87df52008-12-16 21:30:33 +00002600 // Notify the class that we've added a constructor.
2601 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002602}
2603
Anders Carlsson26a807d2009-11-30 21:24:50 +00002604/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2605/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002606bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002607 CXXRecordDecl *RD = Destructor->getParent();
2608
2609 if (Destructor->isVirtual()) {
2610 SourceLocation Loc;
2611
2612 if (!Destructor->isImplicit())
2613 Loc = Destructor->getLocation();
2614 else
2615 Loc = RD->getLocation();
2616
2617 // If we have a virtual destructor, look up the deallocation function
2618 FunctionDecl *OperatorDelete = 0;
2619 DeclarationName Name =
2620 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002621 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002622 return true;
2623
2624 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002625 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002626
2627 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002628}
2629
Mike Stump11289f42009-09-09 15:08:12 +00002630static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002631FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2632 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2633 FTI.ArgInfo[0].Param &&
2634 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2635}
2636
Douglas Gregor831c93f2008-11-05 20:51:48 +00002637/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2638/// the well-formednes of the destructor declarator @p D with type @p
2639/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002640/// emit diagnostics and set the declarator to invalid. Even if this happens,
2641/// will be updated to reflect a well-formed type for the destructor and
2642/// returned.
2643QualType Sema::CheckDestructorDeclarator(Declarator &D,
2644 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002645 // C++ [class.dtor]p1:
2646 // [...] A typedef-name that names a class is a class-name
2647 // (7.1.3); however, a typedef-name that names a class shall not
2648 // be used as the identifier in the declarator for a destructor
2649 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002650 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002651 if (isa<TypedefType>(DeclaratorType)) {
2652 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002653 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002654 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002655 }
2656
2657 // C++ [class.dtor]p2:
2658 // A destructor is used to destroy objects of its class type. A
2659 // destructor takes no parameters, and no return type can be
2660 // specified for it (not even void). The address of a destructor
2661 // shall not be taken. A destructor shall not be static. A
2662 // destructor can be invoked for a const, volatile or const
2663 // volatile object. A destructor shall not be declared const,
2664 // volatile or const volatile (9.3.2).
2665 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002666 if (!D.isInvalidType())
2667 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2668 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2669 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002670 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002671 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002672 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002673 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002674 // Destructors don't have return types, but the parser will
2675 // happily parse something like:
2676 //
2677 // class X {
2678 // float ~X();
2679 // };
2680 //
2681 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002682 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2683 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2684 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002685 }
Mike Stump11289f42009-09-09 15:08:12 +00002686
Chris Lattner38378bf2009-04-25 08:28:21 +00002687 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2688 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002689 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002690 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2691 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002692 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002693 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2694 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002695 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002696 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2697 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002698 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002699 }
2700
2701 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002702 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002703 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2704
2705 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002706 FTI.freeArgs();
2707 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002708 }
2709
Mike Stump11289f42009-09-09 15:08:12 +00002710 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002711 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002712 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002713 D.setInvalidType();
2714 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002715
2716 // Rebuild the function type "R" without any type qualifiers or
2717 // parameters (in case any of the errors above fired) and with
2718 // "void" as the return type, since destructors don't have return
2719 // types. We *always* have to do this, because GetTypeForDeclarator
2720 // will put in a result type of "int" when none was specified.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002721 // FIXME: Exceptions!
2722 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2723 false, false, 0, 0, false, CC_Default);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002724}
2725
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002726/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2727/// well-formednes of the conversion function declarator @p D with
2728/// type @p R. If there are any errors in the declarator, this routine
2729/// will emit diagnostics and return true. Otherwise, it will return
2730/// false. Either way, the type @p R will be updated to reflect a
2731/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002732void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002733 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002734 // C++ [class.conv.fct]p1:
2735 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002736 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002737 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002738 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002739 if (!D.isInvalidType())
2740 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2741 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2742 << SourceRange(D.getIdentifierLoc());
2743 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002744 SC = FunctionDecl::None;
2745 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002746 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002747 // Conversion functions don't have return types, but the parser will
2748 // happily parse something like:
2749 //
2750 // class X {
2751 // float operator bool();
2752 // };
2753 //
2754 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002755 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2756 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2757 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002758 }
2759
2760 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002761 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002762 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2763
2764 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002765 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002766 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002767 }
2768
Mike Stump11289f42009-09-09 15:08:12 +00002769 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002770 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002771 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002772 D.setInvalidType();
2773 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002774
2775 // C++ [class.conv.fct]p4:
2776 // The conversion-type-id shall not represent a function type nor
2777 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002778 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002779 if (ConvType->isArrayType()) {
2780 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2781 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002782 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002783 } else if (ConvType->isFunctionType()) {
2784 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2785 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002786 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002787 }
2788
2789 // Rebuild the function type "R" without any parameters (in case any
2790 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002791 // return type.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002792 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002793 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002794 Proto->getTypeQuals(),
2795 Proto->hasExceptionSpec(),
2796 Proto->hasAnyExceptionSpec(),
2797 Proto->getNumExceptions(),
2798 Proto->exception_begin(),
2799 Proto->getNoReturnAttr(),
2800 Proto->getCallConv());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002801
Douglas Gregor5fb53972009-01-14 15:45:31 +00002802 // C++0x explicit conversion operators.
2803 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002804 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002805 diag::warn_explicit_conversion_functions)
2806 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002807}
2808
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002809/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2810/// the declaration of the given C++ conversion function. This routine
2811/// is responsible for recording the conversion function in the C++
2812/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002813Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002814 assert(Conversion && "Expected to receive a conversion function declaration");
2815
Douglas Gregor4287b372008-12-12 08:25:50 +00002816 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002817
2818 // Make sure we aren't redeclaring the conversion function.
2819 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002820
2821 // C++ [class.conv.fct]p1:
2822 // [...] A conversion function is never used to convert a
2823 // (possibly cv-qualified) object to the (possibly cv-qualified)
2824 // same object type (or a reference to it), to a (possibly
2825 // cv-qualified) base class of that type (or a reference to it),
2826 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002827 // FIXME: Suppress this warning if the conversion function ends up being a
2828 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002829 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002830 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002831 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002832 ConvType = ConvTypeRef->getPointeeType();
2833 if (ConvType->isRecordType()) {
2834 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2835 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002836 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002837 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002838 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002839 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002840 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002841 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002842 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002843 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002844 }
2845
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002846 if (Conversion->getPrimaryTemplate()) {
2847 // ignore specializations
2848 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00002849 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00002850 = Conversion->getDescribedFunctionTemplate()) {
2851 if (ClassDecl->replaceConversion(
2852 ConversionTemplate->getPreviousDeclaration(),
2853 ConversionTemplate))
2854 return DeclPtrTy::make(ConversionTemplate);
2855 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2856 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00002857 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002858 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002859 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002860 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002861 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002862 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002863 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002864
Chris Lattner83f095c2009-03-28 19:18:32 +00002865 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002866}
2867
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002868//===----------------------------------------------------------------------===//
2869// Namespace Handling
2870//===----------------------------------------------------------------------===//
2871
2872/// ActOnStartNamespaceDef - This is called at the start of a namespace
2873/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002874Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2875 SourceLocation IdentLoc,
2876 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00002877 SourceLocation LBrace,
2878 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002879 NamespaceDecl *Namespc =
2880 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2881 Namespc->setLBracLoc(LBrace);
2882
2883 Scope *DeclRegionScope = NamespcScope->getParent();
2884
Anders Carlssona7bcade2010-02-07 01:09:23 +00002885 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2886
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002887 if (II) {
2888 // C++ [namespace.def]p2:
2889 // The identifier in an original-namespace-definition shall not have been
2890 // previously defined in the declarative region in which the
2891 // original-namespace-definition appears. The identifier in an
2892 // original-namespace-definition is the name of the namespace. Subsequently
2893 // in that declarative region, it is treated as an original-namespace-name.
2894
John McCall9f3059a2009-10-09 21:13:30 +00002895 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002896 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002897 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002898
Douglas Gregor91f84212008-12-11 16:49:14 +00002899 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2900 // This is an extended namespace definition.
2901 // Attach this namespace decl to the chain of extended namespace
2902 // definitions.
2903 OrigNS->setNextNamespace(Namespc);
2904 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002905
Mike Stump11289f42009-09-09 15:08:12 +00002906 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002907 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002908 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002909 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002910 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002911 } else if (PrevDecl) {
2912 // This is an invalid name redefinition.
2913 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2914 << Namespc->getDeclName();
2915 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2916 Namespc->setInvalidDecl();
2917 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002918 } else if (II->isStr("std") &&
2919 CurContext->getLookupContext()->isTranslationUnit()) {
2920 // This is the first "real" definition of the namespace "std", so update
2921 // our cache of the "std" namespace to point at this definition.
2922 if (StdNamespace) {
2923 // We had already defined a dummy namespace "std". Link this new
2924 // namespace definition to the dummy namespace "std".
2925 StdNamespace->setNextNamespace(Namespc);
2926 StdNamespace->setLocation(IdentLoc);
2927 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2928 }
2929
2930 // Make our StdNamespace cache point at the first real definition of the
2931 // "std" namespace.
2932 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002933 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002934
2935 PushOnScopeChains(Namespc, DeclRegionScope);
2936 } else {
John McCall4fa53422009-10-01 00:25:31 +00002937 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00002938 assert(Namespc->isAnonymousNamespace());
2939 CurContext->addDecl(Namespc);
2940
2941 // Link the anonymous namespace into its parent.
2942 NamespaceDecl *PrevDecl;
2943 DeclContext *Parent = CurContext->getLookupContext();
2944 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2945 PrevDecl = TU->getAnonymousNamespace();
2946 TU->setAnonymousNamespace(Namespc);
2947 } else {
2948 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2949 PrevDecl = ND->getAnonymousNamespace();
2950 ND->setAnonymousNamespace(Namespc);
2951 }
2952
2953 // Link the anonymous namespace with its previous declaration.
2954 if (PrevDecl) {
2955 assert(PrevDecl->isAnonymousNamespace());
2956 assert(!PrevDecl->getNextNamespace());
2957 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2958 PrevDecl->setNextNamespace(Namespc);
2959 }
John McCall4fa53422009-10-01 00:25:31 +00002960
2961 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2962 // behaves as if it were replaced by
2963 // namespace unique { /* empty body */ }
2964 // using namespace unique;
2965 // namespace unique { namespace-body }
2966 // where all occurrences of 'unique' in a translation unit are
2967 // replaced by the same identifier and this identifier differs
2968 // from all other identifiers in the entire program.
2969
2970 // We just create the namespace with an empty name and then add an
2971 // implicit using declaration, just like the standard suggests.
2972 //
2973 // CodeGen enforces the "universally unique" aspect by giving all
2974 // declarations semantically contained within an anonymous
2975 // namespace internal linkage.
2976
John McCall0db42252009-12-16 02:06:49 +00002977 if (!PrevDecl) {
2978 UsingDirectiveDecl* UD
2979 = UsingDirectiveDecl::Create(Context, CurContext,
2980 /* 'using' */ LBrace,
2981 /* 'namespace' */ SourceLocation(),
2982 /* qualifier */ SourceRange(),
2983 /* NNS */ NULL,
2984 /* identifier */ SourceLocation(),
2985 Namespc,
2986 /* Ancestor */ CurContext);
2987 UD->setImplicit();
2988 CurContext->addDecl(UD);
2989 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002990 }
2991
2992 // Although we could have an invalid decl (i.e. the namespace name is a
2993 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002994 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2995 // for the namespace has the declarations that showed up in that particular
2996 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002997 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002998 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002999}
3000
Sebastian Redla6602e92009-11-23 15:34:23 +00003001/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3002/// is a namespace alias, returns the namespace it points to.
3003static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3004 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3005 return AD->getNamespace();
3006 return dyn_cast_or_null<NamespaceDecl>(D);
3007}
3008
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003009/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3010/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003011void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3012 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003013 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3014 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3015 Namespc->setRBracLoc(RBrace);
3016 PopDeclContext();
3017}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003018
Chris Lattner83f095c2009-03-28 19:18:32 +00003019Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3020 SourceLocation UsingLoc,
3021 SourceLocation NamespcLoc,
3022 const CXXScopeSpec &SS,
3023 SourceLocation IdentLoc,
3024 IdentifierInfo *NamespcName,
3025 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003026 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3027 assert(NamespcName && "Invalid NamespcName.");
3028 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003029 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003030
Douglas Gregor889ceb72009-02-03 19:21:40 +00003031 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003032
Douglas Gregor34074322009-01-14 22:20:51 +00003033 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003034 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3035 LookupParsedName(R, S, &SS);
3036 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003037 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003038
John McCall9f3059a2009-10-09 21:13:30 +00003039 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003040 NamedDecl *Named = R.getFoundDecl();
3041 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3042 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003043 // C++ [namespace.udir]p1:
3044 // A using-directive specifies that the names in the nominated
3045 // namespace can be used in the scope in which the
3046 // using-directive appears after the using-directive. During
3047 // unqualified name lookup (3.4.1), the names appear as if they
3048 // were declared in the nearest enclosing namespace which
3049 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003050 // namespace. [Note: in this context, "contains" means "contains
3051 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003052
3053 // Find enclosing context containing both using-directive and
3054 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003055 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003056 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3057 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3058 CommonAncestor = CommonAncestor->getParent();
3059
Sebastian Redla6602e92009-11-23 15:34:23 +00003060 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003061 SS.getRange(),
3062 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003063 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003064 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003065 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003066 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003067 }
3068
Douglas Gregor889ceb72009-02-03 19:21:40 +00003069 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003070 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003071 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003072}
3073
3074void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3075 // If scope has associated entity, then using directive is at namespace
3076 // or translation unit scope. We add UsingDirectiveDecls, into
3077 // it's lookup structure.
3078 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003079 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003080 else
3081 // Otherwise it is block-sope. using-directives will affect lookup
3082 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003083 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003084}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003085
Douglas Gregorfec52632009-06-20 00:51:54 +00003086
3087Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003088 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003089 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003090 SourceLocation UsingLoc,
3091 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003092 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003093 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003094 bool IsTypeName,
3095 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003096 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregor220f4272009-11-04 16:30:06 +00003098 switch (Name.getKind()) {
3099 case UnqualifiedId::IK_Identifier:
3100 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003101 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003102 case UnqualifiedId::IK_ConversionFunctionId:
3103 break;
3104
3105 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003106 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003107 // C++0x inherited constructors.
3108 if (getLangOptions().CPlusPlus0x) break;
3109
Douglas Gregor220f4272009-11-04 16:30:06 +00003110 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3111 << SS.getRange();
3112 return DeclPtrTy();
3113
3114 case UnqualifiedId::IK_DestructorName:
3115 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3116 << SS.getRange();
3117 return DeclPtrTy();
3118
3119 case UnqualifiedId::IK_TemplateId:
3120 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3121 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3122 return DeclPtrTy();
3123 }
3124
3125 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003126 if (!TargetName)
3127 return DeclPtrTy();
3128
John McCalla0097262009-12-11 02:10:03 +00003129 // Warn about using declarations.
3130 // TODO: store that the declaration was written without 'using' and
3131 // talk about access decls instead of using decls in the
3132 // diagnostics.
3133 if (!HasUsingKeyword) {
3134 UsingLoc = Name.getSourceRange().getBegin();
3135
3136 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3137 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3138 "using ");
3139 }
3140
John McCall3f746822009-11-17 05:59:44 +00003141 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003142 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003143 TargetName, AttrList,
3144 /* IsInstantiation */ false,
3145 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003146 if (UD)
3147 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003148
Anders Carlsson696a3f12009-08-28 05:40:36 +00003149 return DeclPtrTy::make(UD);
3150}
3151
John McCall84d87672009-12-10 09:41:52 +00003152/// Determines whether to create a using shadow decl for a particular
3153/// decl, given the set of decls existing prior to this using lookup.
3154bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3155 const LookupResult &Previous) {
3156 // Diagnose finding a decl which is not from a base class of the
3157 // current class. We do this now because there are cases where this
3158 // function will silently decide not to build a shadow decl, which
3159 // will pre-empt further diagnostics.
3160 //
3161 // We don't need to do this in C++0x because we do the check once on
3162 // the qualifier.
3163 //
3164 // FIXME: diagnose the following if we care enough:
3165 // struct A { int foo; };
3166 // struct B : A { using A::foo; };
3167 // template <class T> struct C : A {};
3168 // template <class T> struct D : C<T> { using B::foo; } // <---
3169 // This is invalid (during instantiation) in C++03 because B::foo
3170 // resolves to the using decl in B, which is not a base class of D<T>.
3171 // We can't diagnose it immediately because C<T> is an unknown
3172 // specialization. The UsingShadowDecl in D<T> then points directly
3173 // to A::foo, which will look well-formed when we instantiate.
3174 // The right solution is to not collapse the shadow-decl chain.
3175 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3176 DeclContext *OrigDC = Orig->getDeclContext();
3177
3178 // Handle enums and anonymous structs.
3179 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3180 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3181 while (OrigRec->isAnonymousStructOrUnion())
3182 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3183
3184 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3185 if (OrigDC == CurContext) {
3186 Diag(Using->getLocation(),
3187 diag::err_using_decl_nested_name_specifier_is_current_class)
3188 << Using->getNestedNameRange();
3189 Diag(Orig->getLocation(), diag::note_using_decl_target);
3190 return true;
3191 }
3192
3193 Diag(Using->getNestedNameRange().getBegin(),
3194 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3195 << Using->getTargetNestedNameDecl()
3196 << cast<CXXRecordDecl>(CurContext)
3197 << Using->getNestedNameRange();
3198 Diag(Orig->getLocation(), diag::note_using_decl_target);
3199 return true;
3200 }
3201 }
3202
3203 if (Previous.empty()) return false;
3204
3205 NamedDecl *Target = Orig;
3206 if (isa<UsingShadowDecl>(Target))
3207 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3208
John McCalla17e83e2009-12-11 02:33:26 +00003209 // If the target happens to be one of the previous declarations, we
3210 // don't have a conflict.
3211 //
3212 // FIXME: but we might be increasing its access, in which case we
3213 // should redeclare it.
3214 NamedDecl *NonTag = 0, *Tag = 0;
3215 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3216 I != E; ++I) {
3217 NamedDecl *D = (*I)->getUnderlyingDecl();
3218 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3219 return false;
3220
3221 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3222 }
3223
John McCall84d87672009-12-10 09:41:52 +00003224 if (Target->isFunctionOrFunctionTemplate()) {
3225 FunctionDecl *FD;
3226 if (isa<FunctionTemplateDecl>(Target))
3227 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3228 else
3229 FD = cast<FunctionDecl>(Target);
3230
3231 NamedDecl *OldDecl = 0;
3232 switch (CheckOverload(FD, Previous, OldDecl)) {
3233 case Ovl_Overload:
3234 return false;
3235
3236 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003237 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003238 break;
3239
3240 // We found a decl with the exact signature.
3241 case Ovl_Match:
3242 if (isa<UsingShadowDecl>(OldDecl)) {
3243 // Silently ignore the possible conflict.
3244 return false;
3245 }
3246
3247 // If we're in a record, we want to hide the target, so we
3248 // return true (without a diagnostic) to tell the caller not to
3249 // build a shadow decl.
3250 if (CurContext->isRecord())
3251 return true;
3252
3253 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003254 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003255 break;
3256 }
3257
3258 Diag(Target->getLocation(), diag::note_using_decl_target);
3259 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3260 return true;
3261 }
3262
3263 // Target is not a function.
3264
John McCall84d87672009-12-10 09:41:52 +00003265 if (isa<TagDecl>(Target)) {
3266 // No conflict between a tag and a non-tag.
3267 if (!Tag) return false;
3268
John McCalle29c5cd2009-12-10 19:51:03 +00003269 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003270 Diag(Target->getLocation(), diag::note_using_decl_target);
3271 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3272 return true;
3273 }
3274
3275 // No conflict between a tag and a non-tag.
3276 if (!NonTag) return false;
3277
John McCalle29c5cd2009-12-10 19:51:03 +00003278 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003279 Diag(Target->getLocation(), diag::note_using_decl_target);
3280 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3281 return true;
3282}
3283
John McCall3f746822009-11-17 05:59:44 +00003284/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003285UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003286 UsingDecl *UD,
3287 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003288
3289 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003290 NamedDecl *Target = Orig;
3291 if (isa<UsingShadowDecl>(Target)) {
3292 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3293 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003294 }
3295
3296 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003297 = UsingShadowDecl::Create(Context, CurContext,
3298 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003299 UD->addShadowDecl(Shadow);
3300
3301 if (S)
John McCall3969e302009-12-08 07:46:18 +00003302 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003303 else
John McCall3969e302009-12-08 07:46:18 +00003304 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003305 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003306
John McCall3969e302009-12-08 07:46:18 +00003307 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3308 Shadow->setInvalidDecl();
3309
John McCall84d87672009-12-10 09:41:52 +00003310 return Shadow;
3311}
John McCall3969e302009-12-08 07:46:18 +00003312
John McCall84d87672009-12-10 09:41:52 +00003313/// Hides a using shadow declaration. This is required by the current
3314/// using-decl implementation when a resolvable using declaration in a
3315/// class is followed by a declaration which would hide or override
3316/// one or more of the using decl's targets; for example:
3317///
3318/// struct Base { void foo(int); };
3319/// struct Derived : Base {
3320/// using Base::foo;
3321/// void foo(int);
3322/// };
3323///
3324/// The governing language is C++03 [namespace.udecl]p12:
3325///
3326/// When a using-declaration brings names from a base class into a
3327/// derived class scope, member functions in the derived class
3328/// override and/or hide member functions with the same name and
3329/// parameter types in a base class (rather than conflicting).
3330///
3331/// There are two ways to implement this:
3332/// (1) optimistically create shadow decls when they're not hidden
3333/// by existing declarations, or
3334/// (2) don't create any shadow decls (or at least don't make them
3335/// visible) until we've fully parsed/instantiated the class.
3336/// The problem with (1) is that we might have to retroactively remove
3337/// a shadow decl, which requires several O(n) operations because the
3338/// decl structures are (very reasonably) not designed for removal.
3339/// (2) avoids this but is very fiddly and phase-dependent.
3340void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3341 // Remove it from the DeclContext...
3342 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003343
John McCall84d87672009-12-10 09:41:52 +00003344 // ...and the scope, if applicable...
3345 if (S) {
3346 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3347 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003348 }
3349
John McCall84d87672009-12-10 09:41:52 +00003350 // ...and the using decl.
3351 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3352
3353 // TODO: complain somehow if Shadow was used. It shouldn't
3354 // be possible for this to happen, because
John McCall3f746822009-11-17 05:59:44 +00003355}
3356
John McCalle61f2ba2009-11-18 02:36:19 +00003357/// Builds a using declaration.
3358///
3359/// \param IsInstantiation - Whether this call arises from an
3360/// instantiation of an unresolved using declaration. We treat
3361/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003362NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3363 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003364 const CXXScopeSpec &SS,
3365 SourceLocation IdentLoc,
3366 DeclarationName Name,
3367 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003368 bool IsInstantiation,
3369 bool IsTypeName,
3370 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003371 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3372 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003373
Anders Carlssonf038fc22009-08-28 05:49:21 +00003374 // FIXME: We ignore attributes for now.
3375 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003376
Anders Carlsson59140b32009-08-28 03:16:11 +00003377 if (SS.isEmpty()) {
3378 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003379 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003380 }
Mike Stump11289f42009-09-09 15:08:12 +00003381
John McCall84d87672009-12-10 09:41:52 +00003382 // Do the redeclaration lookup in the current scope.
3383 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3384 ForRedeclaration);
3385 Previous.setHideTags(false);
3386 if (S) {
3387 LookupName(Previous, S);
3388
3389 // It is really dumb that we have to do this.
3390 LookupResult::Filter F = Previous.makeFilter();
3391 while (F.hasNext()) {
3392 NamedDecl *D = F.next();
3393 if (!isDeclInScope(D, CurContext, S))
3394 F.erase();
3395 }
3396 F.done();
3397 } else {
3398 assert(IsInstantiation && "no scope in non-instantiation");
3399 assert(CurContext->isRecord() && "scope not record in instantiation");
3400 LookupQualifiedName(Previous, CurContext);
3401 }
3402
Mike Stump11289f42009-09-09 15:08:12 +00003403 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003404 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3405
John McCall84d87672009-12-10 09:41:52 +00003406 // Check for invalid redeclarations.
3407 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3408 return 0;
3409
3410 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003411 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3412 return 0;
3413
John McCall84c16cf2009-11-12 03:15:40 +00003414 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003415 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003416 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003417 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003418 // FIXME: not all declaration name kinds are legal here
3419 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3420 UsingLoc, TypenameLoc,
3421 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003422 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003423 } else {
3424 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3425 UsingLoc, SS.getRange(), NNS,
3426 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003427 }
John McCallb96ec562009-12-04 22:46:56 +00003428 } else {
3429 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3430 SS.getRange(), UsingLoc, NNS, Name,
3431 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003432 }
John McCallb96ec562009-12-04 22:46:56 +00003433 D->setAccess(AS);
3434 CurContext->addDecl(D);
3435
3436 if (!LookupContext) return D;
3437 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003438
John McCall3969e302009-12-08 07:46:18 +00003439 if (RequireCompleteDeclContext(SS)) {
3440 UD->setInvalidDecl();
3441 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003442 }
3443
John McCall3969e302009-12-08 07:46:18 +00003444 // Look up the target name.
3445
John McCall27b18f82009-11-17 02:14:36 +00003446 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003447
John McCall3969e302009-12-08 07:46:18 +00003448 // Unlike most lookups, we don't always want to hide tag
3449 // declarations: tag names are visible through the using declaration
3450 // even if hidden by ordinary names, *except* in a dependent context
3451 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003452 if (!IsInstantiation)
3453 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003454
John McCall27b18f82009-11-17 02:14:36 +00003455 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003456
John McCall9f3059a2009-10-09 21:13:30 +00003457 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003458 Diag(IdentLoc, diag::err_no_member)
3459 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003460 UD->setInvalidDecl();
3461 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003462 }
3463
John McCallb96ec562009-12-04 22:46:56 +00003464 if (R.isAmbiguous()) {
3465 UD->setInvalidDecl();
3466 return UD;
3467 }
Mike Stump11289f42009-09-09 15:08:12 +00003468
John McCalle61f2ba2009-11-18 02:36:19 +00003469 if (IsTypeName) {
3470 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003471 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003472 Diag(IdentLoc, diag::err_using_typename_non_type);
3473 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3474 Diag((*I)->getUnderlyingDecl()->getLocation(),
3475 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003476 UD->setInvalidDecl();
3477 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003478 }
3479 } else {
3480 // If we asked for a non-typename and we got a type, error out,
3481 // but only if this is an instantiation of an unresolved using
3482 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003483 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003484 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3485 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003486 UD->setInvalidDecl();
3487 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003488 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003489 }
3490
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003491 // C++0x N2914 [namespace.udecl]p6:
3492 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003493 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003494 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3495 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003496 UD->setInvalidDecl();
3497 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
John McCall84d87672009-12-10 09:41:52 +00003500 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3501 if (!CheckUsingShadowDecl(UD, *I, Previous))
3502 BuildUsingShadowDecl(S, UD, *I);
3503 }
John McCall3f746822009-11-17 05:59:44 +00003504
3505 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003506}
3507
John McCall84d87672009-12-10 09:41:52 +00003508/// Checks that the given using declaration is not an invalid
3509/// redeclaration. Note that this is checking only for the using decl
3510/// itself, not for any ill-formedness among the UsingShadowDecls.
3511bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3512 bool isTypeName,
3513 const CXXScopeSpec &SS,
3514 SourceLocation NameLoc,
3515 const LookupResult &Prev) {
3516 // C++03 [namespace.udecl]p8:
3517 // C++0x [namespace.udecl]p10:
3518 // A using-declaration is a declaration and can therefore be used
3519 // repeatedly where (and only where) multiple declarations are
3520 // allowed.
3521 // That's only in file contexts.
3522 if (CurContext->getLookupContext()->isFileContext())
3523 return false;
3524
3525 NestedNameSpecifier *Qual
3526 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3527
3528 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3529 NamedDecl *D = *I;
3530
3531 bool DTypename;
3532 NestedNameSpecifier *DQual;
3533 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3534 DTypename = UD->isTypeName();
3535 DQual = UD->getTargetNestedNameDecl();
3536 } else if (UnresolvedUsingValueDecl *UD
3537 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3538 DTypename = false;
3539 DQual = UD->getTargetNestedNameSpecifier();
3540 } else if (UnresolvedUsingTypenameDecl *UD
3541 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3542 DTypename = true;
3543 DQual = UD->getTargetNestedNameSpecifier();
3544 } else continue;
3545
3546 // using decls differ if one says 'typename' and the other doesn't.
3547 // FIXME: non-dependent using decls?
3548 if (isTypeName != DTypename) continue;
3549
3550 // using decls differ if they name different scopes (but note that
3551 // template instantiation can cause this check to trigger when it
3552 // didn't before instantiation).
3553 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3554 Context.getCanonicalNestedNameSpecifier(DQual))
3555 continue;
3556
3557 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003558 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003559 return true;
3560 }
3561
3562 return false;
3563}
3564
John McCall3969e302009-12-08 07:46:18 +00003565
John McCallb96ec562009-12-04 22:46:56 +00003566/// Checks that the given nested-name qualifier used in a using decl
3567/// in the current context is appropriately related to the current
3568/// scope. If an error is found, diagnoses it and returns true.
3569bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3570 const CXXScopeSpec &SS,
3571 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003572 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003573
John McCall3969e302009-12-08 07:46:18 +00003574 if (!CurContext->isRecord()) {
3575 // C++03 [namespace.udecl]p3:
3576 // C++0x [namespace.udecl]p8:
3577 // A using-declaration for a class member shall be a member-declaration.
3578
3579 // If we weren't able to compute a valid scope, it must be a
3580 // dependent class scope.
3581 if (!NamedContext || NamedContext->isRecord()) {
3582 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3583 << SS.getRange();
3584 return true;
3585 }
3586
3587 // Otherwise, everything is known to be fine.
3588 return false;
3589 }
3590
3591 // The current scope is a record.
3592
3593 // If the named context is dependent, we can't decide much.
3594 if (!NamedContext) {
3595 // FIXME: in C++0x, we can diagnose if we can prove that the
3596 // nested-name-specifier does not refer to a base class, which is
3597 // still possible in some cases.
3598
3599 // Otherwise we have to conservatively report that things might be
3600 // okay.
3601 return false;
3602 }
3603
3604 if (!NamedContext->isRecord()) {
3605 // Ideally this would point at the last name in the specifier,
3606 // but we don't have that level of source info.
3607 Diag(SS.getRange().getBegin(),
3608 diag::err_using_decl_nested_name_specifier_is_not_class)
3609 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3610 return true;
3611 }
3612
3613 if (getLangOptions().CPlusPlus0x) {
3614 // C++0x [namespace.udecl]p3:
3615 // In a using-declaration used as a member-declaration, the
3616 // nested-name-specifier shall name a base class of the class
3617 // being defined.
3618
3619 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3620 cast<CXXRecordDecl>(NamedContext))) {
3621 if (CurContext == NamedContext) {
3622 Diag(NameLoc,
3623 diag::err_using_decl_nested_name_specifier_is_current_class)
3624 << SS.getRange();
3625 return true;
3626 }
3627
3628 Diag(SS.getRange().getBegin(),
3629 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3630 << (NestedNameSpecifier*) SS.getScopeRep()
3631 << cast<CXXRecordDecl>(CurContext)
3632 << SS.getRange();
3633 return true;
3634 }
3635
3636 return false;
3637 }
3638
3639 // C++03 [namespace.udecl]p4:
3640 // A using-declaration used as a member-declaration shall refer
3641 // to a member of a base class of the class being defined [etc.].
3642
3643 // Salient point: SS doesn't have to name a base class as long as
3644 // lookup only finds members from base classes. Therefore we can
3645 // diagnose here only if we can prove that that can't happen,
3646 // i.e. if the class hierarchies provably don't intersect.
3647
3648 // TODO: it would be nice if "definitely valid" results were cached
3649 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3650 // need to be repeated.
3651
3652 struct UserData {
3653 llvm::DenseSet<const CXXRecordDecl*> Bases;
3654
3655 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3656 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3657 Data->Bases.insert(Base);
3658 return true;
3659 }
3660
3661 bool hasDependentBases(const CXXRecordDecl *Class) {
3662 return !Class->forallBases(collect, this);
3663 }
3664
3665 /// Returns true if the base is dependent or is one of the
3666 /// accumulated base classes.
3667 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3668 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3669 return !Data->Bases.count(Base);
3670 }
3671
3672 bool mightShareBases(const CXXRecordDecl *Class) {
3673 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3674 }
3675 };
3676
3677 UserData Data;
3678
3679 // Returns false if we find a dependent base.
3680 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3681 return false;
3682
3683 // Returns false if the class has a dependent base or if it or one
3684 // of its bases is present in the base set of the current context.
3685 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3686 return false;
3687
3688 Diag(SS.getRange().getBegin(),
3689 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3690 << (NestedNameSpecifier*) SS.getScopeRep()
3691 << cast<CXXRecordDecl>(CurContext)
3692 << SS.getRange();
3693
3694 return true;
John McCallb96ec562009-12-04 22:46:56 +00003695}
3696
Mike Stump11289f42009-09-09 15:08:12 +00003697Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003698 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003699 SourceLocation AliasLoc,
3700 IdentifierInfo *Alias,
3701 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003702 SourceLocation IdentLoc,
3703 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003704
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003705 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003706 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3707 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003708
Anders Carlssondca83c42009-03-28 06:23:46 +00003709 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003710 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003711 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003712 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003713 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003714 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003715 if (!R.isAmbiguous() && !R.empty() &&
3716 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003717 return DeclPtrTy();
3718 }
Mike Stump11289f42009-09-09 15:08:12 +00003719
Anders Carlssondca83c42009-03-28 06:23:46 +00003720 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3721 diag::err_redefinition_different_kind;
3722 Diag(AliasLoc, DiagID) << Alias;
3723 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003724 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003725 }
3726
John McCall27b18f82009-11-17 02:14:36 +00003727 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003728 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003729
John McCall9f3059a2009-10-09 21:13:30 +00003730 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003731 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003732 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003733 }
Mike Stump11289f42009-09-09 15:08:12 +00003734
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003735 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003736 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3737 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003738 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003739 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003740
John McCalld8d0d432010-02-16 06:53:13 +00003741 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003742 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003743}
3744
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003745void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3746 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003747 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3748 !Constructor->isUsed()) &&
3749 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003750
Eli Friedman9cf6b592009-11-09 19:20:36 +00003751 CXXRecordDecl *ClassDecl
3752 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3753 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003754
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003755 DeclContext *PreviousContext = CurContext;
3756 CurContext = Constructor;
3757 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003758 Diag(CurrentLocation, diag::note_member_synthesized_at)
3759 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003760 Constructor->setInvalidDecl();
3761 } else {
3762 Constructor->setUsed();
3763 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003764 CurContext = PreviousContext;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003765}
3766
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003767void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003768 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003769 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3770 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003771 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003772 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003773
3774 DeclContext *PreviousContext = CurContext;
3775 CurContext = Destructor;
3776
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003777 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003778 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003779 // implicitly defined, all the implicitly-declared default destructors
3780 // for its base class and its non-static data members shall have been
3781 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003782 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3783 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003784 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003785 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003786 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003787 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003788 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3789 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3790 else
Mike Stump11289f42009-09-09 15:08:12 +00003791 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003792 "DefineImplicitDestructor - missing dtor in a base class");
3793 }
3794 }
Mike Stump11289f42009-09-09 15:08:12 +00003795
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003796 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3797 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003798 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3799 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3800 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003801 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003802 CXXRecordDecl *FieldClassDecl
3803 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3804 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003805 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003806 const_cast<CXXDestructorDecl*>(
3807 FieldClassDecl->getDestructor(Context)))
3808 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3809 else
Mike Stump11289f42009-09-09 15:08:12 +00003810 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003811 "DefineImplicitDestructor - missing dtor in class of a data member");
3812 }
3813 }
3814 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003815
3816 // FIXME: If CheckDestructor fails, we should emit a note about where the
3817 // implicit destructor was needed.
3818 if (CheckDestructor(Destructor)) {
3819 Diag(CurrentLocation, diag::note_member_synthesized_at)
3820 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3821
3822 Destructor->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003823 CurContext = PreviousContext;
3824
Anders Carlsson26a807d2009-11-30 21:24:50 +00003825 return;
3826 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003827 CurContext = PreviousContext;
Anders Carlsson26a807d2009-11-30 21:24:50 +00003828
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003829 Destructor->setUsed();
3830}
3831
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003832void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3833 CXXMethodDecl *MethodDecl) {
3834 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3835 MethodDecl->getOverloadedOperator() == OO_Equal &&
3836 !MethodDecl->isUsed()) &&
3837 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003838
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003839 CXXRecordDecl *ClassDecl
3840 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003841
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003842 DeclContext *PreviousContext = CurContext;
3843 CurContext = MethodDecl;
3844
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003845 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003846 // Before the implicitly-declared copy assignment operator for a class is
3847 // implicitly defined, all implicitly-declared copy assignment operators
3848 // for its direct base classes and its nonstatic data members shall have
3849 // been implicitly defined.
3850 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003851 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3852 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003853 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003854 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003855 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003856 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3857 BaseClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003858 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3859 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003860 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3861 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003862 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3863 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3864 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003865 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003866 CXXRecordDecl *FieldClassDecl
3867 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003868 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003869 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3870 FieldClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003871 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003872 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003873 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003874 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3875 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003876 Diag(CurrentLocation, diag::note_first_required_here);
3877 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003878 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003879 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003880 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3881 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003882 Diag(CurrentLocation, diag::note_first_required_here);
3883 err = true;
3884 }
3885 }
3886 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003887 MethodDecl->setUsed();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003888
3889 CurContext = PreviousContext;
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003890}
3891
3892CXXMethodDecl *
Anders Carlssonefa47322009-12-09 03:01:51 +00003893Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3894 ParmVarDecl *ParmDecl,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003895 CXXRecordDecl *ClassDecl) {
3896 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3897 QualType RHSType(LHSType);
3898 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003899 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003900 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003901 RHSType = Context.getCVRQualifiedType(RHSType,
3902 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003903 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003904 LHSType,
3905 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003906 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003907 RHSType,
3908 CurrentLocation));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003909 Expr *Args[2] = { &*LHS, &*RHS };
John McCallbc077cf2010-02-08 23:07:23 +00003910 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump11289f42009-09-09 15:08:12 +00003911 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003912 CandidateSet);
3913 OverloadCandidateSet::iterator Best;
Anders Carlssonefa47322009-12-09 03:01:51 +00003914 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003915 return cast<CXXMethodDecl>(Best->Function);
3916 assert(false &&
3917 "getAssignOperatorMethod - copy assignment operator method not found");
3918 return 0;
3919}
3920
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003921void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3922 CXXConstructorDecl *CopyConstructor,
3923 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003924 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00003925 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003926 !CopyConstructor->isUsed()) &&
3927 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003928
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003929 CXXRecordDecl *ClassDecl
3930 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3931 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003932
3933 DeclContext *PreviousContext = CurContext;
3934 CurContext = CopyConstructor;
3935
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003936 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003937 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003938 // implicitly defined, all the implicitly-declared copy constructors
3939 // for its base class and its non-static data members shall have been
3940 // implicitly defined.
3941 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3942 Base != ClassDecl->bases_end(); ++Base) {
3943 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003944 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003945 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003946 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003947 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003948 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003949 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3950 FieldEnd = ClassDecl->field_end();
3951 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003952 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3953 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3954 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003955 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003956 CXXRecordDecl *FieldClassDecl
3957 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003958 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003959 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003960 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003961 }
3962 }
3963 CopyConstructor->setUsed();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003964
3965 CurContext = PreviousContext;
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003966}
3967
Anders Carlsson6eb55572009-08-25 05:12:04 +00003968Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003969Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003970 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003971 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003972 bool RequiresZeroInit,
3973 bool BaseInitialization) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003974 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003975
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003976 // C++ [class.copy]p15:
3977 // Whenever a temporary class object is copied using a copy constructor, and
3978 // this object and the copy have the same cv-unqualified type, an
3979 // implementation is permitted to treat the original and the copy as two
3980 // different ways of referring to the same object and not perform a copy at
3981 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003982
Anders Carlsson250aada2009-08-16 05:13:48 +00003983 // FIXME: Is this enough?
Douglas Gregor507eb872009-12-22 00:34:07 +00003984 if (Constructor->isCopyConstructor()) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003985 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregore1314a62009-12-18 05:02:21 +00003986 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3987 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3988 E = ICE->getSubExpr();
Eli Friedmanfddc26c2009-12-24 23:33:34 +00003989 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3990 E = FCE->getSubExpr();
Anders Carlsson250aada2009-08-16 05:13:48 +00003991 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3992 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003993 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3994 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3995 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00003996
3997 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3998 Elidable = !CE->getCallReturnType()->isReferenceType();
3999 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00004000 Elidable = true;
Eli Friedmanfddc26c2009-12-24 23:33:34 +00004001 else if (isa<CXXConstructExpr>(E))
4002 Elidable = true;
Anders Carlsson250aada2009-08-16 05:13:48 +00004003 }
Mike Stump11289f42009-09-09 15:08:12 +00004004
4005 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004006 Elidable, move(ExprArgs), RequiresZeroInit,
4007 BaseInitialization);
Anders Carlsson250aada2009-08-16 05:13:48 +00004008}
4009
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004010/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4011/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004012Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004013Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4014 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004015 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004016 bool RequiresZeroInit,
4017 bool BaseInitialization) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004018 unsigned NumExprs = ExprArgs.size();
4019 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004020
Douglas Gregor27381f32009-11-23 12:27:39 +00004021 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004022 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004023 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004024 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004025}
4026
Mike Stump11289f42009-09-09 15:08:12 +00004027bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004028 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004029 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004030 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004031 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004032 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004033 if (TempResult.isInvalid())
4034 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004035
Anders Carlsson6eb55572009-08-25 05:12:04 +00004036 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004037 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004038 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004039 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004040
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004041 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004042}
4043
John McCall03c48482010-02-02 09:10:11 +00004044void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4045 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004046 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4047 !ClassDecl->hasTrivialDestructor()) {
John McCall6781b052010-02-02 08:45:54 +00004048 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4049 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall03c48482010-02-02 09:10:11 +00004050 CheckDestructorAccess(VD->getLocation(), Record);
John McCall6781b052010-02-02 08:45:54 +00004051 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004052}
4053
Mike Stump11289f42009-09-09 15:08:12 +00004054/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004055/// ActOnDeclarator, when a C++ direct initializer is present.
4056/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004057void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4058 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004059 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004060 SourceLocation *CommaLocs,
4061 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004062 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004063 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004064
4065 // If there is no declaration, there was an error parsing it. Just ignore
4066 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004067 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004068 return;
Mike Stump11289f42009-09-09 15:08:12 +00004069
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004070 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4071 if (!VDecl) {
4072 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4073 RealDecl->setInvalidDecl();
4074 return;
4075 }
4076
Douglas Gregor402250f2009-08-26 21:14:46 +00004077 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004078 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004079 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4080 //
4081 // Clients that want to distinguish between the two forms, can check for
4082 // direct initializer using VarDecl::hasCXXDirectInitializer().
4083 // A major benefit is that clients that don't particularly care about which
4084 // exactly form was it (like the CodeGen) can handle both cases without
4085 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004086
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004087 // C++ 8.5p11:
4088 // The form of initialization (using parentheses or '=') is generally
4089 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004090 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004091 QualType DeclInitType = VDecl->getType();
4092 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004093 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004094
Douglas Gregor50dc2192010-02-11 22:55:30 +00004095 if (!VDecl->getType()->isDependentType() &&
4096 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004097 diag::err_typecheck_decl_incomplete_type)) {
4098 VDecl->setInvalidDecl();
4099 return;
4100 }
4101
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004102 // The variable can not have an abstract class type.
4103 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4104 diag::err_abstract_type_in_decl,
4105 AbstractVariableType))
4106 VDecl->setInvalidDecl();
4107
Sebastian Redl5ca79842010-02-01 20:16:42 +00004108 const VarDecl *Def;
4109 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004110 Diag(VDecl->getLocation(), diag::err_redefinition)
4111 << VDecl->getDeclName();
4112 Diag(Def->getLocation(), diag::note_previous_definition);
4113 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004114 return;
4115 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004116
4117 // If either the declaration has a dependent type or if any of the
4118 // expressions is type-dependent, we represent the initialization
4119 // via a ParenListExpr for later use during template instantiation.
4120 if (VDecl->getType()->isDependentType() ||
4121 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4122 // Let clients know that initialization was done with a direct initializer.
4123 VDecl->setCXXDirectInitializer(true);
4124
4125 // Store the initialization expressions as a ParenListExpr.
4126 unsigned NumExprs = Exprs.size();
4127 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4128 (Expr **)Exprs.release(),
4129 NumExprs, RParenLoc));
4130 return;
4131 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004132
4133 // Capture the variable that is being initialized and the style of
4134 // initialization.
4135 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4136
4137 // FIXME: Poor source location information.
4138 InitializationKind Kind
4139 = InitializationKind::CreateDirect(VDecl->getLocation(),
4140 LParenLoc, RParenLoc);
4141
4142 InitializationSequence InitSeq(*this, Entity, Kind,
4143 (Expr**)Exprs.get(), Exprs.size());
4144 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4145 if (Result.isInvalid()) {
4146 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004147 return;
4148 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004149
4150 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004151 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004152 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004153
John McCall03c48482010-02-02 09:10:11 +00004154 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4155 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004156}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004157
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004158/// \brief Add the applicable constructor candidates for an initialization
4159/// by constructor.
4160static void AddConstructorInitializationCandidates(Sema &SemaRef,
4161 QualType ClassType,
4162 Expr **Args,
4163 unsigned NumArgs,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004164 InitializationKind Kind,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004165 OverloadCandidateSet &CandidateSet) {
4166 // C++ [dcl.init]p14:
4167 // If the initialization is direct-initialization, or if it is
4168 // copy-initialization where the cv-unqualified version of the
4169 // source type is the same class as, or a derived class of, the
4170 // class of the destination, constructors are considered. The
4171 // applicable constructors are enumerated (13.3.1.3), and the
4172 // best one is chosen through overload resolution (13.3). The
4173 // constructor so selected is called to initialize the object,
4174 // with the initializer expression(s) as its argument(s). If no
4175 // constructor applies, or the overload resolution is ambiguous,
4176 // the initialization is ill-formed.
4177 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4178 assert(ClassRec && "Can only initialize a class type here");
4179
4180 // FIXME: When we decide not to synthesize the implicitly-declared
4181 // constructors, we'll need to make them appear here.
4182
4183 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4184 DeclarationName ConstructorName
4185 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4186 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4187 DeclContext::lookup_const_iterator Con, ConEnd;
4188 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4189 Con != ConEnd; ++Con) {
4190 // Find the constructor (which may be a template).
4191 CXXConstructorDecl *Constructor = 0;
4192 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4193 if (ConstructorTmpl)
4194 Constructor
4195 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4196 else
4197 Constructor = cast<CXXConstructorDecl>(*Con);
4198
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004199 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4200 (Kind.getKind() == InitializationKind::IK_Value) ||
4201 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004202 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004203 ((Kind.getKind() == InitializationKind::IK_Default) &&
4204 Constructor->isDefaultConstructor())) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004205 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00004206 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCallb89836b2010-01-26 01:37:31 +00004207 ConstructorTmpl->getAccess(),
John McCall6b51f282009-11-23 01:53:49 +00004208 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004209 Args, NumArgs, CandidateSet);
4210 else
John McCallb89836b2010-01-26 01:37:31 +00004211 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4212 Args, NumArgs, CandidateSet);
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004213 }
4214 }
4215}
4216
4217/// \brief Attempt to perform initialization by constructor
4218/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4219/// copy-initialization.
4220///
4221/// This routine determines whether initialization by constructor is possible,
4222/// but it does not emit any diagnostics in the case where the initialization
4223/// is ill-formed.
4224///
4225/// \param ClassType the type of the object being initialized, which must have
4226/// class type.
4227///
4228/// \param Args the arguments provided to initialize the object
4229///
4230/// \param NumArgs the number of arguments provided to initialize the object
4231///
4232/// \param Kind the type of initialization being performed
4233///
4234/// \returns the constructor used to initialize the object, if successful.
4235/// Otherwise, emits a diagnostic and returns NULL.
4236CXXConstructorDecl *
4237Sema::TryInitializationByConstructor(QualType ClassType,
4238 Expr **Args, unsigned NumArgs,
4239 SourceLocation Loc,
4240 InitializationKind Kind) {
4241 // Build the overload candidate set
John McCallbc077cf2010-02-08 23:07:23 +00004242 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004243 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4244 CandidateSet);
4245
4246 // Determine whether we found a constructor we can use.
4247 OverloadCandidateSet::iterator Best;
4248 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4249 case OR_Success:
4250 case OR_Deleted:
4251 // We found a constructor. Return it.
4252 return cast<CXXConstructorDecl>(Best->Function);
4253
4254 case OR_No_Viable_Function:
4255 case OR_Ambiguous:
4256 // Overload resolution failed. Return nothing.
4257 return 0;
4258 }
4259
4260 // Silence GCC warning
4261 return 0;
4262}
4263
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004264/// \brief Given a constructor and the set of arguments provided for the
4265/// constructor, convert the arguments and add any required default arguments
4266/// to form a proper call to this constructor.
4267///
4268/// \returns true if an error occurred, false otherwise.
4269bool
4270Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4271 MultiExprArg ArgsPtr,
4272 SourceLocation Loc,
4273 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4274 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4275 unsigned NumArgs = ArgsPtr.size();
4276 Expr **Args = (Expr **)ArgsPtr.get();
4277
4278 const FunctionProtoType *Proto
4279 = Constructor->getType()->getAs<FunctionProtoType>();
4280 assert(Proto && "Constructor without a prototype?");
4281 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004282
4283 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004284 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004285 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004286 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004287 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004288
4289 VariadicCallType CallType =
4290 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4291 llvm::SmallVector<Expr *, 8> AllArgs;
4292 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4293 Proto, 0, Args, NumArgs, AllArgs,
4294 CallType);
4295 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4296 ConvertedArgs.push_back(AllArgs[i]);
4297 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004298}
4299
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004300/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4301/// determine whether they are reference-related,
4302/// reference-compatible, reference-compatible with added
4303/// qualification, or incompatible, for use in C++ initialization by
4304/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4305/// type, and the first type (T1) is the pointee type of the reference
4306/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00004307Sema::ReferenceCompareResult
Chandler Carruth607f38e2009-12-29 07:16:59 +00004308Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004309 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00004310 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004311 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004312 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004313 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004314
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004315 QualType T1 = Context.getCanonicalType(OrigT1);
4316 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004317 Qualifiers T1Quals, T2Quals;
4318 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4319 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004320
4321 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004322 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00004323 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004324 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00004325 if (UnqualT1 == UnqualT2)
4326 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004327 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4328 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4329 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00004330 DerivedToBase = true;
4331 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004332 return Ref_Incompatible;
4333
4334 // At this point, we know that T1 and T2 are reference-related (at
4335 // least).
4336
Chandler Carruth607f38e2009-12-29 07:16:59 +00004337 // If the type is an array type, promote the element qualifiers to the type
4338 // for comparison.
4339 if (isa<ArrayType>(T1) && T1Quals)
4340 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4341 if (isa<ArrayType>(T2) && T2Quals)
4342 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4343
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004344 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004345 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004346 // reference-related to T2 and cv1 is the same cv-qualification
4347 // as, or greater cv-qualification than, cv2. For purposes of
4348 // overload resolution, cases for which cv1 is greater
4349 // cv-qualification than cv2 are identified as
4350 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth607f38e2009-12-29 07:16:59 +00004351 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004352 return Ref_Compatible;
4353 else if (T1.isMoreQualifiedThan(T2))
4354 return Ref_Compatible_With_Added_Qualification;
4355 else
4356 return Ref_Related;
4357}
4358
4359/// CheckReferenceInit - Check the initialization of a reference
4360/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4361/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00004362/// list), and DeclType is the type of the declaration. When ICS is
4363/// non-null, this routine will compute the implicit conversion
4364/// sequence according to C++ [over.ics.ref] and will not produce any
4365/// diagnostics; when ICS is null, it will emit diagnostics when any
4366/// errors are found. Either way, a return value of true indicates
4367/// that there was a failure, a return value of false indicates that
4368/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00004369///
4370/// When @p SuppressUserConversions, user-defined conversions are
4371/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004372/// When @p AllowExplicit, we also permit explicit user-defined
4373/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00004374/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00004375/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4376/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00004377bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00004378Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00004379 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004380 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00004381 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00004382 ImplicitConversionSequence *ICS,
4383 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004384 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4385
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004386 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004387 QualType T2 = Init->getType();
4388
Douglas Gregorcd695e52008-11-10 20:40:00 +00004389 // If the initializer is the address of an overloaded function, try
4390 // to resolve the overloaded function. If all goes well, T2 is the
4391 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004392 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00004393 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004394 ICS != 0);
4395 if (Fn) {
4396 // Since we're performing this reference-initialization for
4397 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004398 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00004399 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004400 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004401
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00004402 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004403 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004404
4405 T2 = Fn->getType();
4406 }
4407 }
4408
Douglas Gregor786ab212008-10-29 02:00:59 +00004409 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004410 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00004411 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00004412 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4413 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00004414 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004415 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00004416
4417 // Most paths end in a failed conversion.
John McCall6a61b522010-01-13 09:16:55 +00004418 if (ICS) {
John McCall65eb8792010-02-25 01:37:24 +00004419 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCall6a61b522010-01-13 09:16:55 +00004420 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004421
4422 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004423 // A reference to type "cv1 T1" is initialized by an expression
4424 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004425
4426 // -- If the initializer expression
4427
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004428 // Rvalue references cannot bind to lvalues (N2812).
4429 // There is absolutely no situation where they can. In particular, note that
4430 // this is ill-formed, even if B has a user-defined conversion to A&&:
4431 // B b;
4432 // A&& r = b;
4433 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4434 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004435 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004436 << Init->getSourceRange();
4437 return true;
4438 }
4439
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004440 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00004441 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4442 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00004443 //
4444 // Note that the bit-field check is skipped if we are just computing
4445 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00004446 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004447 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004448 BindsDirectly = true;
4449
Douglas Gregor786ab212008-10-29 02:00:59 +00004450 if (ICS) {
4451 // C++ [over.ics.ref]p1:
4452 // When a parameter of reference type binds directly (8.5.3)
4453 // to an argument expression, the implicit conversion sequence
4454 // is the identity conversion, unless the argument expression
4455 // has a type that is a derived class of the parameter type,
4456 // in which case the implicit conversion sequence is a
4457 // derived-to-base Conversion (13.3.3.1).
John McCall0d1da222010-01-12 00:44:57 +00004458 ICS->setStandard();
Douglas Gregor786ab212008-10-29 02:00:59 +00004459 ICS->Standard.First = ICK_Identity;
4460 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4461 ICS->Standard.Third = ICK_Identity;
4462 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004463 ICS->Standard.setToType(0, T2);
4464 ICS->Standard.setToType(1, T1);
4465 ICS->Standard.setToType(2, T1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004466 ICS->Standard.ReferenceBinding = true;
4467 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004468 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004469 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004470
4471 // Nothing more to do: the inaccessibility/ambiguity check for
4472 // derived-to-base conversions is suppressed when we're
4473 // computing the implicit conversion sequence (C++
4474 // [over.best.ics]p2).
4475 return false;
4476 } else {
4477 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004478 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4479 if (DerivedToBase)
4480 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004481 else if(CheckExceptionSpecCompatibility(Init, T1))
4482 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004483 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004484 }
4485 }
4486
4487 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00004488 // implicitly converted to an lvalue of type "cv3 T3,"
4489 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004490 // 92) (this conversion is selected by enumerating the
4491 // applicable conversion functions (13.3.1.6) and choosing
4492 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004493 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004494 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00004495 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004496 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004497
John McCallbc077cf2010-02-08 23:07:23 +00004498 OverloadCandidateSet CandidateSet(DeclLoc);
John McCallad371252010-01-20 00:46:10 +00004499 const UnresolvedSetImpl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004500 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004501 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004502 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00004503 NamedDecl *D = *I;
4504 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4505 if (isa<UsingShadowDecl>(D))
4506 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4507
Mike Stump11289f42009-09-09 15:08:12 +00004508 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00004509 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00004510 CXXConversionDecl *Conv;
4511 if (ConvTemplate)
4512 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4513 else
John McCall6e9f8f62009-12-03 04:06:58 +00004514 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004515
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004516 // If the conversion function doesn't return a reference type,
4517 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004518 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00004519 (AllowExplicit || !Conv->isExplicit())) {
4520 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00004521 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall6e9f8f62009-12-03 04:06:58 +00004522 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004523 else
John McCallb89836b2010-01-26 01:37:31 +00004524 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4525 DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004526 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004527 }
4528
4529 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00004530 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004531 case OR_Success:
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00004532 // C++ [over.ics.ref]p1:
4533 //
4534 // [...] If the parameter binds directly to the result of
4535 // applying a conversion function to the argument
4536 // expression, the implicit conversion sequence is a
4537 // user-defined conversion sequence (13.3.3.1.2), with the
4538 // second standard conversion sequence either an identity
4539 // conversion or, if the conversion function returns an
4540 // entity of a type that is a derived class of the parameter
4541 // type, a derived-to-base Conversion.
4542 if (!Best->FinalConversion.DirectBinding)
4543 break;
4544
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004545 // This is a direct binding.
4546 BindsDirectly = true;
4547
4548 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004549 ICS->setUserDefined();
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004550 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4551 ICS->UserDefined.After = Best->FinalConversion;
4552 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004553 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004554 assert(ICS->UserDefined.After.ReferenceBinding &&
4555 ICS->UserDefined.After.DirectBinding &&
4556 "Expected a direct reference binding!");
4557 return false;
4558 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004559 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004560 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004561 CastExpr::CK_UserDefinedConversion,
4562 cast<CXXMethodDecl>(Best->Function),
4563 Owned(Init));
4564 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004565
4566 if (CheckExceptionSpecCompatibility(Init, T1))
4567 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004568 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4569 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004570 }
4571 break;
4572
4573 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004574 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004575 ICS->setAmbiguous();
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004576 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4577 Cand != CandidateSet.end(); ++Cand)
4578 if (Cand->Viable)
John McCall0d1da222010-01-12 00:44:57 +00004579 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004580 break;
4581 }
4582 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4583 << Init->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00004584 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004585 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004586
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004587 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004588 case OR_Deleted:
4589 // There was no suitable conversion, or we found a deleted
4590 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004591 break;
4592 }
4593 }
Mike Stump11289f42009-09-09 15:08:12 +00004594
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004595 if (BindsDirectly) {
4596 // C++ [dcl.init.ref]p4:
4597 // [...] In all cases where the reference-related or
4598 // reference-compatible relationship of two types is used to
4599 // establish the validity of a reference binding, and T1 is a
4600 // base class of T2, a program that necessitates such a binding
4601 // is ill-formed if T1 is an inaccessible (clause 11) or
4602 // ambiguous (10.2) base class of T2.
4603 //
4604 // Note that we only check this condition when we're allowed to
4605 // complain about errors, because we should not be checking for
4606 // ambiguity (or inaccessibility) unless the reference binding
4607 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004608 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004609 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004610 Init->getSourceRange(),
4611 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004612 else
4613 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004614 }
4615
4616 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004617 // type (i.e., cv1 shall be const), or the reference shall be an
4618 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004619 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004620 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004621 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregord1e08642010-01-29 19:39:15 +00004622 << T1.isVolatileQualified()
Douglas Gregor906db8a2009-12-15 16:44:32 +00004623 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004624 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004625 return true;
4626 }
4627
4628 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004629 // class type, and "cv1 T1" is reference-compatible with
4630 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004631 // following ways (the choice is implementation-defined):
4632 //
4633 // -- The reference is bound to the object represented by
4634 // the rvalue (see 3.10) or to a sub-object within that
4635 // object.
4636 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004637 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004638 // a constructor is called to copy the entire rvalue
4639 // object into the temporary. The reference is bound to
4640 // the temporary or to a sub-object within the
4641 // temporary.
4642 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004643 // The constructor that would be used to make the copy
4644 // shall be callable whether or not the copy is actually
4645 // done.
4646 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004647 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004648 // freedom, so we will always take the first option and never build
4649 // a temporary in this case. FIXME: We will, however, have to check
4650 // for the presence of a copy constructor in C++98/03 mode.
4651 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004652 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4653 if (ICS) {
John McCall0d1da222010-01-12 00:44:57 +00004654 ICS->setStandard();
Douglas Gregor786ab212008-10-29 02:00:59 +00004655 ICS->Standard.First = ICK_Identity;
4656 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4657 ICS->Standard.Third = ICK_Identity;
4658 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004659 ICS->Standard.setToType(0, T2);
4660 ICS->Standard.setToType(1, T1);
4661 ICS->Standard.setToType(2, T1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004662 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004663 ICS->Standard.DirectBinding = false;
4664 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004665 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004666 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004667 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4668 if (DerivedToBase)
4669 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004670 else if(CheckExceptionSpecCompatibility(Init, T1))
4671 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004672 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004673 }
4674 return false;
4675 }
4676
Eli Friedman44b83ee2009-08-05 19:21:58 +00004677 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004678 // initialized from the initializer expression using the
4679 // rules for a non-reference copy initialization (8.5). The
4680 // reference is then bound to the temporary. If T1 is
4681 // reference-related to T2, cv1 must be the same
4682 // cv-qualification as, or greater cv-qualification than,
4683 // cv2; otherwise, the program is ill-formed.
4684 if (RefRelationship == Ref_Related) {
4685 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4686 // we would be reference-compatible or reference-compatible with
4687 // added qualification. But that wasn't the case, so the reference
4688 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004689 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004690 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor906db8a2009-12-15 16:44:32 +00004691 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004692 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004693 return true;
4694 }
4695
Douglas Gregor576e98c2009-01-30 23:27:23 +00004696 // If at least one of the types is a class type, the types are not
4697 // related, and we aren't allowed any user conversions, the
4698 // reference binding fails. This case is important for breaking
4699 // recursion, since TryImplicitConversion below will attempt to
4700 // create a temporary through the use of a copy constructor.
4701 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4702 (T1->isRecordType() || T2->isRecordType())) {
4703 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004704 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004705 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor576e98c2009-01-30 23:27:23 +00004706 return true;
4707 }
4708
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004709 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004710 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004711 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004712 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004713 // When a parameter of reference type is not bound directly to
4714 // an argument expression, the conversion sequence is the one
4715 // required to convert the argument expression to the
4716 // underlying type of the reference according to
4717 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4718 // to copy-initializing a temporary of the underlying type with
4719 // the argument expression. Any difference in top-level
4720 // cv-qualification is subsumed by the initialization itself
4721 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004722 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4723 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004724 /*ForceRValue=*/false,
4725 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004726
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004727 // Of course, that's still a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004728 if (ICS->isStandard()) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004729 ICS->Standard.ReferenceBinding = true;
4730 ICS->Standard.RRefBinding = isRValRef;
John McCall0d1da222010-01-12 00:44:57 +00004731 } else if (ICS->isUserDefined()) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004732 ICS->UserDefined.After.ReferenceBinding = true;
4733 ICS->UserDefined.After.RRefBinding = isRValRef;
4734 }
John McCall0d1da222010-01-12 00:44:57 +00004735 return ICS->isBad();
Douglas Gregor786ab212008-10-29 02:00:59 +00004736 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004737 ImplicitConversionSequence Conversions;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004738 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004739 false, false,
4740 Conversions);
4741 if (badConversion) {
John McCall0d1da222010-01-12 00:44:57 +00004742 if (Conversions.isAmbiguous()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004743 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004744 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall0d1da222010-01-12 00:44:57 +00004745 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004746 j >= 0; j--) {
John McCall0d1da222010-01-12 00:44:57 +00004747 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallfd0b2f82010-01-06 09:43:14 +00004748 NoteOverloadCandidate(Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004749 }
4750 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004751 else {
4752 if (isRValRef)
4753 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4754 << Init->getSourceRange();
4755 else
4756 Diag(DeclLoc, diag::err_invalid_initialization)
4757 << DeclType << Init->getType() << Init->getSourceRange();
4758 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004759 }
4760 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004761 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004762}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004763
Anders Carlssone363c8e2009-12-12 00:32:00 +00004764static inline bool
4765CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4766 const FunctionDecl *FnDecl) {
4767 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4768 if (isa<NamespaceDecl>(DC)) {
4769 return SemaRef.Diag(FnDecl->getLocation(),
4770 diag::err_operator_new_delete_declared_in_namespace)
4771 << FnDecl->getDeclName();
4772 }
4773
4774 if (isa<TranslationUnitDecl>(DC) &&
4775 FnDecl->getStorageClass() == FunctionDecl::Static) {
4776 return SemaRef.Diag(FnDecl->getLocation(),
4777 diag::err_operator_new_delete_declared_static)
4778 << FnDecl->getDeclName();
4779 }
4780
Anders Carlsson60659a82009-12-12 02:43:16 +00004781 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004782}
4783
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004784static inline bool
4785CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4786 CanQualType ExpectedResultType,
4787 CanQualType ExpectedFirstParamType,
4788 unsigned DependentParamTypeDiag,
4789 unsigned InvalidParamTypeDiag) {
4790 QualType ResultType =
4791 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4792
4793 // Check that the result type is not dependent.
4794 if (ResultType->isDependentType())
4795 return SemaRef.Diag(FnDecl->getLocation(),
4796 diag::err_operator_new_delete_dependent_result_type)
4797 << FnDecl->getDeclName() << ExpectedResultType;
4798
4799 // Check that the result type is what we expect.
4800 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4801 return SemaRef.Diag(FnDecl->getLocation(),
4802 diag::err_operator_new_delete_invalid_result_type)
4803 << FnDecl->getDeclName() << ExpectedResultType;
4804
4805 // A function template must have at least 2 parameters.
4806 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4807 return SemaRef.Diag(FnDecl->getLocation(),
4808 diag::err_operator_new_delete_template_too_few_parameters)
4809 << FnDecl->getDeclName();
4810
4811 // The function decl must have at least 1 parameter.
4812 if (FnDecl->getNumParams() == 0)
4813 return SemaRef.Diag(FnDecl->getLocation(),
4814 diag::err_operator_new_delete_too_few_parameters)
4815 << FnDecl->getDeclName();
4816
4817 // Check the the first parameter type is not dependent.
4818 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4819 if (FirstParamType->isDependentType())
4820 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4821 << FnDecl->getDeclName() << ExpectedFirstParamType;
4822
4823 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004824 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004825 ExpectedFirstParamType)
4826 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4827 << FnDecl->getDeclName() << ExpectedFirstParamType;
4828
4829 return false;
4830}
4831
Anders Carlsson12308f42009-12-11 23:23:22 +00004832static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004833CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004834 // C++ [basic.stc.dynamic.allocation]p1:
4835 // A program is ill-formed if an allocation function is declared in a
4836 // namespace scope other than global scope or declared static in global
4837 // scope.
4838 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4839 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004840
4841 CanQualType SizeTy =
4842 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4843
4844 // C++ [basic.stc.dynamic.allocation]p1:
4845 // The return type shall be void*. The first parameter shall have type
4846 // std::size_t.
4847 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4848 SizeTy,
4849 diag::err_operator_new_dependent_param_type,
4850 diag::err_operator_new_param_type))
4851 return true;
4852
4853 // C++ [basic.stc.dynamic.allocation]p1:
4854 // The first parameter shall not have an associated default argument.
4855 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004856 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004857 diag::err_operator_new_default_arg)
4858 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4859
4860 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004861}
4862
4863static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004864CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4865 // C++ [basic.stc.dynamic.deallocation]p1:
4866 // A program is ill-formed if deallocation functions are declared in a
4867 // namespace scope other than global scope or declared static in global
4868 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004869 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4870 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004871
4872 // C++ [basic.stc.dynamic.deallocation]p2:
4873 // Each deallocation function shall return void and its first parameter
4874 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004875 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4876 SemaRef.Context.VoidPtrTy,
4877 diag::err_operator_delete_dependent_param_type,
4878 diag::err_operator_delete_param_type))
4879 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004880
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004881 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4882 if (FirstParamType->isDependentType())
4883 return SemaRef.Diag(FnDecl->getLocation(),
4884 diag::err_operator_delete_dependent_param_type)
4885 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4886
4887 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4888 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00004889 return SemaRef.Diag(FnDecl->getLocation(),
4890 diag::err_operator_delete_param_type)
4891 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00004892
4893 return false;
4894}
4895
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004896/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4897/// of this overloaded operator is well-formed. If so, returns false;
4898/// otherwise, emits appropriate diagnostics and returns true.
4899bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004900 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004901 "Expected an overloaded operator declaration");
4902
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004903 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4904
Mike Stump11289f42009-09-09 15:08:12 +00004905 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004906 // The allocation and deallocation functions, operator new,
4907 // operator new[], operator delete and operator delete[], are
4908 // described completely in 3.7.3. The attributes and restrictions
4909 // found in the rest of this subclause do not apply to them unless
4910 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00004911 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00004912 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004913
Anders Carlsson22f443f2009-12-12 00:26:23 +00004914 if (Op == OO_New || Op == OO_Array_New)
4915 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004916
4917 // C++ [over.oper]p6:
4918 // An operator function shall either be a non-static member
4919 // function or be a non-member function and have at least one
4920 // parameter whose type is a class, a reference to a class, an
4921 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004922 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4923 if (MethodDecl->isStatic())
4924 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004925 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004926 } else {
4927 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004928 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4929 ParamEnd = FnDecl->param_end();
4930 Param != ParamEnd; ++Param) {
4931 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004932 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4933 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004934 ClassOrEnumParam = true;
4935 break;
4936 }
4937 }
4938
Douglas Gregord69246b2008-11-17 16:14:12 +00004939 if (!ClassOrEnumParam)
4940 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004941 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004942 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004943 }
4944
4945 // C++ [over.oper]p8:
4946 // An operator function cannot have default arguments (8.3.6),
4947 // except where explicitly stated below.
4948 //
Mike Stump11289f42009-09-09 15:08:12 +00004949 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004950 // (C++ [over.call]p1).
4951 if (Op != OO_Call) {
4952 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4953 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004954 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004955 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004956 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004957 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004958 }
4959 }
4960
Douglas Gregor6cf08062008-11-10 13:38:07 +00004961 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4962 { false, false, false }
4963#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4964 , { Unary, Binary, MemberOnly }
4965#include "clang/Basic/OperatorKinds.def"
4966 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004967
Douglas Gregor6cf08062008-11-10 13:38:07 +00004968 bool CanBeUnaryOperator = OperatorUses[Op][0];
4969 bool CanBeBinaryOperator = OperatorUses[Op][1];
4970 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004971
4972 // C++ [over.oper]p8:
4973 // [...] Operator functions cannot have more or fewer parameters
4974 // than the number required for the corresponding operator, as
4975 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004976 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004977 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004978 if (Op != OO_Call &&
4979 ((NumParams == 1 && !CanBeUnaryOperator) ||
4980 (NumParams == 2 && !CanBeBinaryOperator) ||
4981 (NumParams < 1) || (NumParams > 2))) {
4982 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004983 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004984 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004985 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004986 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004987 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004988 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004989 assert(CanBeBinaryOperator &&
4990 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004991 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004992 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004993
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004994 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004995 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004996 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004997
Douglas Gregord69246b2008-11-17 16:14:12 +00004998 // Overloaded operators other than operator() cannot be variadic.
4999 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005000 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005001 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005002 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005003 }
5004
5005 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005006 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5007 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005008 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005009 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005010 }
5011
5012 // C++ [over.inc]p1:
5013 // The user-defined function called operator++ implements the
5014 // prefix and postfix ++ operator. If this function is a member
5015 // function with no parameters, or a non-member function with one
5016 // parameter of class or enumeration type, it defines the prefix
5017 // increment operator ++ for objects of that type. If the function
5018 // is a member function with one parameter (which shall be of type
5019 // int) or a non-member function with two parameters (the second
5020 // of which shall be of type int), it defines the postfix
5021 // increment operator ++ for objects of that type.
5022 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5023 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5024 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005025 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005026 ParamIsInt = BT->getKind() == BuiltinType::Int;
5027
Chris Lattner2b786902008-11-21 07:50:02 +00005028 if (!ParamIsInt)
5029 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005030 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005031 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005032 }
5033
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005034 // Notify the class if it got an assignment operator.
5035 if (Op == OO_Equal) {
5036 // Would have returned earlier otherwise.
5037 assert(isa<CXXMethodDecl>(FnDecl) &&
5038 "Overloaded = not member, but not filtered.");
5039 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5040 Method->getParent()->addedAssignmentOperator(Context, Method);
5041 }
5042
Douglas Gregord69246b2008-11-17 16:14:12 +00005043 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005044}
Chris Lattner3b024a32008-12-17 07:09:26 +00005045
Alexis Huntc88db062010-01-13 09:01:02 +00005046/// CheckLiteralOperatorDeclaration - Check whether the declaration
5047/// of this literal operator function is well-formed. If so, returns
5048/// false; otherwise, emits appropriate diagnostics and returns true.
5049bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5050 DeclContext *DC = FnDecl->getDeclContext();
5051 Decl::Kind Kind = DC->getDeclKind();
5052 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5053 Kind != Decl::LinkageSpec) {
5054 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5055 << FnDecl->getDeclName();
5056 return true;
5057 }
5058
5059 bool Valid = false;
5060
5061 // FIXME: Check for the one valid template signature
5062 // template <char...> type operator "" name();
5063
5064 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5065 // Check the first parameter
5066 QualType T = (*Param)->getType();
5067
5068 // unsigned long long int and long double are allowed, but only
5069 // alone.
5070 // We also allow any character type; their omission seems to be a bug
5071 // in n3000
5072 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5073 Context.hasSameType(T, Context.LongDoubleTy) ||
5074 Context.hasSameType(T, Context.CharTy) ||
5075 Context.hasSameType(T, Context.WCharTy) ||
5076 Context.hasSameType(T, Context.Char16Ty) ||
5077 Context.hasSameType(T, Context.Char32Ty)) {
5078 if (++Param == FnDecl->param_end())
5079 Valid = true;
5080 goto FinishedParams;
5081 }
5082
5083 // Otherwise it must be a pointer to const; let's strip those.
5084 const PointerType *PT = T->getAs<PointerType>();
5085 if (!PT)
5086 goto FinishedParams;
5087 T = PT->getPointeeType();
5088 if (!T.isConstQualified())
5089 goto FinishedParams;
5090 T = T.getUnqualifiedType();
5091
5092 // Move on to the second parameter;
5093 ++Param;
5094
5095 // If there is no second parameter, the first must be a const char *
5096 if (Param == FnDecl->param_end()) {
5097 if (Context.hasSameType(T, Context.CharTy))
5098 Valid = true;
5099 goto FinishedParams;
5100 }
5101
5102 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5103 // are allowed as the first parameter to a two-parameter function
5104 if (!(Context.hasSameType(T, Context.CharTy) ||
5105 Context.hasSameType(T, Context.WCharTy) ||
5106 Context.hasSameType(T, Context.Char16Ty) ||
5107 Context.hasSameType(T, Context.Char32Ty)))
5108 goto FinishedParams;
5109
5110 // The second and final parameter must be an std::size_t
5111 T = (*Param)->getType().getUnqualifiedType();
5112 if (Context.hasSameType(T, Context.getSizeType()) &&
5113 ++Param == FnDecl->param_end())
5114 Valid = true;
5115 }
5116
5117 // FIXME: This diagnostic is absolutely terrible.
5118FinishedParams:
5119 if (!Valid) {
5120 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5121 << FnDecl->getDeclName();
5122 return true;
5123 }
5124
5125 return false;
5126}
5127
Douglas Gregor07665a62009-01-05 19:45:36 +00005128/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5129/// linkage specification, including the language and (if present)
5130/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5131/// the location of the language string literal, which is provided
5132/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5133/// the '{' brace. Otherwise, this linkage specification does not
5134/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005135Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5136 SourceLocation ExternLoc,
5137 SourceLocation LangLoc,
5138 const char *Lang,
5139 unsigned StrSize,
5140 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005141 LinkageSpecDecl::LanguageIDs Language;
5142 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5143 Language = LinkageSpecDecl::lang_c;
5144 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5145 Language = LinkageSpecDecl::lang_cxx;
5146 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005147 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005148 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005149 }
Mike Stump11289f42009-09-09 15:08:12 +00005150
Chris Lattner438e5012008-12-17 07:13:27 +00005151 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005152
Douglas Gregor07665a62009-01-05 19:45:36 +00005153 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005154 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005155 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005156 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005157 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005158 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005159}
5160
Douglas Gregor07665a62009-01-05 19:45:36 +00005161/// ActOnFinishLinkageSpecification - Completely the definition of
5162/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5163/// valid, it's the position of the closing '}' brace in a linkage
5164/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005165Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5166 DeclPtrTy LinkageSpec,
5167 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005168 if (LinkageSpec)
5169 PopDeclContext();
5170 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005171}
5172
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005173/// \brief Perform semantic analysis for the variable declaration that
5174/// occurs within a C++ catch clause, returning the newly-created
5175/// variable.
5176VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005177 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005178 IdentifierInfo *Name,
5179 SourceLocation Loc,
5180 SourceRange Range) {
5181 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005182
5183 // Arrays and functions decay.
5184 if (ExDeclType->isArrayType())
5185 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5186 else if (ExDeclType->isFunctionType())
5187 ExDeclType = Context.getPointerType(ExDeclType);
5188
5189 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5190 // The exception-declaration shall not denote a pointer or reference to an
5191 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005192 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005193 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005194 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005195 Invalid = true;
5196 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005197
Sebastian Redl54c04d42008-12-22 19:15:10 +00005198 QualType BaseType = ExDeclType;
5199 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005200 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005201 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005202 BaseType = Ptr->getPointeeType();
5203 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00005204 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00005205 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005206 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005207 BaseType = Ref->getPointeeType();
5208 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00005209 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005210 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005211 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005212 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00005213 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005214
Mike Stump11289f42009-09-09 15:08:12 +00005215 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005216 RequireNonAbstractType(Loc, ExDeclType,
5217 diag::err_abstract_type_in_decl,
5218 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005219 Invalid = true;
5220
Mike Stump11289f42009-09-09 15:08:12 +00005221 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00005222 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005223
Douglas Gregor6de584c2010-03-05 23:38:39 +00005224 if (!Invalid) {
5225 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5226 // C++ [except.handle]p16:
5227 // The object declared in an exception-declaration or, if the
5228 // exception-declaration does not specify a name, a temporary (12.2) is
5229 // copy-initialized (8.5) from the exception object. [...]
5230 // The object is destroyed when the handler exits, after the destruction
5231 // of any automatic objects initialized within the handler.
5232 //
5233 // We just pretend to initialize the object with itself, then make sure
5234 // it can be destroyed later.
5235 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5236 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5237 Loc, ExDeclType, 0);
5238 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5239 SourceLocation());
5240 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5241 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5242 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5243 if (Result.isInvalid())
5244 Invalid = true;
5245 else
5246 FinalizeVarWithDestructor(ExDecl, RecordTy);
5247 }
5248 }
5249
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005250 if (Invalid)
5251 ExDecl->setInvalidDecl();
5252
5253 return ExDecl;
5254}
5255
5256/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5257/// handler.
5258Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005259 TypeSourceInfo *TInfo = 0;
5260 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005261
5262 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005263 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00005264 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005265 // The scope should be freshly made just for us. There is just no way
5266 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005267 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005268 if (PrevDecl->isTemplateParameter()) {
5269 // Maybe we will complain about the shadowed template parameter.
5270 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005271 }
5272 }
5273
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005274 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005275 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5276 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005277 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005278 }
5279
John McCallbcd03502009-12-07 02:54:59 +00005280 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005281 D.getIdentifier(),
5282 D.getIdentifierLoc(),
5283 D.getDeclSpec().getSourceRange());
5284
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005285 if (Invalid)
5286 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005287
Sebastian Redl54c04d42008-12-22 19:15:10 +00005288 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005289 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005290 PushOnScopeChains(ExDecl, S);
5291 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005292 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005293
Douglas Gregor758a8692009-06-17 21:51:59 +00005294 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005295 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005296}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005297
Mike Stump11289f42009-09-09 15:08:12 +00005298Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005299 ExprArg assertexpr,
5300 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005301 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005302 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005303 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5304
Anders Carlsson54b26982009-03-14 00:33:21 +00005305 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5306 llvm::APSInt Value(32);
5307 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5308 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5309 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005310 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005311 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005312
Anders Carlsson54b26982009-03-14 00:33:21 +00005313 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005314 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005315 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005316 }
5317 }
Mike Stump11289f42009-09-09 15:08:12 +00005318
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005319 assertexpr.release();
5320 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005321 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005322 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005323
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005324 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005325 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005326}
Sebastian Redlf769df52009-03-24 22:27:57 +00005327
John McCall11083da2009-09-16 22:47:08 +00005328/// Handle a friend type declaration. This works in tandem with
5329/// ActOnTag.
5330///
5331/// Notes on friend class templates:
5332///
5333/// We generally treat friend class declarations as if they were
5334/// declaring a class. So, for example, the elaborated type specifier
5335/// in a friend declaration is required to obey the restrictions of a
5336/// class-head (i.e. no typedefs in the scope chain), template
5337/// parameters are required to match up with simple template-ids, &c.
5338/// However, unlike when declaring a template specialization, it's
5339/// okay to refer to a template specialization without an empty
5340/// template parameter declaration, e.g.
5341/// friend class A<T>::B<unsigned>;
5342/// We permit this as a special case; if there are any template
5343/// parameters present at all, require proper matching, i.e.
5344/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005345Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005346 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005347 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005348
5349 assert(DS.isFriendSpecified());
5350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5351
John McCall11083da2009-09-16 22:47:08 +00005352 // Try to convert the decl specifier to a type. This works for
5353 // friend templates because ActOnTag never produces a ClassTemplateDecl
5354 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005355 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005356 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5357 if (TheDeclarator.isInvalidType())
5358 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005359
John McCall11083da2009-09-16 22:47:08 +00005360 // This is definitely an error in C++98. It's probably meant to
5361 // be forbidden in C++0x, too, but the specification is just
5362 // poorly written.
5363 //
5364 // The problem is with declarations like the following:
5365 // template <T> friend A<T>::foo;
5366 // where deciding whether a class C is a friend or not now hinges
5367 // on whether there exists an instantiation of A that causes
5368 // 'foo' to equal C. There are restrictions on class-heads
5369 // (which we declare (by fiat) elaborated friend declarations to
5370 // be) that makes this tractable.
5371 //
5372 // FIXME: handle "template <> friend class A<T>;", which
5373 // is possibly well-formed? Who even knows?
5374 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5375 Diag(Loc, diag::err_tagless_friend_type_template)
5376 << DS.getSourceRange();
5377 return DeclPtrTy();
5378 }
5379
John McCallaa74a0c2009-08-28 07:59:38 +00005380 // C++ [class.friend]p2:
5381 // An elaborated-type-specifier shall be used in a friend declaration
5382 // for a class.*
5383 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00005384 // This is one of the rare places in Clang where it's legitimate to
5385 // ask about the "spelling" of the type.
5386 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5387 // If we evaluated the type to a record type, suggest putting
5388 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00005389 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00005390 RecordDecl *RD = RT->getDecl();
5391
5392 std::string InsertionText = std::string(" ") + RD->getKindName();
5393
John McCallc3987482009-10-07 23:34:25 +00005394 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5395 << (unsigned) RD->getTagKind()
5396 << T
5397 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00005398 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5399 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00005400 return DeclPtrTy();
5401 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00005402 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5403 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005404 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00005405 }
5406 }
5407
John McCallc3987482009-10-07 23:34:25 +00005408 // Enum types cannot be friends.
5409 if (T->getAs<EnumType>()) {
5410 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5411 << SourceRange(DS.getFriendSpecLoc());
5412 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00005413 }
John McCallaa74a0c2009-08-28 07:59:38 +00005414
John McCallaa74a0c2009-08-28 07:59:38 +00005415 // C++98 [class.friend]p1: A friend of a class is a function
5416 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005417 // This is fixed in DR77, which just barely didn't make the C++03
5418 // deadline. It's also a very silly restriction that seriously
5419 // affects inner classes and which nobody else seems to implement;
5420 // thus we never diagnose it, not even in -pedantic.
John McCallaa74a0c2009-08-28 07:59:38 +00005421
John McCall11083da2009-09-16 22:47:08 +00005422 Decl *D;
5423 if (TempParams.size())
5424 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5425 TempParams.size(),
5426 (TemplateParameterList**) TempParams.release(),
5427 T.getTypePtr(),
5428 DS.getFriendSpecLoc());
5429 else
5430 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5431 DS.getFriendSpecLoc());
5432 D->setAccess(AS_public);
5433 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005434
John McCall11083da2009-09-16 22:47:08 +00005435 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005436}
5437
John McCall2f212b32009-09-11 21:02:39 +00005438Sema::DeclPtrTy
5439Sema::ActOnFriendFunctionDecl(Scope *S,
5440 Declarator &D,
5441 bool IsDefinition,
5442 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005443 const DeclSpec &DS = D.getDeclSpec();
5444
5445 assert(DS.isFriendSpecified());
5446 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5447
5448 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005449 TypeSourceInfo *TInfo = 0;
5450 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005451
5452 // C++ [class.friend]p1
5453 // A friend of a class is a function or class....
5454 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005455 // It *doesn't* see through dependent types, which is correct
5456 // according to [temp.arg.type]p3:
5457 // If a declaration acquires a function type through a
5458 // type dependent on a template-parameter and this causes
5459 // a declaration that does not use the syntactic form of a
5460 // function declarator to have a function type, the program
5461 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005462 if (!T->isFunctionType()) {
5463 Diag(Loc, diag::err_unexpected_friend);
5464
5465 // It might be worthwhile to try to recover by creating an
5466 // appropriate declaration.
5467 return DeclPtrTy();
5468 }
5469
5470 // C++ [namespace.memdef]p3
5471 // - If a friend declaration in a non-local class first declares a
5472 // class or function, the friend class or function is a member
5473 // of the innermost enclosing namespace.
5474 // - The name of the friend is not found by simple name lookup
5475 // until a matching declaration is provided in that namespace
5476 // scope (either before or after the class declaration granting
5477 // friendship).
5478 // - If a friend function is called, its name may be found by the
5479 // name lookup that considers functions from namespaces and
5480 // classes associated with the types of the function arguments.
5481 // - When looking for a prior declaration of a class or a function
5482 // declared as a friend, scopes outside the innermost enclosing
5483 // namespace scope are not considered.
5484
John McCallaa74a0c2009-08-28 07:59:38 +00005485 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5486 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005487 assert(Name);
5488
John McCall07e91c02009-08-06 02:15:43 +00005489 // The context we found the declaration in, or in which we should
5490 // create the declaration.
5491 DeclContext *DC;
5492
5493 // FIXME: handle local classes
5494
5495 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005496 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5497 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005498 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005499 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00005500 DC = computeDeclContext(ScopeQual);
5501
5502 // FIXME: handle dependent contexts
5503 if (!DC) return DeclPtrTy();
5504
John McCall1f82f242009-11-18 22:49:29 +00005505 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005506
5507 // If searching in that context implicitly found a declaration in
5508 // a different context, treat it like it wasn't found at all.
5509 // TODO: better diagnostics for this case. Suggesting the right
5510 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005511 // FIXME: getRepresentativeDecl() is not right here at all
5512 if (Previous.empty() ||
5513 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005514 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005515 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5516 return DeclPtrTy();
5517 }
5518
5519 // C++ [class.friend]p1: A friend of a class is a function or
5520 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005521 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005522 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5523
John McCall07e91c02009-08-06 02:15:43 +00005524 // Otherwise walk out to the nearest namespace scope looking for matches.
5525 } else {
5526 // TODO: handle local class contexts.
5527
5528 DC = CurContext;
5529 while (true) {
5530 // Skip class contexts. If someone can cite chapter and verse
5531 // for this behavior, that would be nice --- it's what GCC and
5532 // EDG do, and it seems like a reasonable intent, but the spec
5533 // really only says that checks for unqualified existing
5534 // declarations should stop at the nearest enclosing namespace,
5535 // not that they should only consider the nearest enclosing
5536 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005537 while (DC->isRecord())
5538 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005539
John McCall1f82f242009-11-18 22:49:29 +00005540 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005541
5542 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005543 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005544 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005545
John McCall07e91c02009-08-06 02:15:43 +00005546 if (DC->isFileContext()) break;
5547 DC = DC->getParent();
5548 }
5549
5550 // C++ [class.friend]p1: A friend of a class is a function or
5551 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005552 // C++0x changes this for both friend types and functions.
5553 // Most C++ 98 compilers do seem to give an error here, so
5554 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005555 if (!Previous.empty() && DC->Equals(CurContext)
5556 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005557 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5558 }
5559
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005560 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005561 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005562 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5563 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5564 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005565 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005566 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5567 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005568 return DeclPtrTy();
5569 }
John McCall07e91c02009-08-06 02:15:43 +00005570 }
5571
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005572 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005573 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005574 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005575 IsDefinition,
5576 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005577 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005578
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005579 assert(ND->getDeclContext() == DC);
5580 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005581
John McCall759e32b2009-08-31 22:39:49 +00005582 // Add the function declaration to the appropriate lookup tables,
5583 // adjusting the redeclarations list as necessary. We don't
5584 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005585 //
John McCall759e32b2009-08-31 22:39:49 +00005586 // Also update the scope-based lookup if the target context's
5587 // lookup context is in lexical scope.
5588 if (!CurContext->isDependentContext()) {
5589 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005590 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005591 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005592 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005593 }
John McCallaa74a0c2009-08-28 07:59:38 +00005594
5595 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005596 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005597 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005598 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005599 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005600
Douglas Gregor33636e62009-12-24 20:56:24 +00005601 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5602 FrD->setSpecialization(true);
5603
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005604 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005605}
5606
Chris Lattner83f095c2009-03-28 19:18:32 +00005607void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005608 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005609
Chris Lattner83f095c2009-03-28 19:18:32 +00005610 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005611 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5612 if (!Fn) {
5613 Diag(DelLoc, diag::err_deleted_non_function);
5614 return;
5615 }
5616 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5617 Diag(DelLoc, diag::err_deleted_decl_not_first);
5618 Diag(Prev->getLocation(), diag::note_previous_declaration);
5619 // If the declaration wasn't the first, we delete the function anyway for
5620 // recovery.
5621 }
5622 Fn->setDeleted();
5623}
Sebastian Redl4c018662009-04-27 21:33:24 +00005624
5625static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5626 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5627 ++CI) {
5628 Stmt *SubStmt = *CI;
5629 if (!SubStmt)
5630 continue;
5631 if (isa<ReturnStmt>(SubStmt))
5632 Self.Diag(SubStmt->getSourceRange().getBegin(),
5633 diag::err_return_in_constructor_handler);
5634 if (!isa<Expr>(SubStmt))
5635 SearchForReturnInStmt(Self, SubStmt);
5636 }
5637}
5638
5639void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5640 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5641 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5642 SearchForReturnInStmt(*this, Handler);
5643 }
5644}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005645
Mike Stump11289f42009-09-09 15:08:12 +00005646bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005647 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005648 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5649 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005650
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005651 if (Context.hasSameType(NewTy, OldTy) ||
5652 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005653 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005654
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005655 // Check if the return types are covariant
5656 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005657
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005658 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005659 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5660 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005661 NewClassTy = NewPT->getPointeeType();
5662 OldClassTy = OldPT->getPointeeType();
5663 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005664 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5665 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5666 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5667 NewClassTy = NewRT->getPointeeType();
5668 OldClassTy = OldRT->getPointeeType();
5669 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005670 }
5671 }
Mike Stump11289f42009-09-09 15:08:12 +00005672
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005673 // The return types aren't either both pointers or references to a class type.
5674 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005675 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005676 diag::err_different_return_type_for_overriding_virtual_function)
5677 << New->getDeclName() << NewTy << OldTy;
5678 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005679
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005680 return true;
5681 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005682
Anders Carlssone60365b2009-12-31 18:34:24 +00005683 // C++ [class.virtual]p6:
5684 // If the return type of D::f differs from the return type of B::f, the
5685 // class type in the return type of D::f shall be complete at the point of
5686 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005687 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5688 if (!RT->isBeingDefined() &&
5689 RequireCompleteType(New->getLocation(), NewClassTy,
5690 PDiag(diag::err_covariant_return_incomplete)
5691 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005692 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005693 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005694
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005695 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005696 // Check if the new class derives from the old class.
5697 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5698 Diag(New->getLocation(),
5699 diag::err_covariant_return_not_derived)
5700 << New->getDeclName() << NewTy << OldTy;
5701 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5702 return true;
5703 }
Mike Stump11289f42009-09-09 15:08:12 +00005704
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005705 // Check if we the conversion from derived to base is valid.
John McCall5b0829a2010-02-10 09:31:12 +00005706 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005707 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5708 // FIXME: Should this point to the return type?
5709 New->getLocation(), SourceRange(), New->getDeclName())) {
5710 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5711 return true;
5712 }
5713 }
Mike Stump11289f42009-09-09 15:08:12 +00005714
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005715 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005716 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005717 Diag(New->getLocation(),
5718 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005719 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005720 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5721 return true;
5722 };
Mike Stump11289f42009-09-09 15:08:12 +00005723
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005724
5725 // The new class type must have the same or less qualifiers as the old type.
5726 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5727 Diag(New->getLocation(),
5728 diag::err_covariant_return_type_class_type_more_qualified)
5729 << New->getDeclName() << NewTy << OldTy;
5730 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5731 return true;
5732 };
Mike Stump11289f42009-09-09 15:08:12 +00005733
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005734 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005735}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005736
Alexis Hunt96d5c762009-11-21 08:43:09 +00005737bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5738 const CXXMethodDecl *Old)
5739{
5740 if (Old->hasAttr<FinalAttr>()) {
5741 Diag(New->getLocation(), diag::err_final_function_overridden)
5742 << New->getDeclName();
5743 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5744 return true;
5745 }
5746
5747 return false;
5748}
5749
Douglas Gregor21920e372009-12-01 17:24:26 +00005750/// \brief Mark the given method pure.
5751///
5752/// \param Method the method to be marked pure.
5753///
5754/// \param InitRange the source range that covers the "0" initializer.
5755bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5756 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5757 Method->setPure();
5758
5759 // A class is abstract if at least one function is pure virtual.
5760 Method->getParent()->setAbstract(true);
5761 return false;
5762 }
5763
5764 if (!Method->isInvalidDecl())
5765 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5766 << Method->getDeclName() << InitRange;
5767 return true;
5768}
5769
John McCall1f4ee7b2009-12-19 09:28:58 +00005770/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5771/// an initializer for the out-of-line declaration 'Dcl'. The scope
5772/// is a fresh scope pushed for just this purpose.
5773///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005774/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5775/// static data member of class X, names should be looked up in the scope of
5776/// class X.
5777void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005778 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005779 Decl *D = Dcl.getAs<Decl>();
5780 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005781
John McCall1f4ee7b2009-12-19 09:28:58 +00005782 // We should only get called for declarations with scope specifiers, like:
5783 // int foo::bar;
5784 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005785 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005786}
5787
5788/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005789/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005790void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005791 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005792 Decl *D = Dcl.getAs<Decl>();
5793 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005794
John McCall1f4ee7b2009-12-19 09:28:58 +00005795 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005796 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005797}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005798
5799/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5800/// C++ if/switch/while/for statement.
5801/// e.g: "if (int x = f()) {...}"
5802Action::DeclResult
5803Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5804 // C++ 6.4p2:
5805 // The declarator shall not specify a function or an array.
5806 // The type-specifier-seq shall not contain typedef and shall not declare a
5807 // new class or enumeration.
5808 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5809 "Parser allowed 'typedef' as storage class of condition decl.");
5810
John McCallbcd03502009-12-07 02:54:59 +00005811 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005812 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005813 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005814
5815 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5816 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5817 // would be created and CXXConditionDeclExpr wants a VarDecl.
5818 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5819 << D.getSourceRange();
5820 return DeclResult();
5821 } else if (OwnedTag && OwnedTag->isDefinition()) {
5822 // The type-specifier-seq shall not declare a new class or enumeration.
5823 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5824 }
5825
5826 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5827 if (!Dcl)
5828 return DeclResult();
5829
5830 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5831 VD->setDeclaredInCondition(true);
5832 return Dcl;
5833}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005834
Rafael Espindola70e040d2010-03-02 21:28:26 +00005835static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005836 // Ignore dependent types.
5837 if (MD->isDependentContext())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005838 return false;
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005839
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005840 // Ignore declarations that are not definitions.
5841 if (!MD->isThisDeclarationADefinition())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005842 return false;
5843
5844 CXXRecordDecl *RD = MD->getParent();
5845
5846 // Ignore classes without a vtable.
5847 if (!RD->isDynamicClass())
5848 return false;
5849
5850 switch (MD->getParent()->getTemplateSpecializationKind()) {
5851 case TSK_Undeclared:
5852 case TSK_ExplicitSpecialization:
5853 // Classes that aren't instantiations of templates don't need their
5854 // virtual methods marked until we see the definition of the key
5855 // function.
5856 break;
5857
5858 case TSK_ImplicitInstantiation:
5859 // This is a constructor of a class template; mark all of the virtual
5860 // members as referenced to ensure that they get instantiatied.
5861 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5862 return true;
5863 break;
5864
5865 case TSK_ExplicitInstantiationDeclaration:
5866 return true; //FIXME: This looks wrong.
5867
5868 case TSK_ExplicitInstantiationDefinition:
5869 // This is method of a explicit instantiation; mark all of the virtual
5870 // members as referenced to ensure that they get instantiatied.
5871 return true;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005872 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00005873
5874 // Consider only out-of-line definitions of member functions. When we see
5875 // an inline definition, it's too early to compute the key function.
5876 if (!MD->isOutOfLine())
5877 return false;
5878
5879 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5880
5881 // If there is no key function, we will need a copy of the vtable.
5882 if (!KeyFunction)
5883 return true;
5884
5885 // If this is the key function, we need to mark virtual members.
5886 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5887 return true;
5888
5889 return false;
5890}
5891
5892void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5893 CXXMethodDecl *MD) {
5894 CXXRecordDecl *RD = MD->getParent();
5895
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005896 // We will need to mark all of the virtual members as referenced to build the
5897 // vtable.
Rafael Espindola70e040d2010-03-02 21:28:26 +00005898 // We actually call MarkVirtualMembersReferenced instead of adding to
5899 // ClassesWithUnmarkedVirtualMembers because this marking is needed by
5900 // codegen that will happend before we finish parsing the file.
5901 if (needsVtable(MD, Context))
5902 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson82fccd02009-12-07 08:24:59 +00005903}
5904
5905bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5906 if (ClassesWithUnmarkedVirtualMembers.empty())
5907 return false;
5908
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005909 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5910 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5911 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5912 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00005913 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005914 }
5915
Anders Carlsson82fccd02009-12-07 08:24:59 +00005916 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00005917}
Anders Carlsson82fccd02009-12-07 08:24:59 +00005918
5919void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5920 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5921 e = RD->method_end(); i != e; ++i) {
5922 CXXMethodDecl *MD = *i;
5923
5924 // C++ [basic.def.odr]p2:
5925 // [...] A virtual member function is used if it is not pure. [...]
5926 if (MD->isVirtual() && !MD->isPure())
5927 MarkDeclarationReferenced(Loc, MD);
5928 }
5929}