blob: 13b65e3000b3ae8240932ea546b7702c44c7202f [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 Carlssonc80a1272009-08-25 02:29:20 +0000112 QualType ParamType = Param->getType();
113
Anders Carlsson114056f2009-08-25 13:46:13 +0000114 if (RequireCompleteType(Param->getLocation(), Param->getType(),
115 diag::err_typecheck_decl_incomplete_type)) {
116 Param->setInvalidDecl();
117 return true;
118 }
119
Anders Carlssonc80a1272009-08-25 02:29:20 +0000120 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Douglas Gregor85dabae2009-12-16 01:38:02 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
131 if (CheckInitializerTypes(Arg, ParamType, Entity, Kind))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000132 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000133
Anders Carlsson6e997b22009-12-15 20:51:39 +0000134 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000135
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136 // Okay: add the default argument to the parameter
137 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000140
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000141 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142}
143
Chris Lattner58258242008-04-10 02:22:51 +0000144/// ActOnParamDefaultArgument - Check whether the default argument
145/// provided for a function parameter is well-formed. If so, attach it
146/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000147void
Mike Stump11289f42009-09-09 15:08:12 +0000148Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000149 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000150 if (!param || !defarg.get())
151 return;
Mike Stump11289f42009-09-09 15:08:12 +0000152
Chris Lattner83f095c2009-03-28 19:18:32 +0000153 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000154 UnparsedDefaultArgLocs.erase(Param);
155
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000156 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000157 QualType ParamType = Param->getType();
158
159 // Default arguments are only permitted in C++
160 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000161 Diag(EqualLoc, diag::err_param_default_argument)
162 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000163 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000164 return;
165 }
166
Anders Carlssonf1c26952009-08-25 01:02:06 +0000167 // Check that the default argument is well-formed
168 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
169 if (DefaultArgChecker.Visit(DefaultArg.get())) {
170 Param->setInvalidDecl();
171 return;
172 }
Mike Stump11289f42009-09-09 15:08:12 +0000173
Anders Carlssonc80a1272009-08-25 02:29:20 +0000174 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000175}
176
Douglas Gregor58354032008-12-24 00:01:03 +0000177/// ActOnParamUnparsedDefaultArgument - We've seen a default
178/// argument for a function parameter, but we can't parse it yet
179/// because we're inside a class definition. Note that this default
180/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000181void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000182 SourceLocation EqualLoc,
183 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000184 if (!param)
185 return;
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner83f095c2009-03-28 19:18:32 +0000187 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000188 if (Param)
189 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Anders Carlsson84613c42009-06-12 16:51:40 +0000191 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000192}
193
Douglas Gregor4d87df52008-12-16 21:30:33 +0000194/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
195/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000196void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump11289f42009-09-09 15:08:12 +0000199
Anders Carlsson84613c42009-06-12 16:51:40 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000205}
206
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000207/// CheckExtraCXXDefaultArguments - Check for any extra default
208/// arguments in the declarator, which is not a function declaration
209/// or definition and therefore is not permitted to have default
210/// arguments. This routine should be invoked for every declarator
211/// that is not a function declaration or definition.
212void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
213 // C++ [dcl.fct.default]p3
214 // A default argument expression shall be specified only in the
215 // parameter-declaration-clause of a function declaration or in a
216 // template-parameter (14.1). It shall not be specified for a
217 // parameter pack. If it is specified in a
218 // parameter-declaration-clause, it shall not occur within a
219 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000220 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000221 DeclaratorChunk &chunk = D.getTypeObject(i);
222 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000223 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
224 ParmVarDecl *Param =
225 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000226 if (Param->hasUnparsedDefaultArg()) {
227 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
230 delete Toks;
231 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000232 } else if (Param->getDefaultArg()) {
233 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
234 << Param->getDefaultArg()->getSourceRange();
235 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000236 }
237 }
238 }
239 }
240}
241
Chris Lattner199abbc2008-04-08 05:04:30 +0000242// MergeCXXFunctionDecl - Merge two declarations of the same C++
243// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000244// type. Subroutine of MergeFunctionDecl. Returns true if there was an
245// error, false otherwise.
246bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
247 bool Invalid = false;
248
Chris Lattner199abbc2008-04-08 05:04:30 +0000249 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000250 // For non-template functions, default arguments can be added in
251 // later declarations of a function in the same
252 // scope. Declarations in different scopes have completely
253 // distinct sets of default arguments. That is, declarations in
254 // inner scopes do not acquire default arguments from
255 // declarations in outer scopes, and vice versa. In a given
256 // function declaration, all parameters subsequent to a
257 // parameter with a default argument shall have default
258 // arguments supplied in this or previous declarations. A
259 // default argument shall not be redefined by a later
260 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000261 //
262 // C++ [dcl.fct.default]p6:
263 // Except for member functions of class templates, the default arguments
264 // in a member function definition that appears outside of the class
265 // definition are added to the set of default arguments provided by the
266 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000267 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
268 ParmVarDecl *OldParam = Old->getParamDecl(p);
269 ParmVarDecl *NewParam = New->getParamDecl(p);
270
Douglas Gregorc732aba2009-09-11 18:44:32 +0000271 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000272 // FIXME: If the parameter doesn't have an identifier then the location
273 // points to the '=' which means that the fixit hint won't remove any
274 // extra spaces between the type and the '='.
275 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson1566eb52009-11-10 03:32:44 +0000276 if (NewParam->getIdentifier())
277 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000278
Mike Stump11289f42009-09-09 15:08:12 +0000279 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000280 diag::err_param_default_argument_redefinition)
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000281 << NewParam->getDefaultArgRange()
282 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
283 NewParam->getLocEnd()));
Douglas Gregorc732aba2009-09-11 18:44:32 +0000284
285 // Look for the function declaration where the default argument was
286 // actually written, which may be a declaration prior to Old.
287 for (FunctionDecl *Older = Old->getPreviousDeclaration();
288 Older; Older = Older->getPreviousDeclaration()) {
289 if (!Older->getParamDecl(p)->hasDefaultArg())
290 break;
291
292 OldParam = Older->getParamDecl(p);
293 }
294
295 Diag(OldParam->getLocation(), diag::note_previous_definition)
296 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000297 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000298 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000299 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000300 if (OldParam->hasUninstantiatedDefaultArg())
301 NewParam->setUninstantiatedDefaultArg(
302 OldParam->getUninstantiatedDefaultArg());
303 else
304 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000305 } else if (NewParam->hasDefaultArg()) {
306 if (New->getDescribedFunctionTemplate()) {
307 // Paragraph 4, quoted above, only applies to non-template functions.
308 Diag(NewParam->getLocation(),
309 diag::err_param_default_argument_template_redecl)
310 << NewParam->getDefaultArgRange();
311 Diag(Old->getLocation(), diag::note_template_prev_declaration)
312 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000313 } else if (New->getTemplateSpecializationKind()
314 != TSK_ImplicitInstantiation &&
315 New->getTemplateSpecializationKind() != TSK_Undeclared) {
316 // C++ [temp.expr.spec]p21:
317 // Default function arguments shall not be specified in a declaration
318 // or a definition for one of the following explicit specializations:
319 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000320 // - the explicit specialization of a member function template;
321 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000322 // template where the class template specialization to which the
323 // member function specialization belongs is implicitly
324 // instantiated.
325 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
326 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
327 << New->getDeclName()
328 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000329 } else if (New->getDeclContext()->isDependentContext()) {
330 // C++ [dcl.fct.default]p6 (DR217):
331 // Default arguments for a member function of a class template shall
332 // be specified on the initial declaration of the member function
333 // within the class template.
334 //
335 // Reading the tea leaves a bit in DR217 and its reference to DR205
336 // leads me to the conclusion that one cannot add default function
337 // arguments for an out-of-line definition of a member function of a
338 // dependent type.
339 int WhichKind = 2;
340 if (CXXRecordDecl *Record
341 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
342 if (Record->getDescribedClassTemplate())
343 WhichKind = 0;
344 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
345 WhichKind = 1;
346 else
347 WhichKind = 2;
348 }
349
350 Diag(NewParam->getLocation(),
351 diag::err_param_default_argument_member_template_redecl)
352 << WhichKind
353 << NewParam->getDefaultArgRange();
354 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000355 }
356 }
357
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000358 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000359 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +0000360 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000362
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000396 else
Mike Stump11289f42009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattner199abbc2008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000412 if (!Param->hasUnparsedDefaultArg())
413 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000414 Param->setDefaultArg(0);
415 }
416 }
417 }
418}
Douglas Gregor556877c2008-04-13 21:30:24 +0000419
Douglas Gregor61956c42008-10-31 09:07:45 +0000420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000426 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000427 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000428 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
430 } else
431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
432
433 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000434 return &II == CurDecl->getIdentifier();
435 else
436 return false;
437}
438
Mike Stump11289f42009-09-09 15:08:12 +0000439/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000440///
441/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
442/// and returns NULL otherwise.
443CXXBaseSpecifier *
444Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
445 SourceRange SpecifierRange,
446 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000447 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000448 SourceLocation BaseLoc) {
449 // C++ [class.union]p1:
450 // A union shall not have base classes.
451 if (Class->isUnion()) {
452 Diag(Class->getLocation(), diag::err_base_clause_on_union)
453 << SpecifierRange;
454 return 0;
455 }
456
457 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000458 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000459 Class->getTagKind() == RecordDecl::TK_class,
460 Access, BaseType);
461
462 // Base specifiers must be record types.
463 if (!BaseType->isRecordType()) {
464 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
465 return 0;
466 }
467
468 // C++ [class.union]p1:
469 // A union shall not be used as a base class.
470 if (BaseType->isUnionType()) {
471 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
472 return 0;
473 }
474
475 // C++ [class.derived]p2:
476 // The class-name in a base-specifier shall not be an incompletely
477 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000478 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000479 PDiag(diag::err_incomplete_base_class)
480 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000481 return 0;
482
Eli Friedmanc96d4962009-08-15 21:55:26 +0000483 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000484 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000485 assert(BaseDecl && "Record type has no declaration");
486 BaseDecl = BaseDecl->getDefinition(Context);
487 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000488 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
489 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000490
Alexis Hunt96d5c762009-11-21 08:43:09 +0000491 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
492 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
493 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000494 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
495 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000496 return 0;
497 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000498
Eli Friedman89c038e2009-12-05 23:03:49 +0000499 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000500
501 // Create the base specifier.
502 // FIXME: Allocate via ASTContext?
503 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
504 Class->getTagKind() == RecordDecl::TK_class,
505 Access, BaseType);
506}
507
508void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
509 const CXXRecordDecl *BaseClass,
510 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000511 // A class with a non-empty base class is not empty.
512 // FIXME: Standard ref?
513 if (!BaseClass->isEmpty())
514 Class->setEmpty(false);
515
516 // C++ [class.virtual]p1:
517 // A class that [...] inherits a virtual function is called a polymorphic
518 // class.
519 if (BaseClass->isPolymorphic())
520 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000521
Douglas Gregor463421d2009-03-03 04:44:36 +0000522 // C++ [dcl.init.aggr]p1:
523 // An aggregate is [...] a class with [...] no base classes [...].
524 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000525
526 // C++ [class]p4:
527 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000528 Class->setPOD(false);
529
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000530 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000531 // C++ [class.ctor]p5:
532 // A constructor is trivial if its class has no virtual base classes.
533 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000534
535 // C++ [class.copy]p6:
536 // A copy constructor is trivial if its class has no virtual base classes.
537 Class->setHasTrivialCopyConstructor(false);
538
539 // C++ [class.copy]p11:
540 // A copy assignment operator is trivial if its class has no virtual
541 // base classes.
542 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000543
544 // C++0x [meta.unary.prop] is_empty:
545 // T is a class type, but not a union type, with ... no virtual base
546 // classes
547 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000548 } else {
549 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000550 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000551 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000552 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000553 Class->setHasTrivialConstructor(false);
554
555 // C++ [class.copy]p6:
556 // A copy constructor is trivial if all the direct base classes of its
557 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000558 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000559 Class->setHasTrivialCopyConstructor(false);
560
561 // C++ [class.copy]p11:
562 // A copy assignment operator is trivial if all the direct base classes
563 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000564 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000565 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000566 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000567
568 // C++ [class.ctor]p3:
569 // A destructor is trivial if all the direct base classes of its class
570 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000571 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000572 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000573}
574
Douglas Gregor556877c2008-04-13 21:30:24 +0000575/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
576/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000577/// example:
578/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000579/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000580Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000581Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000582 bool Virtual, AccessSpecifier Access,
583 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000584 if (!classdecl)
585 return true;
586
Douglas Gregorc40290e2009-03-09 23:48:35 +0000587 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000588 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000589 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
591 Virtual, Access,
592 BaseType, BaseLoc))
593 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Douglas Gregor463421d2009-03-03 04:44:36 +0000595 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000596}
Douglas Gregor556877c2008-04-13 21:30:24 +0000597
Douglas Gregor463421d2009-03-03 04:44:36 +0000598/// \brief Performs the actual work of attaching the given base class
599/// specifiers to a C++ class.
600bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
601 unsigned NumBases) {
602 if (NumBases == 0)
603 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000604
605 // Used to keep track of which base types we have already seen, so
606 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000607 // that the key is always the unqualified canonical type of the base
608 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000609 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
610
611 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000612 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000613 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000615 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000616 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000617 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000618
Douglas Gregor29a92472008-10-22 17:49:05 +0000619 if (KnownBaseTypes[NewBaseType]) {
620 // C++ [class.mi]p3:
621 // A class shall not be specified as a direct base class of a
622 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000623 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000624 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000625 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000627
628 // Delete the duplicate base class specifier; we're going to
629 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000630 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000631
632 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000633 } else {
634 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000635 KnownBaseTypes[NewBaseType] = Bases[idx];
636 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000637 }
638 }
639
640 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000641 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000642
643 // Delete the remaining (good) base class specifiers, since their
644 // data has been copied into the CXXRecordDecl.
645 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000646 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000647
648 return Invalid;
649}
650
651/// ActOnBaseSpecifiers - Attach the given base specifiers to the
652/// class, after checking whether there are any duplicate base
653/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000654void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000655 unsigned NumBases) {
656 if (!ClassDecl || !Bases || !NumBases)
657 return;
658
659 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000660 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000661 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000662}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000663
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664/// \brief Determine whether the type \p Derived is a C++ class that is
665/// derived from the type \p Base.
666bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
667 if (!getLangOptions().CPlusPlus)
668 return false;
669
670 const RecordType *DerivedRT = Derived->getAs<RecordType>();
671 if (!DerivedRT)
672 return false;
673
674 const RecordType *BaseRT = Base->getAs<RecordType>();
675 if (!BaseRT)
676 return false;
677
678 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
679 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
680 return DerivedRD->isDerivedFrom(BaseRD);
681}
682
683/// \brief Determine whether the type \p Derived is a C++ class that is
684/// derived from the type \p Base.
685bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
686 if (!getLangOptions().CPlusPlus)
687 return false;
688
689 const RecordType *DerivedRT = Derived->getAs<RecordType>();
690 if (!DerivedRT)
691 return false;
692
693 const RecordType *BaseRT = Base->getAs<RecordType>();
694 if (!BaseRT)
695 return false;
696
697 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
698 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
699 return DerivedRD->isDerivedFrom(BaseRD, Paths);
700}
701
702/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
703/// conversion (where Derived and Base are class types) is
704/// well-formed, meaning that the conversion is unambiguous (and
705/// that all of the base classes are accessible). Returns true
706/// and emits a diagnostic if the code is ill-formed, returns false
707/// otherwise. Loc is the location where this routine should point to
708/// if there is an error, and Range is the source range to highlight
709/// if there is an error.
710bool
711Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
712 unsigned InaccessibleBaseID,
713 unsigned AmbigiousBaseConvID,
714 SourceLocation Loc, SourceRange Range,
715 DeclarationName Name) {
716 // First, determine whether the path from Derived to Base is
717 // ambiguous. This is slightly more expensive than checking whether
718 // the Derived to Base conversion exists, because here we need to
719 // explore multiple paths to determine if there is an ambiguity.
720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
721 /*DetectVirtual=*/false);
722 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
723 assert(DerivationOkay &&
724 "Can only be used with a derived-to-base conversion");
725 (void)DerivationOkay;
726
727 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000728 if (InaccessibleBaseID == 0)
729 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000730 // Check that the base class can be accessed.
731 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
732 Name);
733 }
734
735 // We know that the derived-to-base conversion is ambiguous, and
736 // we're going to produce a diagnostic. Perform the derived-to-base
737 // search just one more time to compute all of the possible paths so
738 // that we can print them out. This is more expensive than any of
739 // the previous derived-to-base checks we've done, but at this point
740 // performance isn't as much of an issue.
741 Paths.clear();
742 Paths.setRecordingPaths(true);
743 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
744 assert(StillOkay && "Can only be used with a derived-to-base conversion");
745 (void)StillOkay;
746
747 // Build up a textual representation of the ambiguous paths, e.g.,
748 // D -> B -> A, that will be used to illustrate the ambiguous
749 // conversions in the diagnostic. We only print one of the paths
750 // to each base class subobject.
751 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
752
753 Diag(Loc, AmbigiousBaseConvID)
754 << Derived << Base << PathDisplayStr << Range << Name;
755 return true;
756}
757
758bool
759Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000760 SourceLocation Loc, SourceRange Range,
761 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000762 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000763 IgnoreAccess ? 0 :
764 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000765 diag::err_ambiguous_derived_to_base_conv,
766 Loc, Range, DeclarationName());
767}
768
769
770/// @brief Builds a string representing ambiguous paths from a
771/// specific derived class to different subobjects of the same base
772/// class.
773///
774/// This function builds a string that can be used in error messages
775/// to show the different paths that one can take through the
776/// inheritance hierarchy to go from the derived class to different
777/// subobjects of a base class. The result looks something like this:
778/// @code
779/// struct D -> struct B -> struct A
780/// struct D -> struct C -> struct A
781/// @endcode
782std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
783 std::string PathDisplayStr;
784 std::set<unsigned> DisplayedPaths;
785 for (CXXBasePaths::paths_iterator Path = Paths.begin();
786 Path != Paths.end(); ++Path) {
787 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
788 // We haven't displayed a path to this particular base
789 // class subobject yet.
790 PathDisplayStr += "\n ";
791 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
792 for (CXXBasePath::const_iterator Element = Path->begin();
793 Element != Path->end(); ++Element)
794 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
795 }
796 }
797
798 return PathDisplayStr;
799}
800
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000801//===----------------------------------------------------------------------===//
802// C++ class member Handling
803//===----------------------------------------------------------------------===//
804
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000805/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
806/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
807/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000808/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000809Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000810Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000811 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000812 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
813 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000814 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000815 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000816 Expr *BitWidth = static_cast<Expr*>(BW);
817 Expr *Init = static_cast<Expr*>(InitExpr);
818 SourceLocation Loc = D.getIdentifierLoc();
819
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000820 bool isFunc = D.isFunctionDeclarator();
821
John McCall07e91c02009-08-06 02:15:43 +0000822 assert(!DS.isFriendSpecified());
823
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000824 // C++ 9.2p6: A member shall not be declared to have automatic storage
825 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000826 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
827 // data members and cannot be applied to names declared const or static,
828 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000829 switch (DS.getStorageClassSpec()) {
830 case DeclSpec::SCS_unspecified:
831 case DeclSpec::SCS_typedef:
832 case DeclSpec::SCS_static:
833 // FALL THROUGH.
834 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000835 case DeclSpec::SCS_mutable:
836 if (isFunc) {
837 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000838 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000839 else
Chris Lattner3b054132008-11-19 05:08:23 +0000840 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000841
Sebastian Redl8071edb2008-11-17 23:24:37 +0000842 // FIXME: It would be nicer if the keyword was ignored only for this
843 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000844 D.getMutableDeclSpec().ClearStorageClassSpecs();
845 } else {
846 QualType T = GetTypeForDeclarator(D, S);
847 diag::kind err = static_cast<diag::kind>(0);
848 if (T->isReferenceType())
849 err = diag::err_mutable_reference;
850 else if (T.isConstQualified())
851 err = diag::err_mutable_const;
852 if (err != 0) {
853 if (DS.getStorageClassSpecLoc().isValid())
854 Diag(DS.getStorageClassSpecLoc(), err);
855 else
856 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000857 // FIXME: It would be nicer if the keyword was ignored only for this
858 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000859 D.getMutableDeclSpec().ClearStorageClassSpecs();
860 }
861 }
862 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000863 default:
864 if (DS.getStorageClassSpecLoc().isValid())
865 Diag(DS.getStorageClassSpecLoc(),
866 diag::err_storageclass_invalid_for_member);
867 else
868 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
869 D.getMutableDeclSpec().ClearStorageClassSpecs();
870 }
871
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000872 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000873 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000874 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000875 // Check also for this case:
876 //
877 // typedef int f();
878 // f a;
879 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000880 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000881 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000882 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000883
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000884 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
885 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000886 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000887
888 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000889 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000890 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000891 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
892 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000893 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000894 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000895 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000896 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000897 if (!Member) {
898 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000899 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000900 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000901
902 // Non-instance-fields can't have a bitfield.
903 if (BitWidth) {
904 if (Member->isInvalidDecl()) {
905 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000906 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000907 // C++ 9.6p3: A bit-field shall not be a static member.
908 // "static member 'A' cannot be a bit-field"
909 Diag(Loc, diag::err_static_not_bitfield)
910 << Name << BitWidth->getSourceRange();
911 } else if (isa<TypedefDecl>(Member)) {
912 // "typedef member 'x' cannot be a bit-field"
913 Diag(Loc, diag::err_typedef_not_bitfield)
914 << Name << BitWidth->getSourceRange();
915 } else {
916 // A function typedef ("typedef int f(); f a;").
917 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
918 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000919 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000920 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Chris Lattnerd26760a2009-03-05 23:01:03 +0000923 DeleteExpr(BitWidth);
924 BitWidth = 0;
925 Member->setInvalidDecl();
926 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000927
928 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000929
Douglas Gregor3447e762009-08-20 22:52:58 +0000930 // If we have declared a member function template, set the access of the
931 // templated declaration as well.
932 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
933 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000934 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935
Douglas Gregor92751d42008-11-17 22:58:34 +0000936 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937
Douglas Gregor0c880302009-03-11 23:00:04 +0000938 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000939 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000940 if (Deleted) // FIXME: Source location is not very good.
941 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000942
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000943 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000944 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000945 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000947 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000948}
949
Douglas Gregore8381c02008-11-05 04:29:56 +0000950/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000951Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000952Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000953 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000954 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000955 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000956 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000957 SourceLocation IdLoc,
958 SourceLocation LParenLoc,
959 ExprTy **Args, unsigned NumArgs,
960 SourceLocation *CommaLocs,
961 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000962 if (!ConstructorD)
963 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000965 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000966
967 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000968 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000969 if (!Constructor) {
970 // The user wrote a constructor initializer on a function that is
971 // not a C++ constructor. Ignore the error for now, because we may
972 // have more member initializers coming; we'll diagnose it just
973 // once in ActOnMemInitializers.
974 return true;
975 }
976
977 CXXRecordDecl *ClassDecl = Constructor->getParent();
978
979 // C++ [class.base.init]p2:
980 // Names in a mem-initializer-id are looked up in the scope of the
981 // constructor’s class and, if not found in that scope, are looked
982 // up in the scope containing the constructor’s
983 // definition. [Note: if the constructor’s class contains a member
984 // with the same name as a direct or virtual base class of the
985 // class, a mem-initializer-id naming the member or base class and
986 // composed of a single identifier refers to the class member. A
987 // mem-initializer-id for the hidden base class may be specified
988 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000989 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000990 // Look for a member, first.
991 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000992 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000993 = ClassDecl->lookup(MemberOrBase);
994 if (Result.first != Result.second)
995 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000996
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000997 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000998
Eli Friedman8e1433b2009-07-29 19:44:27 +0000999 if (Member)
1000 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001001 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001002 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001003 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001004 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001005 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001006
1007 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001008 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001009 } else {
1010 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1011 LookupParsedName(R, S, &SS);
1012
1013 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1014 if (!TyD) {
1015 if (R.isAmbiguous()) return true;
1016
1017 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1018 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1019 return true;
1020 }
1021
1022 BaseType = Context.getTypeDeclType(TyD);
1023 if (SS.isSet()) {
1024 NestedNameSpecifier *Qualifier =
1025 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1026
1027 // FIXME: preserve source range information
1028 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1029 }
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
John McCallbcd03502009-12-07 02:54:59 +00001032 if (!TInfo)
1033 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001034
John McCallbcd03502009-12-07 02:54:59 +00001035 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001036 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001037}
1038
John McCalle22a04a2009-11-04 23:02:40 +00001039/// Checks an initializer expression for use of uninitialized fields, such as
1040/// containing the field that is being initialized. Returns true if there is an
1041/// uninitialized field was used an updates the SourceLocation parameter; false
1042/// otherwise.
1043static bool InitExprContainsUninitializedFields(const Stmt* S,
1044 const FieldDecl* LhsField,
1045 SourceLocation* L) {
1046 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1047 if (ME) {
1048 const NamedDecl* RhsField = ME->getMemberDecl();
1049 if (RhsField == LhsField) {
1050 // Initializing a field with itself. Throw a warning.
1051 // But wait; there are exceptions!
1052 // Exception #1: The field may not belong to this record.
1053 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1054 const Expr* base = ME->getBase();
1055 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1056 // Even though the field matches, it does not belong to this record.
1057 return false;
1058 }
1059 // None of the exceptions triggered; return true to indicate an
1060 // uninitialized field was used.
1061 *L = ME->getMemberLoc();
1062 return true;
1063 }
1064 }
1065 bool found = false;
1066 for (Stmt::const_child_iterator it = S->child_begin();
1067 it != S->child_end() && found == false;
1068 ++it) {
1069 if (isa<CallExpr>(S)) {
1070 // Do not descend into function calls or constructors, as the use
1071 // of an uninitialized field may be valid. One would have to inspect
1072 // the contents of the function/ctor to determine if it is safe or not.
1073 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1074 // may be safe, depending on what the function/ctor does.
1075 continue;
1076 }
1077 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1078 }
1079 return found;
1080}
1081
Eli Friedman8e1433b2009-07-29 19:44:27 +00001082Sema::MemInitResult
1083Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1084 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001085 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001086 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001087 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1088 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1089 ExprTemporaries.clear();
1090
John McCalle22a04a2009-11-04 23:02:40 +00001091 // Diagnose value-uses of fields to initialize themselves, e.g.
1092 // foo(foo)
1093 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001094 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001095 for (unsigned i = 0; i < NumArgs; ++i) {
1096 SourceLocation L;
1097 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1098 // FIXME: Return true in the case when other fields are used before being
1099 // uninitialized. For example, let this field be the i'th field. When
1100 // initializing the i'th field, throw a warning if any of the >= i'th
1101 // fields are used, as they are not yet initialized.
1102 // Right now we are only handling the case where the i'th field uses
1103 // itself in its initializer.
1104 Diag(L, diag::warn_field_is_uninit);
1105 }
1106 }
1107
Eli Friedman8e1433b2009-07-29 19:44:27 +00001108 bool HasDependentArg = false;
1109 for (unsigned i = 0; i < NumArgs; i++)
1110 HasDependentArg |= Args[i]->isTypeDependent();
1111
1112 CXXConstructorDecl *C = 0;
1113 QualType FieldType = Member->getType();
1114 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1115 FieldType = Array->getElementType();
1116 if (FieldType->isDependentType()) {
1117 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001118 } else if (FieldType->isRecordType()) {
1119 // Member is a record (struct/union/class), so pass the initializer
1120 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001121 if (!HasDependentArg) {
1122 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1123
1124 C = PerformInitializationByConstructor(FieldType,
1125 MultiExprArg(*this,
1126 (void**)Args,
1127 NumArgs),
1128 IdLoc,
1129 SourceRange(IdLoc, RParenLoc),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001130 Member->getDeclName(),
1131 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001132 ConstructorArgs);
1133
1134 if (C) {
1135 // Take over the constructor arguments as our own.
1136 NumArgs = ConstructorArgs.size();
1137 Args = (Expr **)ConstructorArgs.take();
1138 }
1139 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001140 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001141 // The member type is not a record type (or an array of record
1142 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001143 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001144 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1145 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001146 Expr *NewExp;
1147 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001148 if (FieldType->isReferenceType()) {
1149 Diag(IdLoc, diag::err_null_intialized_reference_member)
1150 << Member->getDeclName();
1151 return Diag(Member->getLocation(), diag::note_declared_at);
1152 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001153 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1154 NumArgs = 1;
1155 }
1156 else
1157 NewExp = (Expr*)Args[0];
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001158 if (PerformCopyInitialization(NewExp, FieldType, AA_Passing))
Eli Friedman8e1433b2009-07-29 19:44:27 +00001159 return true;
1160 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001161 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001162
1163 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1164 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1165 ExprTemporaries.clear();
1166
Eli Friedman8e1433b2009-07-29 19:44:27 +00001167 // FIXME: Perform direct initialization of the member.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001168 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1169 C, LParenLoc, (Expr **)Args,
1170 NumArgs, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001171}
1172
1173Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001174Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001175 Expr **Args, unsigned NumArgs,
1176 SourceLocation LParenLoc, SourceLocation RParenLoc,
1177 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001178 bool HasDependentArg = false;
1179 for (unsigned i = 0; i < NumArgs; i++)
1180 HasDependentArg |= Args[i]->isTypeDependent();
1181
John McCallbcd03502009-12-07 02:54:59 +00001182 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001183 if (!BaseType->isDependentType()) {
1184 if (!BaseType->isRecordType())
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001185 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCallbcd03502009-12-07 02:54:59 +00001186 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001187
1188 // C++ [class.base.init]p2:
1189 // [...] Unless the mem-initializer-id names a nonstatic data
1190 // member of the constructor’s class or a direct or virtual base
1191 // of that class, the mem-initializer is ill-formed. A
1192 // mem-initializer-list can initialize a base class using any
1193 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001194
Eli Friedman8e1433b2009-07-29 19:44:27 +00001195 // First, check for a direct base class.
1196 const CXXBaseSpecifier *DirectBaseSpec = 0;
1197 for (CXXRecordDecl::base_class_const_iterator Base =
1198 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001199 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001200 // We found a direct base of this type. That's what we're
1201 // initializing.
1202 DirectBaseSpec = &*Base;
1203 break;
1204 }
1205 }
Mike Stump11289f42009-09-09 15:08:12 +00001206
Eli Friedman8e1433b2009-07-29 19:44:27 +00001207 // Check for a virtual base class.
1208 // FIXME: We might be able to short-circuit this if we know in advance that
1209 // there are no virtual bases.
1210 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1212 // We haven't found a base yet; search the class hierarchy for a
1213 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1215 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001216 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001217 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001218 Path != Paths.end(); ++Path) {
1219 if (Path->back().Base->isVirtual()) {
1220 VirtualBaseSpec = Path->back().Base;
1221 break;
1222 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001223 }
1224 }
1225 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001226
1227 // C++ [base.class.init]p2:
1228 // If a mem-initializer-id is ambiguous because it designates both
1229 // a direct non-virtual base class and an inherited virtual base
1230 // class, the mem-initializer is ill-formed.
1231 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001232 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCallbcd03502009-12-07 02:54:59 +00001233 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001234 // C++ [base.class.init]p2:
1235 // Unless the mem-initializer-id names a nonstatic data membeer of the
1236 // constructor's class ot a direst or virtual base of that class, the
1237 // mem-initializer is ill-formed.
1238 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001239 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1240 << BaseType << ClassDecl->getNameAsCString()
John McCallbcd03502009-12-07 02:54:59 +00001241 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregore8381c02008-11-05 04:29:56 +00001242 }
1243
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001244 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001245 if (!BaseType->isDependentType() && !HasDependentArg) {
1246 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001247 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001248 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1249
1250 C = PerformInitializationByConstructor(BaseType,
1251 MultiExprArg(*this,
1252 (void**)Args, NumArgs),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001253 BaseLoc,
1254 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001255 Name,
1256 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001257 ConstructorArgs);
1258 if (C) {
1259 // Take over the constructor arguments as our own.
1260 NumArgs = ConstructorArgs.size();
1261 Args = (Expr **)ConstructorArgs.take();
1262 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001263 }
1264
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001265 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1266 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1267 ExprTemporaries.clear();
1268
John McCallbcd03502009-12-07 02:54:59 +00001269 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001270 LParenLoc, (Expr **)Args,
1271 NumArgs, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001272}
1273
Eli Friedman9cf6b592009-11-09 19:20:36 +00001274bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001275Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001276 CXXBaseOrMemberInitializer **Initializers,
1277 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001278 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001279 // We need to build the initializer AST according to order of construction
1280 // and not what user specified in the Initializers list.
1281 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1282 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1283 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1284 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001285 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001286
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001287 for (unsigned i = 0; i < NumInitializers; i++) {
1288 CXXBaseOrMemberInitializer *Member = Initializers[i];
1289 if (Member->isBaseInitializer()) {
1290 if (Member->getBaseClass()->isDependentType())
1291 HasDependentBaseInit = true;
1292 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1293 } else {
1294 AllBaseFields[Member->getMember()] = Member;
1295 }
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001298 if (HasDependentBaseInit) {
1299 // FIXME. This does not preserve the ordering of the initializers.
1300 // Try (with -Wreorder)
1301 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001302 // template<class X> struct B : A<X> {
1303 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001304 // int x1;
1305 // };
1306 // B<int> x;
1307 // On seeing one dependent type, we should essentially exit this routine
1308 // while preserving user-declared initializer list. When this routine is
1309 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001310 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001311
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001312 // If we have a dependent base initialization, we can't determine the
1313 // association between initializers and bases; just dump the known
1314 // initializers into the list, and don't try to deal with other bases.
1315 for (unsigned i = 0; i < NumInitializers; i++) {
1316 CXXBaseOrMemberInitializer *Member = Initializers[i];
1317 if (Member->isBaseInitializer())
1318 AllToInit.push_back(Member);
1319 }
1320 } else {
1321 // Push virtual bases before others.
1322 for (CXXRecordDecl::base_class_iterator VBase =
1323 ClassDecl->vbases_begin(),
1324 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1325 if (VBase->getType()->isDependentType())
1326 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001327 if (CXXBaseOrMemberInitializer *Value
1328 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001329 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001330 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001331 else {
Mike Stump11289f42009-09-09 15:08:12 +00001332 CXXRecordDecl *VBaseDecl =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001333 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001334 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001335 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001336 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001337 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1338 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1339 << 0 << VBase->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001340 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001341 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001342 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001343 continue;
1344 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001345
Anders Carlsson561f7932009-10-29 15:46:07 +00001346 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1347 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1348 Constructor->getLocation(), CtorArgs))
1349 continue;
1350
1351 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1352
Anders Carlssonbdd12402009-11-13 20:11:49 +00001353 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001354 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1355 // necessary.
1356 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001357 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001358 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001359 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001360 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001361 SourceLocation()),
1362 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001363 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001364 CtorArgs.takeAs<Expr>(),
1365 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001366 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001367 AllToInit.push_back(Member);
1368 }
1369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001371 for (CXXRecordDecl::base_class_iterator Base =
1372 ClassDecl->bases_begin(),
1373 E = ClassDecl->bases_end(); Base != E; ++Base) {
1374 // Virtuals are in the virtual base list and already constructed.
1375 if (Base->isVirtual())
1376 continue;
1377 // Skip dependent types.
1378 if (Base->getType()->isDependentType())
1379 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001380 if (CXXBaseOrMemberInitializer *Value
1381 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001382 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001383 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001384 else {
Mike Stump11289f42009-09-09 15:08:12 +00001385 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001386 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001387 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001388 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001389 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001390 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1391 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1392 << 0 << Base->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001393 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001394 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001395 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001396 continue;
1397 }
1398
1399 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1400 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1401 Constructor->getLocation(), CtorArgs))
1402 continue;
1403
1404 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001405
Anders Carlssonbdd12402009-11-13 20:11:49 +00001406 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001407 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1408 // necessary.
1409 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001410 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001411 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001412 new (Context) CXXBaseOrMemberInitializer(Context,
John McCallbcd03502009-12-07 02:54:59 +00001413 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001414 SourceLocation()),
1415 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001416 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001417 CtorArgs.takeAs<Expr>(),
1418 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001419 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001420 AllToInit.push_back(Member);
1421 }
1422 }
1423 }
Mike Stump11289f42009-09-09 15:08:12 +00001424
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001425 // non-static data members.
1426 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1427 E = ClassDecl->field_end(); Field != E; ++Field) {
1428 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001429 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001430 Field->getType()->getAs<RecordType>()) {
1431 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001432 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001433 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001434 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1435 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1436 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1437 // set to the anonymous union data member used in the initializer
1438 // list.
1439 Value->setMember(*Field);
1440 Value->setAnonUnionMember(*FA);
1441 AllToInit.push_back(Value);
1442 break;
1443 }
1444 }
1445 }
1446 continue;
1447 }
1448 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1449 AllToInit.push_back(Value);
1450 continue;
1451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Eli Friedmand7686ef2009-11-09 01:05:47 +00001453 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001454 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001455
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001456 QualType FT = Context.getBaseElementType((*Field)->getType());
1457 if (const RecordType* RT = FT->getAs<RecordType>()) {
1458 CXXConstructorDecl *Ctor =
1459 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001460 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001461 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1462 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1463 << 1 << (*Field)->getDeclName();
1464 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregore7488b92009-12-01 16:58:18 +00001465 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001466 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001467 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001468 continue;
1469 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001470
1471 if (FT.isConstQualified() && Ctor->isTrivial()) {
1472 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1473 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1474 << 1 << (*Field)->getDeclName();
1475 Diag((*Field)->getLocation(), diag::note_declared_at);
1476 HadError = true;
1477 }
1478
1479 // Don't create initializers for trivial constructors, since they don't
1480 // actually need to be run.
1481 if (Ctor->isTrivial())
1482 continue;
1483
Anders Carlsson561f7932009-10-29 15:46:07 +00001484 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1485 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1486 Constructor->getLocation(), CtorArgs))
1487 continue;
1488
Anders Carlssonbdd12402009-11-13 20:11:49 +00001489 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1490 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1491 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001492 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001493 new (Context) CXXBaseOrMemberInitializer(Context,
1494 *Field, SourceLocation(),
1495 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001496 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001497 CtorArgs.takeAs<Expr>(),
1498 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001499 SourceLocation());
1500
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001501 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001502 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001503 }
1504 else if (FT->isReferenceType()) {
1505 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001506 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1507 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001508 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001509 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001510 }
1511 else if (FT.isConstQualified()) {
1512 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001513 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1514 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001515 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001516 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001517 }
1518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001520 NumInitializers = AllToInit.size();
1521 if (NumInitializers > 0) {
1522 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1523 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1524 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001525
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001526 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1527 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1528 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1529 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001530
1531 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001532}
1533
Eli Friedman952c15d2009-07-21 19:28:10 +00001534static void *GetKeyForTopLevelField(FieldDecl *Field) {
1535 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001536 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001537 if (RT->getDecl()->isAnonymousStructOrUnion())
1538 return static_cast<void *>(RT->getDecl());
1539 }
1540 return static_cast<void *>(Field);
1541}
1542
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001543static void *GetKeyForBase(QualType BaseType) {
1544 if (const RecordType *RT = BaseType->getAs<RecordType>())
1545 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001546
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001547 assert(0 && "Unexpected base type!");
1548 return 0;
1549}
1550
Mike Stump11289f42009-09-09 15:08:12 +00001551static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001552 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001553 // For fields injected into the class via declaration of an anonymous union,
1554 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001555 if (Member->isMemberInitializer()) {
1556 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001557
Eli Friedmand7686ef2009-11-09 01:05:47 +00001558 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001559 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001560 // in AnonUnionMember field.
1561 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1562 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001563 if (Field->getDeclContext()->isRecord()) {
1564 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1565 if (RD->isAnonymousStructOrUnion())
1566 return static_cast<void *>(RD);
1567 }
1568 return static_cast<void *>(Field);
1569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001571 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001572}
1573
John McCallc90f6d72009-11-04 23:13:52 +00001574/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001575void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001576 SourceLocation ColonLoc,
1577 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001578 if (!ConstructorDecl)
1579 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001580
1581 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001582
1583 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001584 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001585
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001586 if (!Constructor) {
1587 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1588 return;
1589 }
Mike Stump11289f42009-09-09 15:08:12 +00001590
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001591 if (!Constructor->isDependentContext()) {
1592 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1593 bool err = false;
1594 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001595 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001596 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1597 void *KeyToMember = GetKeyForMember(Member);
1598 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1599 if (!PrevMember) {
1600 PrevMember = Member;
1601 continue;
1602 }
1603 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001604 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001605 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001606 << Field->getNameAsString()
1607 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001608 else {
1609 Type *BaseClass = Member->getBaseClass();
1610 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001611 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001612 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001613 << QualType(BaseClass, 0)
1614 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001615 }
1616 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1617 << 0;
1618 err = true;
1619 }
Mike Stump11289f42009-09-09 15:08:12 +00001620
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001621 if (err)
1622 return;
1623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Eli Friedmand7686ef2009-11-09 01:05:47 +00001625 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001626 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001627 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001629 if (Constructor->isDependentContext())
1630 return;
Mike Stump11289f42009-09-09 15:08:12 +00001631
1632 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001633 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001634 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001635 Diagnostic::Ignored)
1636 return;
Mike Stump11289f42009-09-09 15:08:12 +00001637
Anders Carlssone0eebb32009-08-27 05:45:01 +00001638 // Also issue warning if order of ctor-initializer list does not match order
1639 // of 1) base class declarations and 2) order of non-static data members.
1640 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001641
Anders Carlssone0eebb32009-08-27 05:45:01 +00001642 CXXRecordDecl *ClassDecl
1643 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1644 // Push virtual bases before others.
1645 for (CXXRecordDecl::base_class_iterator VBase =
1646 ClassDecl->vbases_begin(),
1647 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001648 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001649
Anders Carlssone0eebb32009-08-27 05:45:01 +00001650 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1651 E = ClassDecl->bases_end(); Base != E; ++Base) {
1652 // Virtuals are alread in the virtual base list and are constructed
1653 // first.
1654 if (Base->isVirtual())
1655 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001656 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001657 }
Mike Stump11289f42009-09-09 15:08:12 +00001658
Anders Carlssone0eebb32009-08-27 05:45:01 +00001659 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1660 E = ClassDecl->field_end(); Field != E; ++Field)
1661 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001662
Anders Carlssone0eebb32009-08-27 05:45:01 +00001663 int Last = AllBaseOrMembers.size();
1664 int curIndex = 0;
1665 CXXBaseOrMemberInitializer *PrevMember = 0;
1666 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001667 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001668 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1669 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001670
Anders Carlssone0eebb32009-08-27 05:45:01 +00001671 for (; curIndex < Last; curIndex++)
1672 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1673 break;
1674 if (curIndex == Last) {
1675 assert(PrevMember && "Member not in member list?!");
1676 // Initializer as specified in ctor-initializer list is out of order.
1677 // Issue a warning diagnostic.
1678 if (PrevMember->isBaseInitializer()) {
1679 // Diagnostics is for an initialized base class.
1680 Type *BaseClass = PrevMember->getBaseClass();
1681 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001682 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001683 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001684 } else {
1685 FieldDecl *Field = PrevMember->getMember();
1686 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001687 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001688 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001689 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001690 // Also the note!
1691 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001692 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001693 diag::note_fieldorbase_initialized_here) << 0
1694 << Field->getNameAsString();
1695 else {
1696 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001697 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001698 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001699 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001700 }
1701 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001702 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001703 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001704 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001705 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001706 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001707}
1708
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001709void
Anders Carlssondee9a302009-11-17 04:44:12 +00001710Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1711 // Ignore dependent destructors.
1712 if (Destructor->isDependentContext())
1713 return;
1714
1715 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001716
Anders Carlssondee9a302009-11-17 04:44:12 +00001717 // Non-static data members.
1718 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1719 E = ClassDecl->field_end(); I != E; ++I) {
1720 FieldDecl *Field = *I;
1721
1722 QualType FieldType = Context.getBaseElementType(Field->getType());
1723
1724 const RecordType* RT = FieldType->getAs<RecordType>();
1725 if (!RT)
1726 continue;
1727
1728 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1729 if (FieldClassDecl->hasTrivialDestructor())
1730 continue;
1731
1732 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1733 MarkDeclarationReferenced(Destructor->getLocation(),
1734 const_cast<CXXDestructorDecl*>(Dtor));
1735 }
1736
1737 // Bases.
1738 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1739 E = ClassDecl->bases_end(); Base != E; ++Base) {
1740 // Ignore virtual bases.
1741 if (Base->isVirtual())
1742 continue;
1743
1744 // Ignore trivial destructors.
1745 CXXRecordDecl *BaseClassDecl
1746 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1747 if (BaseClassDecl->hasTrivialDestructor())
1748 continue;
1749
1750 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1751 MarkDeclarationReferenced(Destructor->getLocation(),
1752 const_cast<CXXDestructorDecl*>(Dtor));
1753 }
1754
1755 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001756 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1757 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001758 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001759 CXXRecordDecl *BaseClassDecl
1760 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1761 if (BaseClassDecl->hasTrivialDestructor())
1762 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001763
1764 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1765 MarkDeclarationReferenced(Destructor->getLocation(),
1766 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001767 }
1768}
1769
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001770void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001771 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001772 return;
Mike Stump11289f42009-09-09 15:08:12 +00001773
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001774 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001775
1776 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001777 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001778 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001779}
1780
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001781namespace {
1782 /// PureVirtualMethodCollector - traverses a class and its superclasses
1783 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001784 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001785 ASTContext &Context;
1786
Sebastian Redlb7d64912009-03-22 21:28:55 +00001787 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001788 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001789
1790 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001791 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001792
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001793 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001795 public:
Mike Stump11289f42009-09-09 15:08:12 +00001796 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001797 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001798
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001799 MethodList List;
1800 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001802 // Copy the temporary list to methods, and make sure to ignore any
1803 // null entries.
1804 for (size_t i = 0, e = List.size(); i != e; ++i) {
1805 if (List[i])
1806 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001807 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001808 }
Mike Stump11289f42009-09-09 15:08:12 +00001809
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001810 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001811
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001812 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1813 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001814 };
Mike Stump11289f42009-09-09 15:08:12 +00001815
1816 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001817 MethodList& Methods) {
1818 // First, collect the pure virtual methods for the base classes.
1819 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1820 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001821 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001822 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001823 if (BaseDecl && BaseDecl->isAbstract())
1824 Collect(BaseDecl, Methods);
1825 }
1826 }
Mike Stump11289f42009-09-09 15:08:12 +00001827
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001828 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001829 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001830
Anders Carlsson3c012712009-05-17 00:00:05 +00001831 MethodSetTy OverriddenMethods;
1832 size_t MethodsSize = Methods.size();
1833
Mike Stump11289f42009-09-09 15:08:12 +00001834 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001835 i != e; ++i) {
1836 // Traverse the record, looking for methods.
1837 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001838 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001839 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001840 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001841
Anders Carlsson700179432009-10-18 19:34:08 +00001842 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001843 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1844 E = MD->end_overridden_methods(); I != E; ++I) {
1845 // Keep track of the overridden methods.
1846 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001847 }
1848 }
1849 }
Mike Stump11289f42009-09-09 15:08:12 +00001850
1851 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001852 // overridden.
1853 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1854 if (OverriddenMethods.count(Methods[i]))
1855 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001858 }
1859}
Douglas Gregore8381c02008-11-05 04:29:56 +00001860
Anders Carlssoneabf7702009-08-27 00:13:57 +00001861
Mike Stump11289f42009-09-09 15:08:12 +00001862bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001863 unsigned DiagID, AbstractDiagSelID SelID,
1864 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001865 if (SelID == -1)
1866 return RequireNonAbstractType(Loc, T,
1867 PDiag(DiagID), CurrentRD);
1868 else
1869 return RequireNonAbstractType(Loc, T,
1870 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001871}
1872
Anders Carlssoneabf7702009-08-27 00:13:57 +00001873bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1874 const PartialDiagnostic &PD,
1875 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001876 if (!getLangOptions().CPlusPlus)
1877 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001878
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001879 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001880 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001881 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001883 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001884 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001885 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001886 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001887
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001888 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001889 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001890 }
Mike Stump11289f42009-09-09 15:08:12 +00001891
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001892 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001893 if (!RT)
1894 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001895
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001896 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1897 if (!RD)
1898 return false;
1899
Anders Carlssonb57738b2009-03-24 17:23:42 +00001900 if (CurrentRD && CurrentRD != RD)
1901 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001903 if (!RD->isAbstract())
1904 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Anders Carlssoneabf7702009-08-27 00:13:57 +00001906 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001908 // Check if we've already emitted the list of pure virtual functions for this
1909 // class.
1910 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1911 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001912
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001913 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001914
1915 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001916 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1917 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001918
1919 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001920 MD->getDeclName();
1921 }
1922
1923 if (!PureVirtualClassDiagSet)
1924 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1925 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001926
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001927 return true;
1928}
1929
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001930namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001931 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001932 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1933 Sema &SemaRef;
1934 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001935
Anders Carlssonb57738b2009-03-24 17:23:42 +00001936 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001937 bool Invalid = false;
1938
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001939 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1940 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001941 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001942
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001943 return Invalid;
1944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Anders Carlssonb57738b2009-03-24 17:23:42 +00001946 public:
1947 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1948 : SemaRef(SemaRef), AbstractClass(ac) {
1949 Visit(SemaRef.Context.getTranslationUnitDecl());
1950 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001951
Anders Carlssonb57738b2009-03-24 17:23:42 +00001952 bool VisitFunctionDecl(const FunctionDecl *FD) {
1953 if (FD->isThisDeclarationADefinition()) {
1954 // No need to do the check if we're in a definition, because it requires
1955 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001956 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001957 return VisitDeclContext(FD);
1958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Anders Carlssonb57738b2009-03-24 17:23:42 +00001960 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001961 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001962 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001963 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1964 diag::err_abstract_type_in_decl,
1965 Sema::AbstractReturnType,
1966 AbstractClass);
1967
Mike Stump11289f42009-09-09 15:08:12 +00001968 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001969 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001970 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001971 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001972 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001973 VD->getOriginalType(),
1974 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001975 Sema::AbstractParamType,
1976 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001977 }
1978
1979 return Invalid;
1980 }
Mike Stump11289f42009-09-09 15:08:12 +00001981
Anders Carlssonb57738b2009-03-24 17:23:42 +00001982 bool VisitDecl(const Decl* D) {
1983 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1984 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001985
Anders Carlssonb57738b2009-03-24 17:23:42 +00001986 return false;
1987 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001988 };
1989}
1990
Douglas Gregorc99f1552009-12-03 18:33:45 +00001991/// \brief Perform semantic checks on a class definition that has been
1992/// completing, introducing implicitly-declared members, checking for
1993/// abstract types, etc.
1994void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1995 if (!Record || Record->isInvalidDecl())
1996 return;
1997
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00001998 if (!Record->isDependentType())
1999 AddImplicitlyDeclaredMembersToClass(Record);
2000
2001 if (Record->isInvalidDecl())
2002 return;
2003
Douglas Gregorc99f1552009-12-03 18:33:45 +00002004 if (!Record->isAbstract()) {
2005 // Collect all the pure virtual methods and see if this is an abstract
2006 // class after all.
2007 PureVirtualMethodCollector Collector(Context, Record);
2008 if (!Collector.empty())
2009 Record->setAbstract(true);
2010 }
2011
2012 if (Record->isAbstract())
2013 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002014}
2015
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002016void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002017 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002018 SourceLocation LBrac,
2019 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002020 if (!TagDecl)
2021 return;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002023 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002024
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002025 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002026 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00002027 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00002028
Douglas Gregorc99f1552009-12-03 18:33:45 +00002029 CheckCompletedCXXClass(
2030 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002031}
2032
Douglas Gregor05379422008-11-03 17:51:48 +00002033/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2034/// special functions, such as the default constructor, copy
2035/// constructor, or destructor, to the given C++ class (C++
2036/// [special]p1). This routine can only be executed just before the
2037/// definition of the class is complete.
2038void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002039 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002040 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002041
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002042 // FIXME: Implicit declarations have exception specifications, which are
2043 // the union of the specifications of the implicitly called functions.
2044
Douglas Gregor05379422008-11-03 17:51:48 +00002045 if (!ClassDecl->hasUserDeclaredConstructor()) {
2046 // C++ [class.ctor]p5:
2047 // A default constructor for a class X is a constructor of class X
2048 // that can be called without an argument. If there is no
2049 // user-declared constructor for class X, a default constructor is
2050 // implicitly declared. An implicitly-declared default constructor
2051 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002052 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002053 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002054 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002055 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002056 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002057 Context.getFunctionType(Context.VoidTy,
2058 0, 0, false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002059 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002060 /*isExplicit=*/false,
2061 /*isInline=*/true,
2062 /*isImplicitlyDeclared=*/true);
2063 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002064 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002065 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002066 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002067 }
2068
2069 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2070 // C++ [class.copy]p4:
2071 // If the class definition does not explicitly declare a copy
2072 // constructor, one is declared implicitly.
2073
2074 // C++ [class.copy]p5:
2075 // The implicitly-declared copy constructor for a class X will
2076 // have the form
2077 //
2078 // X::X(const X&)
2079 //
2080 // if
2081 bool HasConstCopyConstructor = true;
2082
2083 // -- each direct or virtual base class B of X has a copy
2084 // constructor whose first parameter is of type const B& or
2085 // const volatile B&, and
2086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2087 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2088 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002089 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002090 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002091 = BaseClassDecl->hasConstCopyConstructor(Context);
2092 }
2093
2094 // -- for all the nonstatic data members of X that are of a
2095 // class type M (or array thereof), each such class type
2096 // has a copy constructor whose first parameter is of type
2097 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002098 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2099 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002100 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002101 QualType FieldType = (*Field)->getType();
2102 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2103 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002104 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002105 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002106 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002107 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002108 = FieldClassDecl->hasConstCopyConstructor(Context);
2109 }
2110 }
2111
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002112 // Otherwise, the implicitly declared copy constructor will have
2113 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002114 //
2115 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002116 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002117 if (HasConstCopyConstructor)
2118 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002119 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002120
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002121 // An implicitly-declared copy constructor is an inline public
2122 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002123 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002124 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002125 CXXConstructorDecl *CopyConstructor
2126 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002127 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002128 Context.getFunctionType(Context.VoidTy,
2129 &ArgType, 1,
2130 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002131 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002132 /*isExplicit=*/false,
2133 /*isInline=*/true,
2134 /*isImplicitlyDeclared=*/true);
2135 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002136 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002137 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002138
2139 // Add the parameter to the constructor.
2140 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2141 ClassDecl->getLocation(),
2142 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002143 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002144 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002145 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002146 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002147 }
2148
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002149 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2150 // Note: The following rules are largely analoguous to the copy
2151 // constructor rules. Note that virtual bases are not taken into account
2152 // for determining the argument type of the operator. Note also that
2153 // operators taking an object instead of a reference are allowed.
2154 //
2155 // C++ [class.copy]p10:
2156 // If the class definition does not explicitly declare a copy
2157 // assignment operator, one is declared implicitly.
2158 // The implicitly-defined copy assignment operator for a class X
2159 // will have the form
2160 //
2161 // X& X::operator=(const X&)
2162 //
2163 // if
2164 bool HasConstCopyAssignment = true;
2165
2166 // -- each direct base class B of X has a copy assignment operator
2167 // whose parameter is of type const B&, const volatile B& or B,
2168 // and
2169 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2170 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002171 assert(!Base->getType()->isDependentType() &&
2172 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002173 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002174 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002175 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002176 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002177 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002178 }
2179
2180 // -- for all the nonstatic data members of X that are of a class
2181 // type M (or array thereof), each such class type has a copy
2182 // assignment operator whose parameter is of type const M&,
2183 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002184 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2185 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002186 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002187 QualType FieldType = (*Field)->getType();
2188 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2189 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002190 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002191 const CXXRecordDecl *FieldClassDecl
2192 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002193 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002194 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002195 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002196 }
2197 }
2198
2199 // Otherwise, the implicitly declared copy assignment operator will
2200 // have the form
2201 //
2202 // X& X::operator=(X&)
2203 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002204 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002205 if (HasConstCopyAssignment)
2206 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002207 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002208
2209 // An implicitly-declared copy assignment operator is an inline public
2210 // member of its class.
2211 DeclarationName Name =
2212 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2213 CXXMethodDecl *CopyAssignment =
2214 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2215 Context.getFunctionType(RetType, &ArgType, 1,
2216 false, 0),
John McCallbcd03502009-12-07 02:54:59 +00002217 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002218 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002219 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002220 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002221 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002222
2223 // Add the parameter to the operator.
2224 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2225 ClassDecl->getLocation(),
2226 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002227 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002228 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002229 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002230
2231 // Don't call addedAssignmentOperator. There is no way to distinguish an
2232 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002233 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002234 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002235 }
2236
Douglas Gregor1349b452008-12-15 21:24:18 +00002237 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002238 // C++ [class.dtor]p2:
2239 // If a class has no user-declared destructor, a destructor is
2240 // declared implicitly. An implicitly-declared destructor is an
2241 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002242 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002243 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002244 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002245 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002246 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002247 Context.getFunctionType(Context.VoidTy,
2248 0, 0, false, 0),
2249 /*isInline=*/true,
2250 /*isImplicitlyDeclared=*/true);
2251 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002252 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002253 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002254 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002255
2256 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002257 }
Douglas Gregor05379422008-11-03 17:51:48 +00002258}
2259
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002260void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002261 Decl *D = TemplateD.getAs<Decl>();
2262 if (!D)
2263 return;
2264
2265 TemplateParameterList *Params = 0;
2266 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2267 Params = Template->getTemplateParameters();
2268 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2269 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2270 Params = PartialSpec->getTemplateParameters();
2271 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002272 return;
2273
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002274 for (TemplateParameterList::iterator Param = Params->begin(),
2275 ParamEnd = Params->end();
2276 Param != ParamEnd; ++Param) {
2277 NamedDecl *Named = cast<NamedDecl>(*Param);
2278 if (Named->getDeclName()) {
2279 S->AddDecl(DeclPtrTy::make(Named));
2280 IdResolver.AddDecl(Named);
2281 }
2282 }
2283}
2284
John McCall6df5fef2009-12-19 10:49:29 +00002285void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2286 if (!RecordD) return;
2287 AdjustDeclIfTemplate(RecordD);
2288 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2289 PushDeclContext(S, Record);
2290}
2291
2292void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2293 if (!RecordD) return;
2294 PopDeclContext();
2295}
2296
Douglas Gregor4d87df52008-12-16 21:30:33 +00002297/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2298/// parsing a top-level (non-nested) C++ class, and we are now
2299/// parsing those parts of the given Method declaration that could
2300/// not be parsed earlier (C++ [class.mem]p2), such as default
2301/// arguments. This action should enter the scope of the given
2302/// Method declaration as if we had just parsed the qualified method
2303/// name. However, it should not bring the parameters into scope;
2304/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002305void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002306}
2307
2308/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2309/// C++ method declaration. We're (re-)introducing the given
2310/// function parameter into scope for use in parsing later parts of
2311/// the method declaration. For example, we could see an
2312/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002313void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002314 if (!ParamD)
2315 return;
Mike Stump11289f42009-09-09 15:08:12 +00002316
Chris Lattner83f095c2009-03-28 19:18:32 +00002317 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002318
2319 // If this parameter has an unparsed default argument, clear it out
2320 // to make way for the parsed default argument.
2321 if (Param->hasUnparsedDefaultArg())
2322 Param->setDefaultArg(0);
2323
Chris Lattner83f095c2009-03-28 19:18:32 +00002324 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002325 if (Param->getDeclName())
2326 IdResolver.AddDecl(Param);
2327}
2328
2329/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2330/// processing the delayed method declaration for Method. The method
2331/// declaration is now considered finished. There may be a separate
2332/// ActOnStartOfFunctionDef action later (not necessarily
2333/// immediately!) for this method, if it was also defined inside the
2334/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002335void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002336 if (!MethodD)
2337 return;
Mike Stump11289f42009-09-09 15:08:12 +00002338
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002339 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Chris Lattner83f095c2009-03-28 19:18:32 +00002341 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002342
2343 // Now that we have our default arguments, check the constructor
2344 // again. It could produce additional diagnostics or affect whether
2345 // the class has implicitly-declared destructors, among other
2346 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002347 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2348 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002349
2350 // Check the default arguments, which we may have added.
2351 if (!Method->isInvalidDecl())
2352 CheckCXXDefaultArguments(Method);
2353}
2354
Douglas Gregor831c93f2008-11-05 20:51:48 +00002355/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002356/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002357/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002358/// emit diagnostics and set the invalid bit to true. In any case, the type
2359/// will be updated to reflect a well-formed type for the constructor and
2360/// returned.
2361QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2362 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002363 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002364
2365 // C++ [class.ctor]p3:
2366 // A constructor shall not be virtual (10.3) or static (9.4). A
2367 // constructor can be invoked for a const, volatile or const
2368 // volatile object. A constructor shall not be declared const,
2369 // volatile, or const volatile (9.3.2).
2370 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002371 if (!D.isInvalidType())
2372 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2373 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2374 << SourceRange(D.getIdentifierLoc());
2375 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002376 }
2377 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002378 if (!D.isInvalidType())
2379 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2380 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2381 << SourceRange(D.getIdentifierLoc());
2382 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002383 SC = FunctionDecl::None;
2384 }
Mike Stump11289f42009-09-09 15:08:12 +00002385
Chris Lattner38378bf2009-04-25 08:28:21 +00002386 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2387 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002388 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002389 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2390 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002391 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002392 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2393 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002394 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002395 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2396 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002397 }
Mike Stump11289f42009-09-09 15:08:12 +00002398
Douglas Gregor831c93f2008-11-05 20:51:48 +00002399 // Rebuild the function type "R" without any type qualifiers (in
2400 // case any of the errors above fired) and with "void" as the
2401 // return type, since constructors don't have return types. We
2402 // *always* have to do this, because GetTypeForDeclarator will
2403 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002404 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002405 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2406 Proto->getNumArgs(),
2407 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002408}
2409
Douglas Gregor4d87df52008-12-16 21:30:33 +00002410/// CheckConstructor - Checks a fully-formed constructor for
2411/// well-formedness, issuing any diagnostics required. Returns true if
2412/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002413void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002414 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002415 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2416 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002417 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002418
2419 // C++ [class.copy]p3:
2420 // A declaration of a constructor for a class X is ill-formed if
2421 // its first parameter is of type (optionally cv-qualified) X and
2422 // either there are no other parameters or else all other
2423 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002424 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002425 ((Constructor->getNumParams() == 1) ||
2426 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002427 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2428 Constructor->getTemplateSpecializationKind()
2429 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002430 QualType ParamType = Constructor->getParamDecl(0)->getType();
2431 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2432 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002433 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2434 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002435 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002436
2437 // FIXME: Rather that making the constructor invalid, we should endeavor
2438 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002439 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002440 }
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Douglas Gregor4d87df52008-12-16 21:30:33 +00002443 // Notify the class that we've added a constructor.
2444 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002445}
2446
Anders Carlsson26a807d2009-11-30 21:24:50 +00002447/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2448/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002449bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002450 CXXRecordDecl *RD = Destructor->getParent();
2451
2452 if (Destructor->isVirtual()) {
2453 SourceLocation Loc;
2454
2455 if (!Destructor->isImplicit())
2456 Loc = Destructor->getLocation();
2457 else
2458 Loc = RD->getLocation();
2459
2460 // If we have a virtual destructor, look up the deallocation function
2461 FunctionDecl *OperatorDelete = 0;
2462 DeclarationName Name =
2463 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002464 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002465 return true;
2466
2467 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002468 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002469
2470 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002471}
2472
Mike Stump11289f42009-09-09 15:08:12 +00002473static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002474FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2475 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2476 FTI.ArgInfo[0].Param &&
2477 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2478}
2479
Douglas Gregor831c93f2008-11-05 20:51:48 +00002480/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2481/// the well-formednes of the destructor declarator @p D with type @p
2482/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002483/// emit diagnostics and set the declarator to invalid. Even if this happens,
2484/// will be updated to reflect a well-formed type for the destructor and
2485/// returned.
2486QualType Sema::CheckDestructorDeclarator(Declarator &D,
2487 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002488 // C++ [class.dtor]p1:
2489 // [...] A typedef-name that names a class is a class-name
2490 // (7.1.3); however, a typedef-name that names a class shall not
2491 // be used as the identifier in the declarator for a destructor
2492 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002493 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002494 if (isa<TypedefType>(DeclaratorType)) {
2495 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002496 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002497 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002498 }
2499
2500 // C++ [class.dtor]p2:
2501 // A destructor is used to destroy objects of its class type. A
2502 // destructor takes no parameters, and no return type can be
2503 // specified for it (not even void). The address of a destructor
2504 // shall not be taken. A destructor shall not be static. A
2505 // destructor can be invoked for a const, volatile or const
2506 // volatile object. A destructor shall not be declared const,
2507 // volatile or const volatile (9.3.2).
2508 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002509 if (!D.isInvalidType())
2510 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2511 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2512 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002513 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002514 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002515 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002516 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002517 // Destructors don't have return types, but the parser will
2518 // happily parse something like:
2519 //
2520 // class X {
2521 // float ~X();
2522 // };
2523 //
2524 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002525 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2526 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2527 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002528 }
Mike Stump11289f42009-09-09 15:08:12 +00002529
Chris Lattner38378bf2009-04-25 08:28:21 +00002530 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2531 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002532 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002533 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2534 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002535 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002536 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2537 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002538 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002539 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2540 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002541 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002542 }
2543
2544 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002545 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002546 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2547
2548 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002549 FTI.freeArgs();
2550 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002551 }
2552
Mike Stump11289f42009-09-09 15:08:12 +00002553 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002554 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002555 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002556 D.setInvalidType();
2557 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002558
2559 // Rebuild the function type "R" without any type qualifiers or
2560 // parameters (in case any of the errors above fired) and with
2561 // "void" as the return type, since destructors don't have return
2562 // types. We *always* have to do this, because GetTypeForDeclarator
2563 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002564 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002565}
2566
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002567/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2568/// well-formednes of the conversion function declarator @p D with
2569/// type @p R. If there are any errors in the declarator, this routine
2570/// will emit diagnostics and return true. Otherwise, it will return
2571/// false. Either way, the type @p R will be updated to reflect a
2572/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002573void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002574 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002575 // C++ [class.conv.fct]p1:
2576 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002577 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002578 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002579 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002580 if (!D.isInvalidType())
2581 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2582 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2583 << SourceRange(D.getIdentifierLoc());
2584 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002585 SC = FunctionDecl::None;
2586 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002587 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002588 // Conversion functions don't have return types, but the parser will
2589 // happily parse something like:
2590 //
2591 // class X {
2592 // float operator bool();
2593 // };
2594 //
2595 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002596 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2597 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2598 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002599 }
2600
2601 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002602 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002603 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2604
2605 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002606 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002607 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002608 }
2609
Mike Stump11289f42009-09-09 15:08:12 +00002610 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002611 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002612 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002613 D.setInvalidType();
2614 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002615
2616 // C++ [class.conv.fct]p4:
2617 // The conversion-type-id shall not represent a function type nor
2618 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002619 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002620 if (ConvType->isArrayType()) {
2621 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2622 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002623 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002624 } else if (ConvType->isFunctionType()) {
2625 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2626 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002627 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002628 }
2629
2630 // Rebuild the function type "R" without any parameters (in case any
2631 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002632 // return type.
2633 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002634 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002635
Douglas Gregor5fb53972009-01-14 15:45:31 +00002636 // C++0x explicit conversion operators.
2637 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002638 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002639 diag::warn_explicit_conversion_functions)
2640 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002641}
2642
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002643/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2644/// the declaration of the given C++ conversion function. This routine
2645/// is responsible for recording the conversion function in the C++
2646/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002647Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002648 assert(Conversion && "Expected to receive a conversion function declaration");
2649
Douglas Gregor4287b372008-12-12 08:25:50 +00002650 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002651
2652 // Make sure we aren't redeclaring the conversion function.
2653 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002654
2655 // C++ [class.conv.fct]p1:
2656 // [...] A conversion function is never used to convert a
2657 // (possibly cv-qualified) object to the (possibly cv-qualified)
2658 // same object type (or a reference to it), to a (possibly
2659 // cv-qualified) base class of that type (or a reference to it),
2660 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002661 // FIXME: Suppress this warning if the conversion function ends up being a
2662 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002663 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002664 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002665 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002666 ConvType = ConvTypeRef->getPointeeType();
2667 if (ConvType->isRecordType()) {
2668 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2669 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002670 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002671 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002672 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002673 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002674 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002675 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002676 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002677 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002678 }
2679
Douglas Gregor1dc98262008-12-26 15:00:45 +00002680 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002681 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002682 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002683 = Conversion->getDescribedFunctionTemplate())
2684 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002685 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2686 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002687 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002688 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002689 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002690 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002691 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002692 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002693
Chris Lattner83f095c2009-03-28 19:18:32 +00002694 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002695}
2696
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002697//===----------------------------------------------------------------------===//
2698// Namespace Handling
2699//===----------------------------------------------------------------------===//
2700
2701/// ActOnStartNamespaceDef - This is called at the start of a namespace
2702/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002703Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2704 SourceLocation IdentLoc,
2705 IdentifierInfo *II,
2706 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002707 NamespaceDecl *Namespc =
2708 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2709 Namespc->setLBracLoc(LBrace);
2710
2711 Scope *DeclRegionScope = NamespcScope->getParent();
2712
2713 if (II) {
2714 // C++ [namespace.def]p2:
2715 // The identifier in an original-namespace-definition shall not have been
2716 // previously defined in the declarative region in which the
2717 // original-namespace-definition appears. The identifier in an
2718 // original-namespace-definition is the name of the namespace. Subsequently
2719 // in that declarative region, it is treated as an original-namespace-name.
2720
John McCall9f3059a2009-10-09 21:13:30 +00002721 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002722 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002723 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002724
Douglas Gregor91f84212008-12-11 16:49:14 +00002725 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2726 // This is an extended namespace definition.
2727 // Attach this namespace decl to the chain of extended namespace
2728 // definitions.
2729 OrigNS->setNextNamespace(Namespc);
2730 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002731
Mike Stump11289f42009-09-09 15:08:12 +00002732 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002733 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002734 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002735 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002736 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002737 } else if (PrevDecl) {
2738 // This is an invalid name redefinition.
2739 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2740 << Namespc->getDeclName();
2741 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2742 Namespc->setInvalidDecl();
2743 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002744 } else if (II->isStr("std") &&
2745 CurContext->getLookupContext()->isTranslationUnit()) {
2746 // This is the first "real" definition of the namespace "std", so update
2747 // our cache of the "std" namespace to point at this definition.
2748 if (StdNamespace) {
2749 // We had already defined a dummy namespace "std". Link this new
2750 // namespace definition to the dummy namespace "std".
2751 StdNamespace->setNextNamespace(Namespc);
2752 StdNamespace->setLocation(IdentLoc);
2753 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2754 }
2755
2756 // Make our StdNamespace cache point at the first real definition of the
2757 // "std" namespace.
2758 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002759 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002760
2761 PushOnScopeChains(Namespc, DeclRegionScope);
2762 } else {
John McCall4fa53422009-10-01 00:25:31 +00002763 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00002764 assert(Namespc->isAnonymousNamespace());
2765 CurContext->addDecl(Namespc);
2766
2767 // Link the anonymous namespace into its parent.
2768 NamespaceDecl *PrevDecl;
2769 DeclContext *Parent = CurContext->getLookupContext();
2770 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2771 PrevDecl = TU->getAnonymousNamespace();
2772 TU->setAnonymousNamespace(Namespc);
2773 } else {
2774 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2775 PrevDecl = ND->getAnonymousNamespace();
2776 ND->setAnonymousNamespace(Namespc);
2777 }
2778
2779 // Link the anonymous namespace with its previous declaration.
2780 if (PrevDecl) {
2781 assert(PrevDecl->isAnonymousNamespace());
2782 assert(!PrevDecl->getNextNamespace());
2783 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2784 PrevDecl->setNextNamespace(Namespc);
2785 }
John McCall4fa53422009-10-01 00:25:31 +00002786
2787 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2788 // behaves as if it were replaced by
2789 // namespace unique { /* empty body */ }
2790 // using namespace unique;
2791 // namespace unique { namespace-body }
2792 // where all occurrences of 'unique' in a translation unit are
2793 // replaced by the same identifier and this identifier differs
2794 // from all other identifiers in the entire program.
2795
2796 // We just create the namespace with an empty name and then add an
2797 // implicit using declaration, just like the standard suggests.
2798 //
2799 // CodeGen enforces the "universally unique" aspect by giving all
2800 // declarations semantically contained within an anonymous
2801 // namespace internal linkage.
2802
John McCall0db42252009-12-16 02:06:49 +00002803 if (!PrevDecl) {
2804 UsingDirectiveDecl* UD
2805 = UsingDirectiveDecl::Create(Context, CurContext,
2806 /* 'using' */ LBrace,
2807 /* 'namespace' */ SourceLocation(),
2808 /* qualifier */ SourceRange(),
2809 /* NNS */ NULL,
2810 /* identifier */ SourceLocation(),
2811 Namespc,
2812 /* Ancestor */ CurContext);
2813 UD->setImplicit();
2814 CurContext->addDecl(UD);
2815 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002816 }
2817
2818 // Although we could have an invalid decl (i.e. the namespace name is a
2819 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002820 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2821 // for the namespace has the declarations that showed up in that particular
2822 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002823 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002824 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002825}
2826
Sebastian Redla6602e92009-11-23 15:34:23 +00002827/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2828/// is a namespace alias, returns the namespace it points to.
2829static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2830 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2831 return AD->getNamespace();
2832 return dyn_cast_or_null<NamespaceDecl>(D);
2833}
2834
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002835/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2836/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002837void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2838 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002839 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2840 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2841 Namespc->setRBracLoc(RBrace);
2842 PopDeclContext();
2843}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002844
Chris Lattner83f095c2009-03-28 19:18:32 +00002845Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2846 SourceLocation UsingLoc,
2847 SourceLocation NamespcLoc,
2848 const CXXScopeSpec &SS,
2849 SourceLocation IdentLoc,
2850 IdentifierInfo *NamespcName,
2851 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002852 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2853 assert(NamespcName && "Invalid NamespcName.");
2854 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002855 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002856
Douglas Gregor889ceb72009-02-03 19:21:40 +00002857 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002858
Douglas Gregor34074322009-01-14 22:20:51 +00002859 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002860 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2861 LookupParsedName(R, S, &SS);
2862 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002863 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002864
John McCall9f3059a2009-10-09 21:13:30 +00002865 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002866 NamedDecl *Named = R.getFoundDecl();
2867 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2868 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002869 // C++ [namespace.udir]p1:
2870 // A using-directive specifies that the names in the nominated
2871 // namespace can be used in the scope in which the
2872 // using-directive appears after the using-directive. During
2873 // unqualified name lookup (3.4.1), the names appear as if they
2874 // were declared in the nearest enclosing namespace which
2875 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002876 // namespace. [Note: in this context, "contains" means "contains
2877 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002878
2879 // Find enclosing context containing both using-directive and
2880 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002881 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002882 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2883 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2884 CommonAncestor = CommonAncestor->getParent();
2885
Sebastian Redla6602e92009-11-23 15:34:23 +00002886 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002887 SS.getRange(),
2888 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002889 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002890 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002891 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002892 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002893 }
2894
Douglas Gregor889ceb72009-02-03 19:21:40 +00002895 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002896 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002897 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002898}
2899
2900void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2901 // If scope has associated entity, then using directive is at namespace
2902 // or translation unit scope. We add UsingDirectiveDecls, into
2903 // it's lookup structure.
2904 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002905 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002906 else
2907 // Otherwise it is block-sope. using-directives will affect lookup
2908 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002909 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002910}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002911
Douglas Gregorfec52632009-06-20 00:51:54 +00002912
2913Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002914 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00002915 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00002916 SourceLocation UsingLoc,
2917 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002918 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002919 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002920 bool IsTypeName,
2921 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002922 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002923
Douglas Gregor220f4272009-11-04 16:30:06 +00002924 switch (Name.getKind()) {
2925 case UnqualifiedId::IK_Identifier:
2926 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00002927 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00002928 case UnqualifiedId::IK_ConversionFunctionId:
2929 break;
2930
2931 case UnqualifiedId::IK_ConstructorName:
John McCall3969e302009-12-08 07:46:18 +00002932 // C++0x inherited constructors.
2933 if (getLangOptions().CPlusPlus0x) break;
2934
Douglas Gregor220f4272009-11-04 16:30:06 +00002935 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2936 << SS.getRange();
2937 return DeclPtrTy();
2938
2939 case UnqualifiedId::IK_DestructorName:
2940 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2941 << SS.getRange();
2942 return DeclPtrTy();
2943
2944 case UnqualifiedId::IK_TemplateId:
2945 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2946 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2947 return DeclPtrTy();
2948 }
2949
2950 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00002951 if (!TargetName)
2952 return DeclPtrTy();
2953
John McCalla0097262009-12-11 02:10:03 +00002954 // Warn about using declarations.
2955 // TODO: store that the declaration was written without 'using' and
2956 // talk about access decls instead of using decls in the
2957 // diagnostics.
2958 if (!HasUsingKeyword) {
2959 UsingLoc = Name.getSourceRange().getBegin();
2960
2961 Diag(UsingLoc, diag::warn_access_decl_deprecated)
2962 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
2963 "using ");
2964 }
2965
John McCall3f746822009-11-17 05:59:44 +00002966 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002967 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002968 TargetName, AttrList,
2969 /* IsInstantiation */ false,
2970 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00002971 if (UD)
2972 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00002973
Anders Carlsson696a3f12009-08-28 05:40:36 +00002974 return DeclPtrTy::make(UD);
2975}
2976
John McCall84d87672009-12-10 09:41:52 +00002977/// Determines whether to create a using shadow decl for a particular
2978/// decl, given the set of decls existing prior to this using lookup.
2979bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2980 const LookupResult &Previous) {
2981 // Diagnose finding a decl which is not from a base class of the
2982 // current class. We do this now because there are cases where this
2983 // function will silently decide not to build a shadow decl, which
2984 // will pre-empt further diagnostics.
2985 //
2986 // We don't need to do this in C++0x because we do the check once on
2987 // the qualifier.
2988 //
2989 // FIXME: diagnose the following if we care enough:
2990 // struct A { int foo; };
2991 // struct B : A { using A::foo; };
2992 // template <class T> struct C : A {};
2993 // template <class T> struct D : C<T> { using B::foo; } // <---
2994 // This is invalid (during instantiation) in C++03 because B::foo
2995 // resolves to the using decl in B, which is not a base class of D<T>.
2996 // We can't diagnose it immediately because C<T> is an unknown
2997 // specialization. The UsingShadowDecl in D<T> then points directly
2998 // to A::foo, which will look well-formed when we instantiate.
2999 // The right solution is to not collapse the shadow-decl chain.
3000 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3001 DeclContext *OrigDC = Orig->getDeclContext();
3002
3003 // Handle enums and anonymous structs.
3004 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3005 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3006 while (OrigRec->isAnonymousStructOrUnion())
3007 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3008
3009 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3010 if (OrigDC == CurContext) {
3011 Diag(Using->getLocation(),
3012 diag::err_using_decl_nested_name_specifier_is_current_class)
3013 << Using->getNestedNameRange();
3014 Diag(Orig->getLocation(), diag::note_using_decl_target);
3015 return true;
3016 }
3017
3018 Diag(Using->getNestedNameRange().getBegin(),
3019 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3020 << Using->getTargetNestedNameDecl()
3021 << cast<CXXRecordDecl>(CurContext)
3022 << Using->getNestedNameRange();
3023 Diag(Orig->getLocation(), diag::note_using_decl_target);
3024 return true;
3025 }
3026 }
3027
3028 if (Previous.empty()) return false;
3029
3030 NamedDecl *Target = Orig;
3031 if (isa<UsingShadowDecl>(Target))
3032 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3033
John McCalla17e83e2009-12-11 02:33:26 +00003034 // If the target happens to be one of the previous declarations, we
3035 // don't have a conflict.
3036 //
3037 // FIXME: but we might be increasing its access, in which case we
3038 // should redeclare it.
3039 NamedDecl *NonTag = 0, *Tag = 0;
3040 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3041 I != E; ++I) {
3042 NamedDecl *D = (*I)->getUnderlyingDecl();
3043 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3044 return false;
3045
3046 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3047 }
3048
John McCall84d87672009-12-10 09:41:52 +00003049 if (Target->isFunctionOrFunctionTemplate()) {
3050 FunctionDecl *FD;
3051 if (isa<FunctionTemplateDecl>(Target))
3052 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3053 else
3054 FD = cast<FunctionDecl>(Target);
3055
3056 NamedDecl *OldDecl = 0;
3057 switch (CheckOverload(FD, Previous, OldDecl)) {
3058 case Ovl_Overload:
3059 return false;
3060
3061 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003062 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003063 break;
3064
3065 // We found a decl with the exact signature.
3066 case Ovl_Match:
3067 if (isa<UsingShadowDecl>(OldDecl)) {
3068 // Silently ignore the possible conflict.
3069 return false;
3070 }
3071
3072 // If we're in a record, we want to hide the target, so we
3073 // return true (without a diagnostic) to tell the caller not to
3074 // build a shadow decl.
3075 if (CurContext->isRecord())
3076 return true;
3077
3078 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003079 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003080 break;
3081 }
3082
3083 Diag(Target->getLocation(), diag::note_using_decl_target);
3084 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3085 return true;
3086 }
3087
3088 // Target is not a function.
3089
John McCall84d87672009-12-10 09:41:52 +00003090 if (isa<TagDecl>(Target)) {
3091 // No conflict between a tag and a non-tag.
3092 if (!Tag) return false;
3093
John McCalle29c5cd2009-12-10 19:51:03 +00003094 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003095 Diag(Target->getLocation(), diag::note_using_decl_target);
3096 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3097 return true;
3098 }
3099
3100 // No conflict between a tag and a non-tag.
3101 if (!NonTag) return false;
3102
John McCalle29c5cd2009-12-10 19:51:03 +00003103 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003104 Diag(Target->getLocation(), diag::note_using_decl_target);
3105 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3106 return true;
3107}
3108
John McCall3f746822009-11-17 05:59:44 +00003109/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003110UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003111 UsingDecl *UD,
3112 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003113
3114 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003115 NamedDecl *Target = Orig;
3116 if (isa<UsingShadowDecl>(Target)) {
3117 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3118 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003119 }
3120
3121 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003122 = UsingShadowDecl::Create(Context, CurContext,
3123 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003124 UD->addShadowDecl(Shadow);
3125
3126 if (S)
John McCall3969e302009-12-08 07:46:18 +00003127 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003128 else
John McCall3969e302009-12-08 07:46:18 +00003129 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003130 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003131
John McCall3969e302009-12-08 07:46:18 +00003132 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3133 Shadow->setInvalidDecl();
3134
John McCall84d87672009-12-10 09:41:52 +00003135 return Shadow;
3136}
John McCall3969e302009-12-08 07:46:18 +00003137
John McCall84d87672009-12-10 09:41:52 +00003138/// Hides a using shadow declaration. This is required by the current
3139/// using-decl implementation when a resolvable using declaration in a
3140/// class is followed by a declaration which would hide or override
3141/// one or more of the using decl's targets; for example:
3142///
3143/// struct Base { void foo(int); };
3144/// struct Derived : Base {
3145/// using Base::foo;
3146/// void foo(int);
3147/// };
3148///
3149/// The governing language is C++03 [namespace.udecl]p12:
3150///
3151/// When a using-declaration brings names from a base class into a
3152/// derived class scope, member functions in the derived class
3153/// override and/or hide member functions with the same name and
3154/// parameter types in a base class (rather than conflicting).
3155///
3156/// There are two ways to implement this:
3157/// (1) optimistically create shadow decls when they're not hidden
3158/// by existing declarations, or
3159/// (2) don't create any shadow decls (or at least don't make them
3160/// visible) until we've fully parsed/instantiated the class.
3161/// The problem with (1) is that we might have to retroactively remove
3162/// a shadow decl, which requires several O(n) operations because the
3163/// decl structures are (very reasonably) not designed for removal.
3164/// (2) avoids this but is very fiddly and phase-dependent.
3165void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3166 // Remove it from the DeclContext...
3167 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003168
John McCall84d87672009-12-10 09:41:52 +00003169 // ...and the scope, if applicable...
3170 if (S) {
3171 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3172 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003173 }
3174
John McCall84d87672009-12-10 09:41:52 +00003175 // ...and the using decl.
3176 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3177
3178 // TODO: complain somehow if Shadow was used. It shouldn't
3179 // be possible for this to happen, because
John McCall3f746822009-11-17 05:59:44 +00003180}
3181
John McCalle61f2ba2009-11-18 02:36:19 +00003182/// Builds a using declaration.
3183///
3184/// \param IsInstantiation - Whether this call arises from an
3185/// instantiation of an unresolved using declaration. We treat
3186/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003187NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3188 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003189 const CXXScopeSpec &SS,
3190 SourceLocation IdentLoc,
3191 DeclarationName Name,
3192 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003193 bool IsInstantiation,
3194 bool IsTypeName,
3195 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003196 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3197 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003198
Anders Carlssonf038fc22009-08-28 05:49:21 +00003199 // FIXME: We ignore attributes for now.
3200 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003201
Anders Carlsson59140b32009-08-28 03:16:11 +00003202 if (SS.isEmpty()) {
3203 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003204 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003205 }
Mike Stump11289f42009-09-09 15:08:12 +00003206
John McCall84d87672009-12-10 09:41:52 +00003207 // Do the redeclaration lookup in the current scope.
3208 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3209 ForRedeclaration);
3210 Previous.setHideTags(false);
3211 if (S) {
3212 LookupName(Previous, S);
3213
3214 // It is really dumb that we have to do this.
3215 LookupResult::Filter F = Previous.makeFilter();
3216 while (F.hasNext()) {
3217 NamedDecl *D = F.next();
3218 if (!isDeclInScope(D, CurContext, S))
3219 F.erase();
3220 }
3221 F.done();
3222 } else {
3223 assert(IsInstantiation && "no scope in non-instantiation");
3224 assert(CurContext->isRecord() && "scope not record in instantiation");
3225 LookupQualifiedName(Previous, CurContext);
3226 }
3227
Mike Stump11289f42009-09-09 15:08:12 +00003228 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003229 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3230
John McCall84d87672009-12-10 09:41:52 +00003231 // Check for invalid redeclarations.
3232 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3233 return 0;
3234
3235 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003236 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3237 return 0;
3238
John McCall84c16cf2009-11-12 03:15:40 +00003239 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003240 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003241 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003242 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003243 // FIXME: not all declaration name kinds are legal here
3244 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3245 UsingLoc, TypenameLoc,
3246 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003247 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003248 } else {
3249 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3250 UsingLoc, SS.getRange(), NNS,
3251 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003252 }
John McCallb96ec562009-12-04 22:46:56 +00003253 } else {
3254 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3255 SS.getRange(), UsingLoc, NNS, Name,
3256 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003257 }
John McCallb96ec562009-12-04 22:46:56 +00003258 D->setAccess(AS);
3259 CurContext->addDecl(D);
3260
3261 if (!LookupContext) return D;
3262 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003263
John McCall3969e302009-12-08 07:46:18 +00003264 if (RequireCompleteDeclContext(SS)) {
3265 UD->setInvalidDecl();
3266 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003267 }
3268
John McCall3969e302009-12-08 07:46:18 +00003269 // Look up the target name.
3270
John McCall27b18f82009-11-17 02:14:36 +00003271 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003272
John McCall3969e302009-12-08 07:46:18 +00003273 // Unlike most lookups, we don't always want to hide tag
3274 // declarations: tag names are visible through the using declaration
3275 // even if hidden by ordinary names, *except* in a dependent context
3276 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003277 if (!IsInstantiation)
3278 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003279
John McCall27b18f82009-11-17 02:14:36 +00003280 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003281
John McCall9f3059a2009-10-09 21:13:30 +00003282 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003283 Diag(IdentLoc, diag::err_no_member)
3284 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003285 UD->setInvalidDecl();
3286 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003287 }
3288
John McCallb96ec562009-12-04 22:46:56 +00003289 if (R.isAmbiguous()) {
3290 UD->setInvalidDecl();
3291 return UD;
3292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
John McCalle61f2ba2009-11-18 02:36:19 +00003294 if (IsTypeName) {
3295 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003296 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003297 Diag(IdentLoc, diag::err_using_typename_non_type);
3298 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3299 Diag((*I)->getUnderlyingDecl()->getLocation(),
3300 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003301 UD->setInvalidDecl();
3302 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003303 }
3304 } else {
3305 // If we asked for a non-typename and we got a type, error out,
3306 // but only if this is an instantiation of an unresolved using
3307 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003308 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003309 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3310 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003311 UD->setInvalidDecl();
3312 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003313 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003314 }
3315
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003316 // C++0x N2914 [namespace.udecl]p6:
3317 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003318 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003319 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3320 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003321 UD->setInvalidDecl();
3322 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003323 }
Mike Stump11289f42009-09-09 15:08:12 +00003324
John McCall84d87672009-12-10 09:41:52 +00003325 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3326 if (!CheckUsingShadowDecl(UD, *I, Previous))
3327 BuildUsingShadowDecl(S, UD, *I);
3328 }
John McCall3f746822009-11-17 05:59:44 +00003329
3330 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003331}
3332
John McCall84d87672009-12-10 09:41:52 +00003333/// Checks that the given using declaration is not an invalid
3334/// redeclaration. Note that this is checking only for the using decl
3335/// itself, not for any ill-formedness among the UsingShadowDecls.
3336bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3337 bool isTypeName,
3338 const CXXScopeSpec &SS,
3339 SourceLocation NameLoc,
3340 const LookupResult &Prev) {
3341 // C++03 [namespace.udecl]p8:
3342 // C++0x [namespace.udecl]p10:
3343 // A using-declaration is a declaration and can therefore be used
3344 // repeatedly where (and only where) multiple declarations are
3345 // allowed.
3346 // That's only in file contexts.
3347 if (CurContext->getLookupContext()->isFileContext())
3348 return false;
3349
3350 NestedNameSpecifier *Qual
3351 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3352
3353 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3354 NamedDecl *D = *I;
3355
3356 bool DTypename;
3357 NestedNameSpecifier *DQual;
3358 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3359 DTypename = UD->isTypeName();
3360 DQual = UD->getTargetNestedNameDecl();
3361 } else if (UnresolvedUsingValueDecl *UD
3362 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3363 DTypename = false;
3364 DQual = UD->getTargetNestedNameSpecifier();
3365 } else if (UnresolvedUsingTypenameDecl *UD
3366 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3367 DTypename = true;
3368 DQual = UD->getTargetNestedNameSpecifier();
3369 } else continue;
3370
3371 // using decls differ if one says 'typename' and the other doesn't.
3372 // FIXME: non-dependent using decls?
3373 if (isTypeName != DTypename) continue;
3374
3375 // using decls differ if they name different scopes (but note that
3376 // template instantiation can cause this check to trigger when it
3377 // didn't before instantiation).
3378 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3379 Context.getCanonicalNestedNameSpecifier(DQual))
3380 continue;
3381
3382 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003383 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003384 return true;
3385 }
3386
3387 return false;
3388}
3389
John McCall3969e302009-12-08 07:46:18 +00003390
John McCallb96ec562009-12-04 22:46:56 +00003391/// Checks that the given nested-name qualifier used in a using decl
3392/// in the current context is appropriately related to the current
3393/// scope. If an error is found, diagnoses it and returns true.
3394bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3395 const CXXScopeSpec &SS,
3396 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003397 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003398
John McCall3969e302009-12-08 07:46:18 +00003399 if (!CurContext->isRecord()) {
3400 // C++03 [namespace.udecl]p3:
3401 // C++0x [namespace.udecl]p8:
3402 // A using-declaration for a class member shall be a member-declaration.
3403
3404 // If we weren't able to compute a valid scope, it must be a
3405 // dependent class scope.
3406 if (!NamedContext || NamedContext->isRecord()) {
3407 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3408 << SS.getRange();
3409 return true;
3410 }
3411
3412 // Otherwise, everything is known to be fine.
3413 return false;
3414 }
3415
3416 // The current scope is a record.
3417
3418 // If the named context is dependent, we can't decide much.
3419 if (!NamedContext) {
3420 // FIXME: in C++0x, we can diagnose if we can prove that the
3421 // nested-name-specifier does not refer to a base class, which is
3422 // still possible in some cases.
3423
3424 // Otherwise we have to conservatively report that things might be
3425 // okay.
3426 return false;
3427 }
3428
3429 if (!NamedContext->isRecord()) {
3430 // Ideally this would point at the last name in the specifier,
3431 // but we don't have that level of source info.
3432 Diag(SS.getRange().getBegin(),
3433 diag::err_using_decl_nested_name_specifier_is_not_class)
3434 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3435 return true;
3436 }
3437
3438 if (getLangOptions().CPlusPlus0x) {
3439 // C++0x [namespace.udecl]p3:
3440 // In a using-declaration used as a member-declaration, the
3441 // nested-name-specifier shall name a base class of the class
3442 // being defined.
3443
3444 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3445 cast<CXXRecordDecl>(NamedContext))) {
3446 if (CurContext == NamedContext) {
3447 Diag(NameLoc,
3448 diag::err_using_decl_nested_name_specifier_is_current_class)
3449 << SS.getRange();
3450 return true;
3451 }
3452
3453 Diag(SS.getRange().getBegin(),
3454 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3455 << (NestedNameSpecifier*) SS.getScopeRep()
3456 << cast<CXXRecordDecl>(CurContext)
3457 << SS.getRange();
3458 return true;
3459 }
3460
3461 return false;
3462 }
3463
3464 // C++03 [namespace.udecl]p4:
3465 // A using-declaration used as a member-declaration shall refer
3466 // to a member of a base class of the class being defined [etc.].
3467
3468 // Salient point: SS doesn't have to name a base class as long as
3469 // lookup only finds members from base classes. Therefore we can
3470 // diagnose here only if we can prove that that can't happen,
3471 // i.e. if the class hierarchies provably don't intersect.
3472
3473 // TODO: it would be nice if "definitely valid" results were cached
3474 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3475 // need to be repeated.
3476
3477 struct UserData {
3478 llvm::DenseSet<const CXXRecordDecl*> Bases;
3479
3480 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3481 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3482 Data->Bases.insert(Base);
3483 return true;
3484 }
3485
3486 bool hasDependentBases(const CXXRecordDecl *Class) {
3487 return !Class->forallBases(collect, this);
3488 }
3489
3490 /// Returns true if the base is dependent or is one of the
3491 /// accumulated base classes.
3492 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3493 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3494 return !Data->Bases.count(Base);
3495 }
3496
3497 bool mightShareBases(const CXXRecordDecl *Class) {
3498 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3499 }
3500 };
3501
3502 UserData Data;
3503
3504 // Returns false if we find a dependent base.
3505 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3506 return false;
3507
3508 // Returns false if the class has a dependent base or if it or one
3509 // of its bases is present in the base set of the current context.
3510 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3511 return false;
3512
3513 Diag(SS.getRange().getBegin(),
3514 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3515 << (NestedNameSpecifier*) SS.getScopeRep()
3516 << cast<CXXRecordDecl>(CurContext)
3517 << SS.getRange();
3518
3519 return true;
John McCallb96ec562009-12-04 22:46:56 +00003520}
3521
Mike Stump11289f42009-09-09 15:08:12 +00003522Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003523 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003524 SourceLocation AliasLoc,
3525 IdentifierInfo *Alias,
3526 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003527 SourceLocation IdentLoc,
3528 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003529
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003530 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003531 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3532 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003533
Anders Carlssondca83c42009-03-28 06:23:46 +00003534 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003535 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003536 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003537 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003538 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003539 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003540 if (!R.isAmbiguous() && !R.empty() &&
3541 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003542 return DeclPtrTy();
3543 }
Mike Stump11289f42009-09-09 15:08:12 +00003544
Anders Carlssondca83c42009-03-28 06:23:46 +00003545 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3546 diag::err_redefinition_different_kind;
3547 Diag(AliasLoc, DiagID) << Alias;
3548 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003549 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003550 }
3551
John McCall27b18f82009-11-17 02:14:36 +00003552 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003553 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003554
John McCall9f3059a2009-10-09 21:13:30 +00003555 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003556 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003557 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003558 }
Mike Stump11289f42009-09-09 15:08:12 +00003559
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003560 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003561 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3562 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003563 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003564 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003565
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003566 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003567 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003568}
3569
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003570void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3571 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003572 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3573 !Constructor->isUsed()) &&
3574 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003575
Eli Friedman9cf6b592009-11-09 19:20:36 +00003576 CXXRecordDecl *ClassDecl
3577 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3578 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003579
Eli Friedman9cf6b592009-11-09 19:20:36 +00003580 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003581 Diag(CurrentLocation, diag::note_member_synthesized_at)
3582 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003583 Constructor->setInvalidDecl();
3584 } else {
3585 Constructor->setUsed();
3586 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003587}
3588
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003589void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003590 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003591 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3592 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003593 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003594 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3595 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003596 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003597 // implicitly defined, all the implicitly-declared default destructors
3598 // for its base class and its non-static data members shall have been
3599 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003600 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3601 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003602 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003603 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003604 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003605 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003606 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3607 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3608 else
Mike Stump11289f42009-09-09 15:08:12 +00003609 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003610 "DefineImplicitDestructor - missing dtor in a base class");
3611 }
3612 }
Mike Stump11289f42009-09-09 15:08:12 +00003613
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003614 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3615 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003616 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3617 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3618 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003619 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003620 CXXRecordDecl *FieldClassDecl
3621 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3622 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003623 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003624 const_cast<CXXDestructorDecl*>(
3625 FieldClassDecl->getDestructor(Context)))
3626 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3627 else
Mike Stump11289f42009-09-09 15:08:12 +00003628 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003629 "DefineImplicitDestructor - missing dtor in class of a data member");
3630 }
3631 }
3632 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003633
3634 // FIXME: If CheckDestructor fails, we should emit a note about where the
3635 // implicit destructor was needed.
3636 if (CheckDestructor(Destructor)) {
3637 Diag(CurrentLocation, diag::note_member_synthesized_at)
3638 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3639
3640 Destructor->setInvalidDecl();
3641 return;
3642 }
3643
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003644 Destructor->setUsed();
3645}
3646
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003647void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3648 CXXMethodDecl *MethodDecl) {
3649 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3650 MethodDecl->getOverloadedOperator() == OO_Equal &&
3651 !MethodDecl->isUsed()) &&
3652 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003653
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003654 CXXRecordDecl *ClassDecl
3655 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003656
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003657 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003658 // Before the implicitly-declared copy assignment operator for a class is
3659 // implicitly defined, all implicitly-declared copy assignment operators
3660 // for its direct base classes and its nonstatic data members shall have
3661 // been implicitly defined.
3662 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003663 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3664 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003665 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003666 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003667 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003668 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3669 BaseClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003670 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3671 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003672 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3673 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003674 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3675 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3676 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003677 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003678 CXXRecordDecl *FieldClassDecl
3679 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003680 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonefa47322009-12-09 03:01:51 +00003681 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3682 FieldClassDecl))
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003683 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003684 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003685 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003686 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3687 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003688 Diag(CurrentLocation, diag::note_first_required_here);
3689 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003690 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003691 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003692 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3693 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003694 Diag(CurrentLocation, diag::note_first_required_here);
3695 err = true;
3696 }
3697 }
3698 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003699 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003700}
3701
3702CXXMethodDecl *
Anders Carlssonefa47322009-12-09 03:01:51 +00003703Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3704 ParmVarDecl *ParmDecl,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003705 CXXRecordDecl *ClassDecl) {
3706 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3707 QualType RHSType(LHSType);
3708 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003709 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003710 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003711 RHSType = Context.getCVRQualifiedType(RHSType,
3712 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003713 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003714 LHSType,
3715 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003716 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonefa47322009-12-09 03:01:51 +00003717 RHSType,
3718 CurrentLocation));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003719 Expr *Args[2] = { &*LHS, &*RHS };
3720 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003721 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003722 CandidateSet);
3723 OverloadCandidateSet::iterator Best;
Anders Carlssonefa47322009-12-09 03:01:51 +00003724 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003725 return cast<CXXMethodDecl>(Best->Function);
3726 assert(false &&
3727 "getAssignOperatorMethod - copy assignment operator method not found");
3728 return 0;
3729}
3730
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003731void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3732 CXXConstructorDecl *CopyConstructor,
3733 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003734 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00003735 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003736 !CopyConstructor->isUsed()) &&
3737 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003738
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003739 CXXRecordDecl *ClassDecl
3740 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3741 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003742 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003743 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003744 // implicitly defined, all the implicitly-declared copy constructors
3745 // for its base class and its non-static data members shall have been
3746 // implicitly defined.
3747 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3748 Base != ClassDecl->bases_end(); ++Base) {
3749 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003750 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003751 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003752 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003753 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003754 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003755 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3756 FieldEnd = ClassDecl->field_end();
3757 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003758 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3759 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3760 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003761 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003762 CXXRecordDecl *FieldClassDecl
3763 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003764 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003765 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003766 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003767 }
3768 }
3769 CopyConstructor->setUsed();
3770}
3771
Anders Carlsson6eb55572009-08-25 05:12:04 +00003772Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003773Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003774 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003775 MultiExprArg ExprArgs,
3776 bool RequiresZeroInit) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003777 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003778
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003779 // C++ [class.copy]p15:
3780 // Whenever a temporary class object is copied using a copy constructor, and
3781 // this object and the copy have the same cv-unqualified type, an
3782 // implementation is permitted to treat the original and the copy as two
3783 // different ways of referring to the same object and not perform a copy at
3784 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003785
Anders Carlsson250aada2009-08-16 05:13:48 +00003786 // FIXME: Is this enough?
Douglas Gregor507eb872009-12-22 00:34:07 +00003787 if (Constructor->isCopyConstructor()) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003788 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregore1314a62009-12-18 05:02:21 +00003789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3790 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3791 E = ICE->getSubExpr();
Anders Carlsson250aada2009-08-16 05:13:48 +00003792 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3793 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003794 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3795 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3796 E = ICE->getSubExpr();
Eli Friedmaneddf1212009-12-06 09:26:33 +00003797
3798 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3799 Elidable = !CE->getCallReturnType()->isReferenceType();
3800 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson250aada2009-08-16 05:13:48 +00003801 Elidable = true;
3802 }
Mike Stump11289f42009-09-09 15:08:12 +00003803
3804 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003805 Elidable, move(ExprArgs), RequiresZeroInit);
Anders Carlsson250aada2009-08-16 05:13:48 +00003806}
3807
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003808/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3809/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003810Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003811Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3812 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003813 MultiExprArg ExprArgs,
3814 bool RequiresZeroInit) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003815 unsigned NumExprs = ExprArgs.size();
3816 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003817
Douglas Gregor27381f32009-11-23 12:27:39 +00003818 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003819 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003820 Constructor, Elidable, Exprs, NumExprs,
3821 RequiresZeroInit));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003822}
3823
Anders Carlsson574315a2009-08-27 05:08:22 +00003824Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003825Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3826 QualType Ty,
3827 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003828 MultiExprArg Args,
3829 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003830 unsigned NumExprs = Args.size();
3831 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003832
Douglas Gregor27381f32009-11-23 12:27:39 +00003833 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003834 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3835 TyBeginLoc, Exprs,
3836 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003837}
3838
3839
Mike Stump11289f42009-09-09 15:08:12 +00003840bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003841 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003842 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003843 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003844 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003845 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003846 if (TempResult.isInvalid())
3847 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003848
Anders Carlsson6eb55572009-08-25 05:12:04 +00003849 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003850 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00003851 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003852 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003853
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003854 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003855}
3856
Mike Stump11289f42009-09-09 15:08:12 +00003857void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003858 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003859 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003860 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003861 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003862 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003863 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003864}
3865
Mike Stump11289f42009-09-09 15:08:12 +00003866/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003867/// ActOnDeclarator, when a C++ direct initializer is present.
3868/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003869void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3870 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003871 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003872 SourceLocation *CommaLocs,
3873 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003874 unsigned NumExprs = Exprs.size();
3875 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003876 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003877
3878 // If there is no declaration, there was an error parsing it. Just ignore
3879 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003880 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003881 return;
Mike Stump11289f42009-09-09 15:08:12 +00003882
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003883 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3884 if (!VDecl) {
3885 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3886 RealDecl->setInvalidDecl();
3887 return;
3888 }
3889
Douglas Gregor402250f2009-08-26 21:14:46 +00003890 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003891 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003892 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3893 //
3894 // Clients that want to distinguish between the two forms, can check for
3895 // direct initializer using VarDecl::hasCXXDirectInitializer().
3896 // A major benefit is that clients that don't particularly care about which
3897 // exactly form was it (like the CodeGen) can handle both cases without
3898 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003899
Douglas Gregor402250f2009-08-26 21:14:46 +00003900 // If either the declaration has a dependent type or if any of the expressions
3901 // is type-dependent, we represent the initialization via a ParenListExpr for
3902 // later use during template instantiation.
3903 if (VDecl->getType()->isDependentType() ||
3904 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3905 // Let clients know that initialization was done with a direct initializer.
3906 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003907
Douglas Gregor402250f2009-08-26 21:14:46 +00003908 // Store the initialization expressions as a ParenListExpr.
3909 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003910 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003911 new (Context) ParenListExpr(Context, LParenLoc,
3912 (Expr **)Exprs.release(),
3913 NumExprs, RParenLoc));
3914 return;
3915 }
Mike Stump11289f42009-09-09 15:08:12 +00003916
Douglas Gregor402250f2009-08-26 21:14:46 +00003917
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003918 // C++ 8.5p11:
3919 // The form of initialization (using parentheses or '=') is generally
3920 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003921 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003922 QualType DeclInitType = VDecl->getType();
3923 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003924 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003925
Douglas Gregor4044d992009-03-24 16:43:20 +00003926 // FIXME: This isn't the right place to complete the type.
3927 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3928 diag::err_typecheck_decl_incomplete_type)) {
3929 VDecl->setInvalidDecl();
3930 return;
3931 }
3932
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003933 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003934 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3935
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003936 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003937 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003938 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003939 VDecl->getLocation(),
3940 SourceRange(VDecl->getLocation(),
3941 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003942 VDecl->getDeclName(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003943 InitializationKind::CreateDirect(VDecl->getLocation(),
3944 LParenLoc,
3945 RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003946 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003947 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003948 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003949 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003950 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003951 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003952 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003953 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003954 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003955 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003956 return;
3957 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003958
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003959 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003960 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3961 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003962 RealDecl->setInvalidDecl();
3963 return;
3964 }
3965
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003966 // Let clients know that initialization was done with a direct initializer.
3967 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003968
3969 assert(NumExprs == 1 && "Expected 1 expression");
3970 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003971 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3972 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003973}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003974
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003975/// \brief Add the applicable constructor candidates for an initialization
3976/// by constructor.
3977static void AddConstructorInitializationCandidates(Sema &SemaRef,
3978 QualType ClassType,
3979 Expr **Args,
3980 unsigned NumArgs,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003981 InitializationKind Kind,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003982 OverloadCandidateSet &CandidateSet) {
3983 // C++ [dcl.init]p14:
3984 // If the initialization is direct-initialization, or if it is
3985 // copy-initialization where the cv-unqualified version of the
3986 // source type is the same class as, or a derived class of, the
3987 // class of the destination, constructors are considered. The
3988 // applicable constructors are enumerated (13.3.1.3), and the
3989 // best one is chosen through overload resolution (13.3). The
3990 // constructor so selected is called to initialize the object,
3991 // with the initializer expression(s) as its argument(s). If no
3992 // constructor applies, or the overload resolution is ambiguous,
3993 // the initialization is ill-formed.
3994 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3995 assert(ClassRec && "Can only initialize a class type here");
3996
3997 // FIXME: When we decide not to synthesize the implicitly-declared
3998 // constructors, we'll need to make them appear here.
3999
4000 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4001 DeclarationName ConstructorName
4002 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4003 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4004 DeclContext::lookup_const_iterator Con, ConEnd;
4005 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4006 Con != ConEnd; ++Con) {
4007 // Find the constructor (which may be a template).
4008 CXXConstructorDecl *Constructor = 0;
4009 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4010 if (ConstructorTmpl)
4011 Constructor
4012 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4013 else
4014 Constructor = cast<CXXConstructorDecl>(*Con);
4015
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004016 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4017 (Kind.getKind() == InitializationKind::IK_Value) ||
4018 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004019 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004020 ((Kind.getKind() == InitializationKind::IK_Default) &&
4021 Constructor->isDefaultConstructor())) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004022 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00004023 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4024 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004025 Args, NumArgs, CandidateSet);
4026 else
4027 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
4028 }
4029 }
4030}
4031
4032/// \brief Attempt to perform initialization by constructor
4033/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4034/// copy-initialization.
4035///
4036/// This routine determines whether initialization by constructor is possible,
4037/// but it does not emit any diagnostics in the case where the initialization
4038/// is ill-formed.
4039///
4040/// \param ClassType the type of the object being initialized, which must have
4041/// class type.
4042///
4043/// \param Args the arguments provided to initialize the object
4044///
4045/// \param NumArgs the number of arguments provided to initialize the object
4046///
4047/// \param Kind the type of initialization being performed
4048///
4049/// \returns the constructor used to initialize the object, if successful.
4050/// Otherwise, emits a diagnostic and returns NULL.
4051CXXConstructorDecl *
4052Sema::TryInitializationByConstructor(QualType ClassType,
4053 Expr **Args, unsigned NumArgs,
4054 SourceLocation Loc,
4055 InitializationKind Kind) {
4056 // Build the overload candidate set
4057 OverloadCandidateSet CandidateSet;
4058 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4059 CandidateSet);
4060
4061 // Determine whether we found a constructor we can use.
4062 OverloadCandidateSet::iterator Best;
4063 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4064 case OR_Success:
4065 case OR_Deleted:
4066 // We found a constructor. Return it.
4067 return cast<CXXConstructorDecl>(Best->Function);
4068
4069 case OR_No_Viable_Function:
4070 case OR_Ambiguous:
4071 // Overload resolution failed. Return nothing.
4072 return 0;
4073 }
4074
4075 // Silence GCC warning
4076 return 0;
4077}
4078
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004079/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4080/// may occur as part of direct-initialization or copy-initialization.
4081///
4082/// \param ClassType the type of the object being initialized, which must have
4083/// class type.
4084///
4085/// \param ArgsPtr the arguments provided to initialize the object
4086///
4087/// \param Loc the source location where the initialization occurs
4088///
4089/// \param Range the source range that covers the entire initialization
4090///
4091/// \param InitEntity the name of the entity being initialized, if known
4092///
4093/// \param Kind the type of initialization being performed
4094///
4095/// \param ConvertedArgs a vector that will be filled in with the
4096/// appropriately-converted arguments to the constructor (if initialization
4097/// succeeded).
4098///
4099/// \returns the constructor used to initialize the object, if successful.
4100/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004101CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00004102Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004103 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00004104 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004105 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004106 InitializationKind Kind,
4107 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004108
4109 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004110 Expr **Args = (Expr **)ArgsPtr.get();
4111 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004112 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00004113 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4114 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00004115
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004116 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004117 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004118 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004119 // We found a constructor. Break out so that we can convert the arguments
4120 // appropriately.
4121 break;
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004123 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00004124 if (InitEntity)
4125 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00004126 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00004127 else
4128 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00004129 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00004130 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004131 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004132
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004133 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00004134 if (InitEntity)
4135 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4136 else
4137 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004138 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4139 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004140
4141 case OR_Deleted:
4142 if (InitEntity)
4143 Diag(Loc, diag::err_ovl_deleted_init)
4144 << Best->Function->isDeleted()
4145 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00004146 else {
4147 const CXXRecordDecl *RD =
4148 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004149 Diag(Loc, diag::err_ovl_deleted_init)
4150 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00004151 << RD->getDeclName() << Range;
4152 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00004153 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4154 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004155 }
Mike Stump11289f42009-09-09 15:08:12 +00004156
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004157 // Convert the arguments, fill in default arguments, etc.
4158 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4159 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4160 return 0;
4161
4162 return Constructor;
4163}
4164
4165/// \brief Given a constructor and the set of arguments provided for the
4166/// constructor, convert the arguments and add any required default arguments
4167/// to form a proper call to this constructor.
4168///
4169/// \returns true if an error occurred, false otherwise.
4170bool
4171Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4172 MultiExprArg ArgsPtr,
4173 SourceLocation Loc,
4174 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4175 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4176 unsigned NumArgs = ArgsPtr.size();
4177 Expr **Args = (Expr **)ArgsPtr.get();
4178
4179 const FunctionProtoType *Proto
4180 = Constructor->getType()->getAs<FunctionProtoType>();
4181 assert(Proto && "Constructor without a prototype?");
4182 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004183
4184 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004185 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004186 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004187 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004188 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004189
4190 VariadicCallType CallType =
4191 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4192 llvm::SmallVector<Expr *, 8> AllArgs;
4193 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4194 Proto, 0, Args, NumArgs, AllArgs,
4195 CallType);
4196 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4197 ConvertedArgs.push_back(AllArgs[i]);
4198 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004199}
4200
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004201/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4202/// determine whether they are reference-related,
4203/// reference-compatible, reference-compatible with added
4204/// qualification, or incompatible, for use in C++ initialization by
4205/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4206/// type, and the first type (T1) is the pointee type of the reference
4207/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00004208Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004209Sema::CompareReferenceRelationship(SourceLocation Loc,
4210 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00004211 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004212 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004213 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004214 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004215
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004216 QualType T1 = Context.getCanonicalType(OrigT1);
4217 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004218 QualType UnqualT1 = T1.getLocalUnqualifiedType();
4219 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004220
4221 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004222 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00004223 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004224 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00004225 if (UnqualT1 == UnqualT2)
4226 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004227 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4228 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4229 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00004230 DerivedToBase = true;
4231 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004232 return Ref_Incompatible;
4233
4234 // At this point, we know that T1 and T2 are reference-related (at
4235 // least).
4236
4237 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004238 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004239 // reference-related to T2 and cv1 is the same cv-qualification
4240 // as, or greater cv-qualification than, cv2. For purposes of
4241 // overload resolution, cases for which cv1 is greater
4242 // cv-qualification than cv2 are identified as
4243 // reference-compatible with added qualification (see 13.3.3.2).
4244 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
4245 return Ref_Compatible;
4246 else if (T1.isMoreQualifiedThan(T2))
4247 return Ref_Compatible_With_Added_Qualification;
4248 else
4249 return Ref_Related;
4250}
4251
4252/// CheckReferenceInit - Check the initialization of a reference
4253/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4254/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00004255/// list), and DeclType is the type of the declaration. When ICS is
4256/// non-null, this routine will compute the implicit conversion
4257/// sequence according to C++ [over.ics.ref] and will not produce any
4258/// diagnostics; when ICS is null, it will emit diagnostics when any
4259/// errors are found. Either way, a return value of true indicates
4260/// that there was a failure, a return value of false indicates that
4261/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00004262///
4263/// When @p SuppressUserConversions, user-defined conversions are
4264/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004265/// When @p AllowExplicit, we also permit explicit user-defined
4266/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00004267/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00004268/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4269/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00004270bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00004271Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00004272 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004273 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00004274 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00004275 ImplicitConversionSequence *ICS,
4276 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004277 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4278
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004279 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004280 QualType T2 = Init->getType();
4281
Douglas Gregorcd695e52008-11-10 20:40:00 +00004282 // If the initializer is the address of an overloaded function, try
4283 // to resolve the overloaded function. If all goes well, T2 is the
4284 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004285 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00004286 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004287 ICS != 0);
4288 if (Fn) {
4289 // Since we're performing this reference-initialization for
4290 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004291 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00004292 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004294
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00004295 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004296 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004297
4298 T2 = Fn->getType();
4299 }
4300 }
4301
Douglas Gregor786ab212008-10-29 02:00:59 +00004302 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004303 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00004304 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00004305 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4306 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00004307 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00004308 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00004309
4310 // Most paths end in a failed conversion.
4311 if (ICS)
4312 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004313
4314 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00004315 // A reference to type "cv1 T1" is initialized by an expression
4316 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004317
4318 // -- If the initializer expression
4319
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004320 // Rvalue references cannot bind to lvalues (N2812).
4321 // There is absolutely no situation where they can. In particular, note that
4322 // this is ill-formed, even if B has a user-defined conversion to A&&:
4323 // B b;
4324 // A&& r = b;
4325 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4326 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004327 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004328 << Init->getSourceRange();
4329 return true;
4330 }
4331
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004332 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00004333 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4334 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00004335 //
4336 // Note that the bit-field check is skipped if we are just computing
4337 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00004338 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004339 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004340 BindsDirectly = true;
4341
Douglas Gregor786ab212008-10-29 02:00:59 +00004342 if (ICS) {
4343 // C++ [over.ics.ref]p1:
4344 // When a parameter of reference type binds directly (8.5.3)
4345 // to an argument expression, the implicit conversion sequence
4346 // is the identity conversion, unless the argument expression
4347 // has a type that is a derived class of the parameter type,
4348 // in which case the implicit conversion sequence is a
4349 // derived-to-base Conversion (13.3.3.1).
4350 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4351 ICS->Standard.First = ICK_Identity;
4352 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4353 ICS->Standard.Third = ICK_Identity;
4354 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4355 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004356 ICS->Standard.ReferenceBinding = true;
4357 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004358 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004359 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004360
4361 // Nothing more to do: the inaccessibility/ambiguity check for
4362 // derived-to-base conversions is suppressed when we're
4363 // computing the implicit conversion sequence (C++
4364 // [over.best.ics]p2).
4365 return false;
4366 } else {
4367 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004368 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4369 if (DerivedToBase)
4370 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004371 else if(CheckExceptionSpecCompatibility(Init, T1))
4372 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004373 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004374 }
4375 }
4376
4377 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00004378 // implicitly converted to an lvalue of type "cv3 T3,"
4379 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004380 // 92) (this conversion is selected by enumerating the
4381 // applicable conversion functions (13.3.1.6) and choosing
4382 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004383 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004384 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00004385 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004386 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004387
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004388 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00004389 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004390 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00004391 for (UnresolvedSet::iterator I = Conversions->begin(),
4392 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00004393 NamedDecl *D = *I;
4394 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4395 if (isa<UsingShadowDecl>(D))
4396 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4397
Mike Stump11289f42009-09-09 15:08:12 +00004398 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00004399 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00004400 CXXConversionDecl *Conv;
4401 if (ConvTemplate)
4402 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4403 else
John McCall6e9f8f62009-12-03 04:06:58 +00004404 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004405
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004406 // If the conversion function doesn't return a reference type,
4407 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004408 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00004409 (AllowExplicit || !Conv->isExplicit())) {
4410 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00004411 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4412 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004413 else
John McCall6e9f8f62009-12-03 04:06:58 +00004414 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004415 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004416 }
4417
4418 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00004419 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004420 case OR_Success:
4421 // This is a direct binding.
4422 BindsDirectly = true;
4423
4424 if (ICS) {
4425 // C++ [over.ics.ref]p1:
4426 //
4427 // [...] If the parameter binds directly to the result of
4428 // applying a conversion function to the argument
4429 // expression, the implicit conversion sequence is a
4430 // user-defined conversion sequence (13.3.3.1.2), with the
4431 // second standard conversion sequence either an identity
4432 // conversion or, if the conversion function returns an
4433 // entity of a type that is a derived class of the parameter
4434 // type, a derived-to-base Conversion.
4435 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4436 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4437 ICS->UserDefined.After = Best->FinalConversion;
4438 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004439 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004440 assert(ICS->UserDefined.After.ReferenceBinding &&
4441 ICS->UserDefined.After.DirectBinding &&
4442 "Expected a direct reference binding!");
4443 return false;
4444 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004445 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00004446 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004447 CastExpr::CK_UserDefinedConversion,
4448 cast<CXXMethodDecl>(Best->Function),
4449 Owned(Init));
4450 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00004451
4452 if (CheckExceptionSpecCompatibility(Init, T1))
4453 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00004454 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4455 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004456 }
4457 break;
4458
4459 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00004460 if (ICS) {
4461 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4462 Cand != CandidateSet.end(); ++Cand)
4463 if (Cand->Viable)
4464 ICS->ConversionFunctionSet.push_back(Cand->Function);
4465 break;
4466 }
4467 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4468 << Init->getSourceRange();
4469 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004470 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004472 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004473 case OR_Deleted:
4474 // There was no suitable conversion, or we found a deleted
4475 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004476 break;
4477 }
4478 }
Mike Stump11289f42009-09-09 15:08:12 +00004479
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004480 if (BindsDirectly) {
4481 // C++ [dcl.init.ref]p4:
4482 // [...] In all cases where the reference-related or
4483 // reference-compatible relationship of two types is used to
4484 // establish the validity of a reference binding, and T1 is a
4485 // base class of T2, a program that necessitates such a binding
4486 // is ill-formed if T1 is an inaccessible (clause 11) or
4487 // ambiguous (10.2) base class of T2.
4488 //
4489 // Note that we only check this condition when we're allowed to
4490 // complain about errors, because we should not be checking for
4491 // ambiguity (or inaccessibility) unless the reference binding
4492 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004493 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004494 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004495 Init->getSourceRange(),
4496 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004497 else
4498 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004499 }
4500
4501 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004502 // type (i.e., cv1 shall be const), or the reference shall be an
4503 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004504 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004505 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004506 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregor906db8a2009-12-15 16:44:32 +00004507 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004508 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004509 return true;
4510 }
4511
4512 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004513 // class type, and "cv1 T1" is reference-compatible with
4514 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004515 // following ways (the choice is implementation-defined):
4516 //
4517 // -- The reference is bound to the object represented by
4518 // the rvalue (see 3.10) or to a sub-object within that
4519 // object.
4520 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004521 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004522 // a constructor is called to copy the entire rvalue
4523 // object into the temporary. The reference is bound to
4524 // the temporary or to a sub-object within the
4525 // temporary.
4526 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004527 // The constructor that would be used to make the copy
4528 // shall be callable whether or not the copy is actually
4529 // done.
4530 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004531 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004532 // freedom, so we will always take the first option and never build
4533 // a temporary in this case. FIXME: We will, however, have to check
4534 // for the presence of a copy constructor in C++98/03 mode.
4535 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004536 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4537 if (ICS) {
4538 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4539 ICS->Standard.First = ICK_Identity;
4540 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4541 ICS->Standard.Third = ICK_Identity;
4542 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4543 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004544 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004545 ICS->Standard.DirectBinding = false;
4546 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004547 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004548 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004549 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4550 if (DerivedToBase)
4551 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004552 else if(CheckExceptionSpecCompatibility(Init, T1))
4553 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004554 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004555 }
4556 return false;
4557 }
4558
Eli Friedman44b83ee2009-08-05 19:21:58 +00004559 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004560 // initialized from the initializer expression using the
4561 // rules for a non-reference copy initialization (8.5). The
4562 // reference is then bound to the temporary. If T1 is
4563 // reference-related to T2, cv1 must be the same
4564 // cv-qualification as, or greater cv-qualification than,
4565 // cv2; otherwise, the program is ill-formed.
4566 if (RefRelationship == Ref_Related) {
4567 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4568 // we would be reference-compatible or reference-compatible with
4569 // added qualification. But that wasn't the case, so the reference
4570 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004571 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004572 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor906db8a2009-12-15 16:44:32 +00004573 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004574 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004575 return true;
4576 }
4577
Douglas Gregor576e98c2009-01-30 23:27:23 +00004578 // If at least one of the types is a class type, the types are not
4579 // related, and we aren't allowed any user conversions, the
4580 // reference binding fails. This case is important for breaking
4581 // recursion, since TryImplicitConversion below will attempt to
4582 // create a temporary through the use of a copy constructor.
4583 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4584 (T1->isRecordType() || T2->isRecordType())) {
4585 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004586 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004587 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor576e98c2009-01-30 23:27:23 +00004588 return true;
4589 }
4590
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004591 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004592 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004593 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004594 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004595 // When a parameter of reference type is not bound directly to
4596 // an argument expression, the conversion sequence is the one
4597 // required to convert the argument expression to the
4598 // underlying type of the reference according to
4599 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4600 // to copy-initializing a temporary of the underlying type with
4601 // the argument expression. Any difference in top-level
4602 // cv-qualification is subsumed by the initialization itself
4603 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004604 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4605 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004606 /*ForceRValue=*/false,
4607 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004608
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004609 // Of course, that's still a reference binding.
4610 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4611 ICS->Standard.ReferenceBinding = true;
4612 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004613 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004614 ImplicitConversionSequence::UserDefinedConversion) {
4615 ICS->UserDefined.After.ReferenceBinding = true;
4616 ICS->UserDefined.After.RRefBinding = isRValRef;
4617 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004618 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4619 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004620 ImplicitConversionSequence Conversions;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004621 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004622 false, false,
4623 Conversions);
4624 if (badConversion) {
4625 if ((Conversions.ConversionKind ==
4626 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004627 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004628 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004629 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4630 for (int j = Conversions.ConversionFunctionSet.size()-1;
4631 j >= 0; j--) {
4632 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4633 Diag(Func->getLocation(), diag::err_ovl_candidate);
4634 }
4635 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004636 else {
4637 if (isRValRef)
4638 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4639 << Init->getSourceRange();
4640 else
4641 Diag(DeclLoc, diag::err_invalid_initialization)
4642 << DeclType << Init->getType() << Init->getSourceRange();
4643 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004644 }
4645 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004646 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004647}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004648
Anders Carlssone363c8e2009-12-12 00:32:00 +00004649static inline bool
4650CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4651 const FunctionDecl *FnDecl) {
4652 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4653 if (isa<NamespaceDecl>(DC)) {
4654 return SemaRef.Diag(FnDecl->getLocation(),
4655 diag::err_operator_new_delete_declared_in_namespace)
4656 << FnDecl->getDeclName();
4657 }
4658
4659 if (isa<TranslationUnitDecl>(DC) &&
4660 FnDecl->getStorageClass() == FunctionDecl::Static) {
4661 return SemaRef.Diag(FnDecl->getLocation(),
4662 diag::err_operator_new_delete_declared_static)
4663 << FnDecl->getDeclName();
4664 }
4665
Anders Carlsson60659a82009-12-12 02:43:16 +00004666 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004667}
4668
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004669static inline bool
4670CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4671 CanQualType ExpectedResultType,
4672 CanQualType ExpectedFirstParamType,
4673 unsigned DependentParamTypeDiag,
4674 unsigned InvalidParamTypeDiag) {
4675 QualType ResultType =
4676 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4677
4678 // Check that the result type is not dependent.
4679 if (ResultType->isDependentType())
4680 return SemaRef.Diag(FnDecl->getLocation(),
4681 diag::err_operator_new_delete_dependent_result_type)
4682 << FnDecl->getDeclName() << ExpectedResultType;
4683
4684 // Check that the result type is what we expect.
4685 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4686 return SemaRef.Diag(FnDecl->getLocation(),
4687 diag::err_operator_new_delete_invalid_result_type)
4688 << FnDecl->getDeclName() << ExpectedResultType;
4689
4690 // A function template must have at least 2 parameters.
4691 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4692 return SemaRef.Diag(FnDecl->getLocation(),
4693 diag::err_operator_new_delete_template_too_few_parameters)
4694 << FnDecl->getDeclName();
4695
4696 // The function decl must have at least 1 parameter.
4697 if (FnDecl->getNumParams() == 0)
4698 return SemaRef.Diag(FnDecl->getLocation(),
4699 diag::err_operator_new_delete_too_few_parameters)
4700 << FnDecl->getDeclName();
4701
4702 // Check the the first parameter type is not dependent.
4703 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4704 if (FirstParamType->isDependentType())
4705 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4706 << FnDecl->getDeclName() << ExpectedFirstParamType;
4707
4708 // Check that the first parameter type is what we expect.
4709 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4710 ExpectedFirstParamType)
4711 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4712 << FnDecl->getDeclName() << ExpectedFirstParamType;
4713
4714 return false;
4715}
4716
Anders Carlsson12308f42009-12-11 23:23:22 +00004717static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004718CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004719 // C++ [basic.stc.dynamic.allocation]p1:
4720 // A program is ill-formed if an allocation function is declared in a
4721 // namespace scope other than global scope or declared static in global
4722 // scope.
4723 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4724 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004725
4726 CanQualType SizeTy =
4727 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4728
4729 // C++ [basic.stc.dynamic.allocation]p1:
4730 // The return type shall be void*. The first parameter shall have type
4731 // std::size_t.
4732 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4733 SizeTy,
4734 diag::err_operator_new_dependent_param_type,
4735 diag::err_operator_new_param_type))
4736 return true;
4737
4738 // C++ [basic.stc.dynamic.allocation]p1:
4739 // The first parameter shall not have an associated default argument.
4740 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004741 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004742 diag::err_operator_new_default_arg)
4743 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4744
4745 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004746}
4747
4748static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004749CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4750 // C++ [basic.stc.dynamic.deallocation]p1:
4751 // A program is ill-formed if deallocation functions are declared in a
4752 // namespace scope other than global scope or declared static in global
4753 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004754 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4755 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004756
4757 // C++ [basic.stc.dynamic.deallocation]p2:
4758 // Each deallocation function shall return void and its first parameter
4759 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004760 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4761 SemaRef.Context.VoidPtrTy,
4762 diag::err_operator_delete_dependent_param_type,
4763 diag::err_operator_delete_param_type))
4764 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004765
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004766 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4767 if (FirstParamType->isDependentType())
4768 return SemaRef.Diag(FnDecl->getLocation(),
4769 diag::err_operator_delete_dependent_param_type)
4770 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4771
4772 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4773 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00004774 return SemaRef.Diag(FnDecl->getLocation(),
4775 diag::err_operator_delete_param_type)
4776 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00004777
4778 return false;
4779}
4780
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004781/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4782/// of this overloaded operator is well-formed. If so, returns false;
4783/// otherwise, emits appropriate diagnostics and returns true.
4784bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004785 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004786 "Expected an overloaded operator declaration");
4787
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004788 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4789
Mike Stump11289f42009-09-09 15:08:12 +00004790 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004791 // The allocation and deallocation functions, operator new,
4792 // operator new[], operator delete and operator delete[], are
4793 // described completely in 3.7.3. The attributes and restrictions
4794 // found in the rest of this subclause do not apply to them unless
4795 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00004796 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00004797 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004798
Anders Carlsson22f443f2009-12-12 00:26:23 +00004799 if (Op == OO_New || Op == OO_Array_New)
4800 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004801
4802 // C++ [over.oper]p6:
4803 // An operator function shall either be a non-static member
4804 // function or be a non-member function and have at least one
4805 // parameter whose type is a class, a reference to a class, an
4806 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004807 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4808 if (MethodDecl->isStatic())
4809 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004810 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004811 } else {
4812 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004813 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4814 ParamEnd = FnDecl->param_end();
4815 Param != ParamEnd; ++Param) {
4816 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004817 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4818 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004819 ClassOrEnumParam = true;
4820 break;
4821 }
4822 }
4823
Douglas Gregord69246b2008-11-17 16:14:12 +00004824 if (!ClassOrEnumParam)
4825 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004826 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004827 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004828 }
4829
4830 // C++ [over.oper]p8:
4831 // An operator function cannot have default arguments (8.3.6),
4832 // except where explicitly stated below.
4833 //
Mike Stump11289f42009-09-09 15:08:12 +00004834 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004835 // (C++ [over.call]p1).
4836 if (Op != OO_Call) {
4837 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4838 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004839 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004840 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004841 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004842 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004843 }
4844 }
4845
Douglas Gregor6cf08062008-11-10 13:38:07 +00004846 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4847 { false, false, false }
4848#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4849 , { Unary, Binary, MemberOnly }
4850#include "clang/Basic/OperatorKinds.def"
4851 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004852
Douglas Gregor6cf08062008-11-10 13:38:07 +00004853 bool CanBeUnaryOperator = OperatorUses[Op][0];
4854 bool CanBeBinaryOperator = OperatorUses[Op][1];
4855 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004856
4857 // C++ [over.oper]p8:
4858 // [...] Operator functions cannot have more or fewer parameters
4859 // than the number required for the corresponding operator, as
4860 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004861 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004862 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004863 if (Op != OO_Call &&
4864 ((NumParams == 1 && !CanBeUnaryOperator) ||
4865 (NumParams == 2 && !CanBeBinaryOperator) ||
4866 (NumParams < 1) || (NumParams > 2))) {
4867 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004868 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004869 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004870 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004871 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004872 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004873 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004874 assert(CanBeBinaryOperator &&
4875 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004876 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004877 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004878
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004879 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004880 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004881 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004882
Douglas Gregord69246b2008-11-17 16:14:12 +00004883 // Overloaded operators other than operator() cannot be variadic.
4884 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004885 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004886 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004887 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004888 }
4889
4890 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004891 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4892 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004893 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004894 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004895 }
4896
4897 // C++ [over.inc]p1:
4898 // The user-defined function called operator++ implements the
4899 // prefix and postfix ++ operator. If this function is a member
4900 // function with no parameters, or a non-member function with one
4901 // parameter of class or enumeration type, it defines the prefix
4902 // increment operator ++ for objects of that type. If the function
4903 // is a member function with one parameter (which shall be of type
4904 // int) or a non-member function with two parameters (the second
4905 // of which shall be of type int), it defines the postfix
4906 // increment operator ++ for objects of that type.
4907 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4908 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4909 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004910 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004911 ParamIsInt = BT->getKind() == BuiltinType::Int;
4912
Chris Lattner2b786902008-11-21 07:50:02 +00004913 if (!ParamIsInt)
4914 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004915 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004916 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004917 }
4918
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004919 // Notify the class if it got an assignment operator.
4920 if (Op == OO_Equal) {
4921 // Would have returned earlier otherwise.
4922 assert(isa<CXXMethodDecl>(FnDecl) &&
4923 "Overloaded = not member, but not filtered.");
4924 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4925 Method->getParent()->addedAssignmentOperator(Context, Method);
4926 }
4927
Douglas Gregord69246b2008-11-17 16:14:12 +00004928 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004929}
Chris Lattner3b024a32008-12-17 07:09:26 +00004930
Douglas Gregor07665a62009-01-05 19:45:36 +00004931/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4932/// linkage specification, including the language and (if present)
4933/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4934/// the location of the language string literal, which is provided
4935/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4936/// the '{' brace. Otherwise, this linkage specification does not
4937/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004938Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4939 SourceLocation ExternLoc,
4940 SourceLocation LangLoc,
4941 const char *Lang,
4942 unsigned StrSize,
4943 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004944 LinkageSpecDecl::LanguageIDs Language;
4945 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4946 Language = LinkageSpecDecl::lang_c;
4947 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4948 Language = LinkageSpecDecl::lang_cxx;
4949 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004950 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004951 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004952 }
Mike Stump11289f42009-09-09 15:08:12 +00004953
Chris Lattner438e5012008-12-17 07:13:27 +00004954 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004955
Douglas Gregor07665a62009-01-05 19:45:36 +00004956 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004957 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004958 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004959 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004960 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004961 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004962}
4963
Douglas Gregor07665a62009-01-05 19:45:36 +00004964/// ActOnFinishLinkageSpecification - Completely the definition of
4965/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4966/// valid, it's the position of the closing '}' brace in a linkage
4967/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004968Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4969 DeclPtrTy LinkageSpec,
4970 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004971 if (LinkageSpec)
4972 PopDeclContext();
4973 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004974}
4975
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004976/// \brief Perform semantic analysis for the variable declaration that
4977/// occurs within a C++ catch clause, returning the newly-created
4978/// variable.
4979VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00004980 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004981 IdentifierInfo *Name,
4982 SourceLocation Loc,
4983 SourceRange Range) {
4984 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004985
4986 // Arrays and functions decay.
4987 if (ExDeclType->isArrayType())
4988 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4989 else if (ExDeclType->isFunctionType())
4990 ExDeclType = Context.getPointerType(ExDeclType);
4991
4992 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4993 // The exception-declaration shall not denote a pointer or reference to an
4994 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004995 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004996 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004997 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004998 Invalid = true;
4999 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005000
Sebastian Redl54c04d42008-12-22 19:15:10 +00005001 QualType BaseType = ExDeclType;
5002 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005003 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005004 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005005 BaseType = Ptr->getPointeeType();
5006 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00005007 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00005008 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005009 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005010 BaseType = Ref->getPointeeType();
5011 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00005012 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005013 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005014 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005015 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00005016 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005017
Mike Stump11289f42009-09-09 15:08:12 +00005018 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005019 RequireNonAbstractType(Loc, ExDeclType,
5020 diag::err_abstract_type_in_decl,
5021 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005022 Invalid = true;
5023
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005024 // FIXME: Need to test for ability to copy-construct and destroy the
5025 // exception variable.
5026
Sebastian Redl9b244a82008-12-22 21:35:02 +00005027 // FIXME: Need to check for abstract classes.
5028
Mike Stump11289f42009-09-09 15:08:12 +00005029 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCallbcd03502009-12-07 02:54:59 +00005030 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005031
5032 if (Invalid)
5033 ExDecl->setInvalidDecl();
5034
5035 return ExDecl;
5036}
5037
5038/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5039/// handler.
5040Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005041 TypeSourceInfo *TInfo = 0;
5042 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005043
5044 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005045 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00005046 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005047 // The scope should be freshly made just for us. There is just no way
5048 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005049 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005050 if (PrevDecl->isTemplateParameter()) {
5051 // Maybe we will complain about the shadowed template parameter.
5052 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005053 }
5054 }
5055
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005056 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005057 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5058 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005059 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005060 }
5061
John McCallbcd03502009-12-07 02:54:59 +00005062 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005063 D.getIdentifier(),
5064 D.getIdentifierLoc(),
5065 D.getDeclSpec().getSourceRange());
5066
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005067 if (Invalid)
5068 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005069
Sebastian Redl54c04d42008-12-22 19:15:10 +00005070 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005071 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005072 PushOnScopeChains(ExDecl, S);
5073 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005074 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005075
Douglas Gregor758a8692009-06-17 21:51:59 +00005076 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005077 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005078}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005079
Mike Stump11289f42009-09-09 15:08:12 +00005080Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005081 ExprArg assertexpr,
5082 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005083 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005084 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005085 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5086
Anders Carlsson54b26982009-03-14 00:33:21 +00005087 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5088 llvm::APSInt Value(32);
5089 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5090 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5091 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005092 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005093 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005094
Anders Carlsson54b26982009-03-14 00:33:21 +00005095 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005096 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005097 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005098 }
5099 }
Mike Stump11289f42009-09-09 15:08:12 +00005100
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005101 assertexpr.release();
5102 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005103 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005104 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005105
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005106 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005107 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005108}
Sebastian Redlf769df52009-03-24 22:27:57 +00005109
John McCall11083da2009-09-16 22:47:08 +00005110/// Handle a friend type declaration. This works in tandem with
5111/// ActOnTag.
5112///
5113/// Notes on friend class templates:
5114///
5115/// We generally treat friend class declarations as if they were
5116/// declaring a class. So, for example, the elaborated type specifier
5117/// in a friend declaration is required to obey the restrictions of a
5118/// class-head (i.e. no typedefs in the scope chain), template
5119/// parameters are required to match up with simple template-ids, &c.
5120/// However, unlike when declaring a template specialization, it's
5121/// okay to refer to a template specialization without an empty
5122/// template parameter declaration, e.g.
5123/// friend class A<T>::B<unsigned>;
5124/// We permit this as a special case; if there are any template
5125/// parameters present at all, require proper matching, i.e.
5126/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005127Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005128 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005129 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005130
5131 assert(DS.isFriendSpecified());
5132 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5133
John McCall11083da2009-09-16 22:47:08 +00005134 // Try to convert the decl specifier to a type. This works for
5135 // friend templates because ActOnTag never produces a ClassTemplateDecl
5136 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005137 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005138 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5139 if (TheDeclarator.isInvalidType())
5140 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005141
John McCall11083da2009-09-16 22:47:08 +00005142 // This is definitely an error in C++98. It's probably meant to
5143 // be forbidden in C++0x, too, but the specification is just
5144 // poorly written.
5145 //
5146 // The problem is with declarations like the following:
5147 // template <T> friend A<T>::foo;
5148 // where deciding whether a class C is a friend or not now hinges
5149 // on whether there exists an instantiation of A that causes
5150 // 'foo' to equal C. There are restrictions on class-heads
5151 // (which we declare (by fiat) elaborated friend declarations to
5152 // be) that makes this tractable.
5153 //
5154 // FIXME: handle "template <> friend class A<T>;", which
5155 // is possibly well-formed? Who even knows?
5156 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5157 Diag(Loc, diag::err_tagless_friend_type_template)
5158 << DS.getSourceRange();
5159 return DeclPtrTy();
5160 }
5161
John McCallaa74a0c2009-08-28 07:59:38 +00005162 // C++ [class.friend]p2:
5163 // An elaborated-type-specifier shall be used in a friend declaration
5164 // for a class.*
5165 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00005166 // This is one of the rare places in Clang where it's legitimate to
5167 // ask about the "spelling" of the type.
5168 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5169 // If we evaluated the type to a record type, suggest putting
5170 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00005171 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00005172 RecordDecl *RD = RT->getDecl();
5173
5174 std::string InsertionText = std::string(" ") + RD->getKindName();
5175
John McCallc3987482009-10-07 23:34:25 +00005176 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5177 << (unsigned) RD->getTagKind()
5178 << T
5179 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00005180 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5181 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00005182 return DeclPtrTy();
5183 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00005184 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5185 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005186 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00005187 }
5188 }
5189
John McCallc3987482009-10-07 23:34:25 +00005190 // Enum types cannot be friends.
5191 if (T->getAs<EnumType>()) {
5192 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5193 << SourceRange(DS.getFriendSpecLoc());
5194 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00005195 }
John McCallaa74a0c2009-08-28 07:59:38 +00005196
John McCallaa74a0c2009-08-28 07:59:38 +00005197 // C++98 [class.friend]p1: A friend of a class is a function
5198 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005199 // This is fixed in DR77, which just barely didn't make the C++03
5200 // deadline. It's also a very silly restriction that seriously
5201 // affects inner classes and which nobody else seems to implement;
5202 // thus we never diagnose it, not even in -pedantic.
John McCallaa74a0c2009-08-28 07:59:38 +00005203
John McCall11083da2009-09-16 22:47:08 +00005204 Decl *D;
5205 if (TempParams.size())
5206 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5207 TempParams.size(),
5208 (TemplateParameterList**) TempParams.release(),
5209 T.getTypePtr(),
5210 DS.getFriendSpecLoc());
5211 else
5212 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5213 DS.getFriendSpecLoc());
5214 D->setAccess(AS_public);
5215 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005216
John McCall11083da2009-09-16 22:47:08 +00005217 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005218}
5219
John McCall2f212b32009-09-11 21:02:39 +00005220Sema::DeclPtrTy
5221Sema::ActOnFriendFunctionDecl(Scope *S,
5222 Declarator &D,
5223 bool IsDefinition,
5224 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005225 const DeclSpec &DS = D.getDeclSpec();
5226
5227 assert(DS.isFriendSpecified());
5228 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5229
5230 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005231 TypeSourceInfo *TInfo = 0;
5232 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005233
5234 // C++ [class.friend]p1
5235 // A friend of a class is a function or class....
5236 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005237 // It *doesn't* see through dependent types, which is correct
5238 // according to [temp.arg.type]p3:
5239 // If a declaration acquires a function type through a
5240 // type dependent on a template-parameter and this causes
5241 // a declaration that does not use the syntactic form of a
5242 // function declarator to have a function type, the program
5243 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005244 if (!T->isFunctionType()) {
5245 Diag(Loc, diag::err_unexpected_friend);
5246
5247 // It might be worthwhile to try to recover by creating an
5248 // appropriate declaration.
5249 return DeclPtrTy();
5250 }
5251
5252 // C++ [namespace.memdef]p3
5253 // - If a friend declaration in a non-local class first declares a
5254 // class or function, the friend class or function is a member
5255 // of the innermost enclosing namespace.
5256 // - The name of the friend is not found by simple name lookup
5257 // until a matching declaration is provided in that namespace
5258 // scope (either before or after the class declaration granting
5259 // friendship).
5260 // - If a friend function is called, its name may be found by the
5261 // name lookup that considers functions from namespaces and
5262 // classes associated with the types of the function arguments.
5263 // - When looking for a prior declaration of a class or a function
5264 // declared as a friend, scopes outside the innermost enclosing
5265 // namespace scope are not considered.
5266
John McCallaa74a0c2009-08-28 07:59:38 +00005267 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5268 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005269 assert(Name);
5270
John McCall07e91c02009-08-06 02:15:43 +00005271 // The context we found the declaration in, or in which we should
5272 // create the declaration.
5273 DeclContext *DC;
5274
5275 // FIXME: handle local classes
5276
5277 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005278 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5279 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005280 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005281 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00005282 DC = computeDeclContext(ScopeQual);
5283
5284 // FIXME: handle dependent contexts
5285 if (!DC) return DeclPtrTy();
5286
John McCall1f82f242009-11-18 22:49:29 +00005287 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005288
5289 // If searching in that context implicitly found a declaration in
5290 // a different context, treat it like it wasn't found at all.
5291 // TODO: better diagnostics for this case. Suggesting the right
5292 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005293 // FIXME: getRepresentativeDecl() is not right here at all
5294 if (Previous.empty() ||
5295 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005296 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005297 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5298 return DeclPtrTy();
5299 }
5300
5301 // C++ [class.friend]p1: A friend of a class is a function or
5302 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005303 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005304 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5305
John McCall07e91c02009-08-06 02:15:43 +00005306 // Otherwise walk out to the nearest namespace scope looking for matches.
5307 } else {
5308 // TODO: handle local class contexts.
5309
5310 DC = CurContext;
5311 while (true) {
5312 // Skip class contexts. If someone can cite chapter and verse
5313 // for this behavior, that would be nice --- it's what GCC and
5314 // EDG do, and it seems like a reasonable intent, but the spec
5315 // really only says that checks for unqualified existing
5316 // declarations should stop at the nearest enclosing namespace,
5317 // not that they should only consider the nearest enclosing
5318 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005319 while (DC->isRecord())
5320 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005321
John McCall1f82f242009-11-18 22:49:29 +00005322 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005323
5324 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005325 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005326 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005327
John McCall07e91c02009-08-06 02:15:43 +00005328 if (DC->isFileContext()) break;
5329 DC = DC->getParent();
5330 }
5331
5332 // C++ [class.friend]p1: A friend of a class is a function or
5333 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005334 // C++0x changes this for both friend types and functions.
5335 // Most C++ 98 compilers do seem to give an error here, so
5336 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005337 if (!Previous.empty() && DC->Equals(CurContext)
5338 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005339 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5340 }
5341
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005342 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005343 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005344 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5345 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5346 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005347 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005348 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5349 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005350 return DeclPtrTy();
5351 }
John McCall07e91c02009-08-06 02:15:43 +00005352 }
5353
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005354 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005355 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005356 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005357 IsDefinition,
5358 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005359 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005360
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005361 assert(ND->getDeclContext() == DC);
5362 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005363
John McCall759e32b2009-08-31 22:39:49 +00005364 // Add the function declaration to the appropriate lookup tables,
5365 // adjusting the redeclarations list as necessary. We don't
5366 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005367 //
John McCall759e32b2009-08-31 22:39:49 +00005368 // Also update the scope-based lookup if the target context's
5369 // lookup context is in lexical scope.
5370 if (!CurContext->isDependentContext()) {
5371 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005372 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005373 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005374 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005375 }
John McCallaa74a0c2009-08-28 07:59:38 +00005376
5377 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005378 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005379 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005380 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005381 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005382
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005383 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005384}
5385
Chris Lattner83f095c2009-03-28 19:18:32 +00005386void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005387 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005388
Chris Lattner83f095c2009-03-28 19:18:32 +00005389 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005390 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5391 if (!Fn) {
5392 Diag(DelLoc, diag::err_deleted_non_function);
5393 return;
5394 }
5395 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5396 Diag(DelLoc, diag::err_deleted_decl_not_first);
5397 Diag(Prev->getLocation(), diag::note_previous_declaration);
5398 // If the declaration wasn't the first, we delete the function anyway for
5399 // recovery.
5400 }
5401 Fn->setDeleted();
5402}
Sebastian Redl4c018662009-04-27 21:33:24 +00005403
5404static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5405 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5406 ++CI) {
5407 Stmt *SubStmt = *CI;
5408 if (!SubStmt)
5409 continue;
5410 if (isa<ReturnStmt>(SubStmt))
5411 Self.Diag(SubStmt->getSourceRange().getBegin(),
5412 diag::err_return_in_constructor_handler);
5413 if (!isa<Expr>(SubStmt))
5414 SearchForReturnInStmt(Self, SubStmt);
5415 }
5416}
5417
5418void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5419 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5420 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5421 SearchForReturnInStmt(*this, Handler);
5422 }
5423}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005424
Mike Stump11289f42009-09-09 15:08:12 +00005425bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005426 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005427 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5428 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005429
5430 QualType CNewTy = Context.getCanonicalType(NewTy);
5431 QualType COldTy = Context.getCanonicalType(OldTy);
5432
Mike Stump11289f42009-09-09 15:08:12 +00005433 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005434 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005435 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005436
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005437 // Check if the return types are covariant
5438 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005439
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005440 /// Both types must be pointers or references to classes.
5441 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5442 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5443 NewClassTy = NewPT->getPointeeType();
5444 OldClassTy = OldPT->getPointeeType();
5445 }
5446 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5447 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5448 NewClassTy = NewRT->getPointeeType();
5449 OldClassTy = OldRT->getPointeeType();
5450 }
5451 }
Mike Stump11289f42009-09-09 15:08:12 +00005452
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005453 // The return types aren't either both pointers or references to a class type.
5454 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005455 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005456 diag::err_different_return_type_for_overriding_virtual_function)
5457 << New->getDeclName() << NewTy << OldTy;
5458 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005459
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005460 return true;
5461 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005462
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005463 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005464 // Check if the new class derives from the old class.
5465 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5466 Diag(New->getLocation(),
5467 diag::err_covariant_return_not_derived)
5468 << New->getDeclName() << NewTy << OldTy;
5469 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5470 return true;
5471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005473 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00005474 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005475 diag::err_covariant_return_inaccessible_base,
5476 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5477 // FIXME: Should this point to the return type?
5478 New->getLocation(), SourceRange(), New->getDeclName())) {
5479 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5480 return true;
5481 }
5482 }
Mike Stump11289f42009-09-09 15:08:12 +00005483
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005484 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005485 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005486 Diag(New->getLocation(),
5487 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005488 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005489 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5490 return true;
5491 };
Mike Stump11289f42009-09-09 15:08:12 +00005492
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005493
5494 // The new class type must have the same or less qualifiers as the old type.
5495 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5496 Diag(New->getLocation(),
5497 diag::err_covariant_return_type_class_type_more_qualified)
5498 << New->getDeclName() << NewTy << OldTy;
5499 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5500 return true;
5501 };
Mike Stump11289f42009-09-09 15:08:12 +00005502
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005503 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005504}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005505
Alexis Hunt96d5c762009-11-21 08:43:09 +00005506bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5507 const CXXMethodDecl *Old)
5508{
5509 if (Old->hasAttr<FinalAttr>()) {
5510 Diag(New->getLocation(), diag::err_final_function_overridden)
5511 << New->getDeclName();
5512 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5513 return true;
5514 }
5515
5516 return false;
5517}
5518
Douglas Gregor21920e372009-12-01 17:24:26 +00005519/// \brief Mark the given method pure.
5520///
5521/// \param Method the method to be marked pure.
5522///
5523/// \param InitRange the source range that covers the "0" initializer.
5524bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5525 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5526 Method->setPure();
5527
5528 // A class is abstract if at least one function is pure virtual.
5529 Method->getParent()->setAbstract(true);
5530 return false;
5531 }
5532
5533 if (!Method->isInvalidDecl())
5534 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5535 << Method->getDeclName() << InitRange;
5536 return true;
5537}
5538
John McCall1f4ee7b2009-12-19 09:28:58 +00005539/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5540/// an initializer for the out-of-line declaration 'Dcl'. The scope
5541/// is a fresh scope pushed for just this purpose.
5542///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005543/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5544/// static data member of class X, names should be looked up in the scope of
5545/// class X.
5546void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005547 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005548 Decl *D = Dcl.getAs<Decl>();
5549 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005550
John McCall1f4ee7b2009-12-19 09:28:58 +00005551 // We should only get called for declarations with scope specifiers, like:
5552 // int foo::bar;
5553 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005554 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005555}
5556
5557/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005558/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005559void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005560 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005561 Decl *D = Dcl.getAs<Decl>();
5562 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005563
John McCall1f4ee7b2009-12-19 09:28:58 +00005564 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005565 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005566}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005567
5568/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5569/// C++ if/switch/while/for statement.
5570/// e.g: "if (int x = f()) {...}"
5571Action::DeclResult
5572Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5573 // C++ 6.4p2:
5574 // The declarator shall not specify a function or an array.
5575 // The type-specifier-seq shall not contain typedef and shall not declare a
5576 // new class or enumeration.
5577 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5578 "Parser allowed 'typedef' as storage class of condition decl.");
5579
John McCallbcd03502009-12-07 02:54:59 +00005580 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005581 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005582 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005583
5584 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5585 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5586 // would be created and CXXConditionDeclExpr wants a VarDecl.
5587 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5588 << D.getSourceRange();
5589 return DeclResult();
5590 } else if (OwnedTag && OwnedTag->isDefinition()) {
5591 // The type-specifier-seq shall not declare a new class or enumeration.
5592 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5593 }
5594
5595 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5596 if (!Dcl)
5597 return DeclResult();
5598
5599 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5600 VD->setDeclaredInCondition(true);
5601 return Dcl;
5602}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005603
Anders Carlsson82fccd02009-12-07 08:24:59 +00005604void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5605 CXXMethodDecl *MD) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005606 // Ignore dependent types.
5607 if (MD->isDependentContext())
5608 return;
5609
5610 CXXRecordDecl *RD = MD->getParent();
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005611
5612 // Ignore classes without a vtable.
5613 if (!RD->isDynamicClass())
5614 return;
5615
Anders Carlsson82fccd02009-12-07 08:24:59 +00005616 if (!MD->isOutOfLine()) {
5617 // The only inline functions we care about are constructors. We also defer
5618 // marking the virtual members as referenced until we've reached the end
5619 // of the translation unit. We do this because we need to know the key
5620 // function of the class in order to determine the key function.
5621 if (isa<CXXConstructorDecl>(MD))
5622 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5623 return;
5624 }
5625
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005626 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005627
5628 if (!KeyFunction) {
5629 // This record does not have a key function, so we assume that the vtable
5630 // will be emitted when it's used by the constructor.
5631 if (!isa<CXXConstructorDecl>(MD))
5632 return;
5633 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5634 // We don't have the right key function.
5635 return;
5636 }
5637
Anders Carlsson82fccd02009-12-07 08:24:59 +00005638 // Mark the members as referenced.
5639 MarkVirtualMembersReferenced(Loc, RD);
5640 ClassesWithUnmarkedVirtualMembers.erase(RD);
5641}
5642
5643bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5644 if (ClassesWithUnmarkedVirtualMembers.empty())
5645 return false;
5646
5647 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5648 ClassesWithUnmarkedVirtualMembers.begin(),
5649 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5650 CXXRecordDecl *RD = i->first;
5651
5652 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5653 if (KeyFunction) {
5654 // We know that the class has a key function. If the key function was
5655 // declared in this translation unit, then it the class decl would not
5656 // have been in the ClassesWithUnmarkedVirtualMembers map.
5657 continue;
5658 }
5659
5660 SourceLocation Loc = i->second;
5661 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005662 }
5663
Anders Carlsson82fccd02009-12-07 08:24:59 +00005664 ClassesWithUnmarkedVirtualMembers.clear();
5665 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00005666}
Anders Carlsson82fccd02009-12-07 08:24:59 +00005667
5668void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5669 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5670 e = RD->method_end(); i != e; ++i) {
5671 CXXMethodDecl *MD = *i;
5672
5673 // C++ [basic.def.odr]p2:
5674 // [...] A virtual member function is used if it is not pure. [...]
5675 if (MD->isVirtual() && !MD->isPure())
5676 MarkDeclarationReferenced(Loc, MD);
5677 }
5678}
5679