blob: a27785e4f3571d8e8d41e02a5e060bb2b9176e28 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000093 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
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).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
Anders Carlsson6e997b22009-12-15 20:51:39 +0000140 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000145 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000146}
147
Chris Lattner58258242008-04-10 02:22:51 +0000148/// ActOnParamDefaultArgument - Check whether the default argument
149/// provided for a function parameter is well-formed. If so, attach it
150/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000151void
John McCall48871652010-08-21 09:40:31 +0000152Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000153 Expr *DefaultArg) {
154 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000155 return;
Mike Stump11289f42009-09-09 15:08:12 +0000156
John McCall48871652010-08-21 09:40:31 +0000157 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000158 UnparsedDefaultArgLocs.erase(Param);
159
Chris Lattner199abbc2008-04-08 05:04:30 +0000160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlssonf1c26952009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
170 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump11289f42009-09-09 15:08:12 +0000174
John McCallb268a282010-08-23 23:25:46 +0000175 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000176}
177
Douglas Gregor58354032008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000182void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump11289f42009-09-09 15:08:12 +0000187
John McCall48871652010-08-21 09:40:31 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000191
Anders Carlsson84613c42009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000193}
194
Douglas Gregor4d87df52008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000197void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump11289f42009-09-09 15:08:12 +0000200
John McCall48871652010-08-21 09:40:31 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000202
Anders Carlsson84613c42009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000204
Anders Carlsson84613c42009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000206}
207
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner199abbc2008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner199abbc2008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregorc732aba2009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000300 // Merge the old default argument into the new parameter.
301 // It's important to use getInit() here; getDefaultArg()
302 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000303 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000304 if (OldParam->hasUninstantiatedDefaultArg())
305 NewParam->setUninstantiatedDefaultArg(
306 OldParam->getUninstantiatedDefaultArg());
307 else
John McCalle61b02b2010-05-04 01:53:42 +0000308 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000309 } else if (NewParam->hasDefaultArg()) {
310 if (New->getDescribedFunctionTemplate()) {
311 // Paragraph 4, quoted above, only applies to non-template functions.
312 Diag(NewParam->getLocation(),
313 diag::err_param_default_argument_template_redecl)
314 << NewParam->getDefaultArgRange();
315 Diag(Old->getLocation(), diag::note_template_prev_declaration)
316 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000317 } else if (New->getTemplateSpecializationKind()
318 != TSK_ImplicitInstantiation &&
319 New->getTemplateSpecializationKind() != TSK_Undeclared) {
320 // C++ [temp.expr.spec]p21:
321 // Default function arguments shall not be specified in a declaration
322 // or a definition for one of the following explicit specializations:
323 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000324 // - the explicit specialization of a member function template;
325 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000326 // template where the class template specialization to which the
327 // member function specialization belongs is implicitly
328 // instantiated.
329 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
330 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
331 << New->getDeclName()
332 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000333 } else if (New->getDeclContext()->isDependentContext()) {
334 // C++ [dcl.fct.default]p6 (DR217):
335 // Default arguments for a member function of a class template shall
336 // be specified on the initial declaration of the member function
337 // within the class template.
338 //
339 // Reading the tea leaves a bit in DR217 and its reference to DR205
340 // leads me to the conclusion that one cannot add default function
341 // arguments for an out-of-line definition of a member function of a
342 // dependent type.
343 int WhichKind = 2;
344 if (CXXRecordDecl *Record
345 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
346 if (Record->getDescribedClassTemplate())
347 WhichKind = 0;
348 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
349 WhichKind = 1;
350 else
351 WhichKind = 2;
352 }
353
354 Diag(NewParam->getLocation(),
355 diag::err_param_default_argument_member_template_redecl)
356 << WhichKind
357 << NewParam->getDefaultArgRange();
358 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000359 }
360 }
361
Douglas Gregorf40863c2010-02-12 07:32:17 +0000362 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000363 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000364
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000365 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000366}
367
368/// CheckCXXDefaultArguments - Verify that the default arguments for a
369/// function declaration are well-formed according to C++
370/// [dcl.fct.default].
371void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
372 unsigned NumParams = FD->getNumParams();
373 unsigned p;
374
375 // Find first parameter with a default argument
376 for (p = 0; p < NumParams; ++p) {
377 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000378 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000379 break;
380 }
381
382 // C++ [dcl.fct.default]p4:
383 // In a given function declaration, all parameters
384 // subsequent to a parameter with a default argument shall
385 // have default arguments supplied in this or previous
386 // declarations. A default argument shall not be redefined
387 // by a later declaration (not even to the same value).
388 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000389 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000390 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000391 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000392 if (Param->isInvalidDecl())
393 /* We already complained about this parameter. */;
394 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000395 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000396 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000397 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000398 else
Mike Stump11289f42009-09-09 15:08:12 +0000399 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000400 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattner199abbc2008-04-08 05:04:30 +0000402 LastMissingDefaultArg = p;
403 }
404 }
405
406 if (LastMissingDefaultArg > 0) {
407 // Some default arguments were missing. Clear out all of the
408 // default arguments up to (and including) the last missing
409 // default argument, so that we leave the function parameters
410 // in a semantically valid state.
411 for (p = 0; p <= LastMissingDefaultArg; ++p) {
412 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000413 if (Param->hasDefaultArg()) {
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) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000426 assert(getLangOptions().CPlusPlus && "No class names in C!");
427
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000428 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000429 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000430 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
432 } else
433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
434
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000435 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000436 return &II == CurDecl->getIdentifier();
437 else
438 return false;
439}
440
Mike Stump11289f42009-09-09 15:08:12 +0000441/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000442///
443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
444/// and returns NULL otherwise.
445CXXBaseSpecifier *
446Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
447 SourceRange SpecifierRange,
448 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000449 TypeSourceInfo *TInfo) {
450 QualType BaseType = TInfo->getType();
451
Douglas Gregor463421d2009-03-03 04:44:36 +0000452 // C++ [class.union]p1:
453 // A union shall not have base classes.
454 if (Class->isUnion()) {
455 Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 << SpecifierRange;
457 return 0;
458 }
459
460 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000462 Class->getTagKind() == TTK_Class,
463 Access, TInfo);
464
465 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000466
467 // Base specifiers must be record types.
468 if (!BaseType->isRecordType()) {
469 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.union]p1:
474 // A union shall not be used as a base class.
475 if (BaseType->isUnionType()) {
476 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
477 return 0;
478 }
479
480 // C++ [class.derived]p2:
481 // The class-name in a base-specifier shall not be an incompletely
482 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000483 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000484 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000485 << SpecifierRange)) {
486 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000487 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000488 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000489
Eli Friedmanc96d4962009-08-15 21:55:26 +0000490 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000491 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000493 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000494 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000495 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
496 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000497
Alexis Hunt96d5c762009-11-21 08:43:09 +0000498 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
499 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
500 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000501 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
502 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000503 return 0;
504 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000505
John McCall3696dcb2010-08-17 07:23:57 +0000506 if (BaseDecl->isInvalidDecl())
507 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000508
509 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000510 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000511 Class->getTagKind() == TTK_Class,
512 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000513}
514
Douglas Gregor556877c2008-04-13 21:30:24 +0000515/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
516/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000517/// example:
518/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000519/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000520BaseResult
John McCall48871652010-08-21 09:40:31 +0000521Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000522 bool Virtual, AccessSpecifier Access,
John McCallba7bf592010-08-24 05:47:05 +0000523 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000524 if (!classdecl)
525 return true;
526
Douglas Gregorc40290e2009-03-09 23:48:35 +0000527 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000528 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000529 if (!Class)
530 return true;
531
Nick Lewycky19b9f952010-07-26 16:56:01 +0000532 TypeSourceInfo *TInfo = 0;
533 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor463421d2009-03-03 04:44:36 +0000534 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000535 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000536 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregor463421d2009-03-03 04:44:36 +0000538 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000539}
Douglas Gregor556877c2008-04-13 21:30:24 +0000540
Douglas Gregor463421d2009-03-03 04:44:36 +0000541/// \brief Performs the actual work of attaching the given base class
542/// specifiers to a C++ class.
543bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
544 unsigned NumBases) {
545 if (NumBases == 0)
546 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000547
548 // Used to keep track of which base types we have already seen, so
549 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000550 // that the key is always the unqualified canonical type of the base
551 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000552 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
553
554 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000555 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000556 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000557 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000558 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000559 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000560 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000561 if (!Class->hasObjectMember()) {
562 if (const RecordType *FDTTy =
563 NewBaseType.getTypePtr()->getAs<RecordType>())
564 if (FDTTy->getDecl()->hasObjectMember())
565 Class->setHasObjectMember(true);
566 }
567
Douglas Gregor29a92472008-10-22 17:49:05 +0000568 if (KnownBaseTypes[NewBaseType]) {
569 // C++ [class.mi]p3:
570 // A class shall not be specified as a direct base class of a
571 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000573 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000574 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000575 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000576
577 // Delete the duplicate base class specifier; we're going to
578 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000579 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000580
581 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000582 } else {
583 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000584 KnownBaseTypes[NewBaseType] = Bases[idx];
585 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 }
587 }
588
589 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000590 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591
592 // Delete the remaining (good) base class specifiers, since their
593 // data has been copied into the CXXRecordDecl.
594 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000595 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000596
597 return Invalid;
598}
599
600/// ActOnBaseSpecifiers - Attach the given base specifiers to the
601/// class, after checking whether there are any duplicate base
602/// classes.
John McCall48871652010-08-21 09:40:31 +0000603void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000604 unsigned NumBases) {
605 if (!ClassDecl || !Bases || !NumBases)
606 return;
607
608 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000609 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000611}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000612
John McCalle78aac42010-03-10 03:28:59 +0000613static CXXRecordDecl *GetClassForType(QualType T) {
614 if (const RecordType *RT = T->getAs<RecordType>())
615 return cast<CXXRecordDecl>(RT->getDecl());
616 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
617 return ICT->getDecl();
618 else
619 return 0;
620}
621
Douglas Gregor36d1b142009-10-06 17:59:45 +0000622/// \brief Determine whether the type \p Derived is a C++ class that is
623/// derived from the type \p Base.
624bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
625 if (!getLangOptions().CPlusPlus)
626 return false;
John McCalle78aac42010-03-10 03:28:59 +0000627
628 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
629 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000630 return false;
631
John McCalle78aac42010-03-10 03:28:59 +0000632 CXXRecordDecl *BaseRD = GetClassForType(Base);
633 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000634 return false;
635
John McCall67da35c2010-02-04 22:26:26 +0000636 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
637 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000638}
639
640/// \brief Determine whether the type \p Derived is a C++ class that is
641/// derived from the type \p Base.
642bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
643 if (!getLangOptions().CPlusPlus)
644 return false;
645
John McCalle78aac42010-03-10 03:28:59 +0000646 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
647 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000648 return false;
649
John McCalle78aac42010-03-10 03:28:59 +0000650 CXXRecordDecl *BaseRD = GetClassForType(Base);
651 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000652 return false;
653
Douglas Gregor36d1b142009-10-06 17:59:45 +0000654 return DerivedRD->isDerivedFrom(BaseRD, Paths);
655}
656
Anders Carlssona70cff62010-04-24 19:06:50 +0000657void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000658 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000659 assert(BasePathArray.empty() && "Base path array must be empty!");
660 assert(Paths.isRecordingPaths() && "Must record paths!");
661
662 const CXXBasePath &Path = Paths.front();
663
664 // We first go backward and check if we have a virtual base.
665 // FIXME: It would be better if CXXBasePath had the base specifier for
666 // the nearest virtual base.
667 unsigned Start = 0;
668 for (unsigned I = Path.size(); I != 0; --I) {
669 if (Path[I - 1].Base->isVirtual()) {
670 Start = I - 1;
671 break;
672 }
673 }
674
675 // Now add all bases.
676 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000677 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000678}
679
Douglas Gregor88d292c2010-05-13 16:44:06 +0000680/// \brief Determine whether the given base path includes a virtual
681/// base class.
John McCallcf142162010-08-07 06:22:56 +0000682bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
683 for (CXXCastPath::const_iterator B = BasePath.begin(),
684 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000685 B != BEnd; ++B)
686 if ((*B)->isVirtual())
687 return true;
688
689 return false;
690}
691
Douglas Gregor36d1b142009-10-06 17:59:45 +0000692/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
693/// conversion (where Derived and Base are class types) is
694/// well-formed, meaning that the conversion is unambiguous (and
695/// that all of the base classes are accessible). Returns true
696/// and emits a diagnostic if the code is ill-formed, returns false
697/// otherwise. Loc is the location where this routine should point to
698/// if there is an error, and Range is the source range to highlight
699/// if there is an error.
700bool
701Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000702 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000703 unsigned AmbigiousBaseConvID,
704 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000705 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000706 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000707 // First, determine whether the path from Derived to Base is
708 // ambiguous. This is slightly more expensive than checking whether
709 // the Derived to Base conversion exists, because here we need to
710 // explore multiple paths to determine if there is an ambiguity.
711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
712 /*DetectVirtual=*/false);
713 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
714 assert(DerivationOkay &&
715 "Can only be used with a derived-to-base conversion");
716 (void)DerivationOkay;
717
718 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000719 if (InaccessibleBaseID) {
720 // Check that the base class can be accessed.
721 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
722 InaccessibleBaseID)) {
723 case AR_inaccessible:
724 return true;
725 case AR_accessible:
726 case AR_dependent:
727 case AR_delayed:
728 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000729 }
John McCall5b0829a2010-02-10 09:31:12 +0000730 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000731
732 // Build a base path if necessary.
733 if (BasePath)
734 BuildBasePathArray(Paths, *BasePath);
735 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000736 }
737
738 // We know that the derived-to-base conversion is ambiguous, and
739 // we're going to produce a diagnostic. Perform the derived-to-base
740 // search just one more time to compute all of the possible paths so
741 // that we can print them out. This is more expensive than any of
742 // the previous derived-to-base checks we've done, but at this point
743 // performance isn't as much of an issue.
744 Paths.clear();
745 Paths.setRecordingPaths(true);
746 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
747 assert(StillOkay && "Can only be used with a derived-to-base conversion");
748 (void)StillOkay;
749
750 // Build up a textual representation of the ambiguous paths, e.g.,
751 // D -> B -> A, that will be used to illustrate the ambiguous
752 // conversions in the diagnostic. We only print one of the paths
753 // to each base class subobject.
754 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
755
756 Diag(Loc, AmbigiousBaseConvID)
757 << Derived << Base << PathDisplayStr << Range << Name;
758 return true;
759}
760
761bool
762Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000763 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000764 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000765 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000766 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000767 IgnoreAccess ? 0
768 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000769 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000770 Loc, Range, DeclarationName(),
771 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000772}
773
774
775/// @brief Builds a string representing ambiguous paths from a
776/// specific derived class to different subobjects of the same base
777/// class.
778///
779/// This function builds a string that can be used in error messages
780/// to show the different paths that one can take through the
781/// inheritance hierarchy to go from the derived class to different
782/// subobjects of a base class. The result looks something like this:
783/// @code
784/// struct D -> struct B -> struct A
785/// struct D -> struct C -> struct A
786/// @endcode
787std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
788 std::string PathDisplayStr;
789 std::set<unsigned> DisplayedPaths;
790 for (CXXBasePaths::paths_iterator Path = Paths.begin();
791 Path != Paths.end(); ++Path) {
792 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
793 // We haven't displayed a path to this particular base
794 // class subobject yet.
795 PathDisplayStr += "\n ";
796 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
797 for (CXXBasePath::const_iterator Element = Path->begin();
798 Element != Path->end(); ++Element)
799 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
800 }
801 }
802
803 return PathDisplayStr;
804}
805
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000806//===----------------------------------------------------------------------===//
807// C++ class member Handling
808//===----------------------------------------------------------------------===//
809
Abramo Bagnarad7340582010-06-05 05:09:32 +0000810/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000811Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
812 SourceLocation ASLoc,
813 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000814 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000815 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000816 ASLoc, ColonLoc);
817 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000818 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000819}
820
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000821/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
822/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
823/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000824/// any.
John McCall48871652010-08-21 09:40:31 +0000825Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000826Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000827 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000828 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
829 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000830 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000831 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
832 DeclarationName Name = NameInfo.getName();
833 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000834 Expr *BitWidth = static_cast<Expr*>(BW);
835 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000836
John McCallb1cd7da2010-06-04 08:34:12 +0000837 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000838 assert(!DS.isFriendSpecified());
839
John McCallb1cd7da2010-06-04 08:34:12 +0000840 bool isFunc = false;
841 if (D.isFunctionDeclarator())
842 isFunc = true;
843 else if (D.getNumTypeObjects() == 0 &&
844 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000845 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000846 isFunc = TDType->isFunctionType();
847 }
848
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000849 // C++ 9.2p6: A member shall not be declared to have automatic storage
850 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000851 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
852 // data members and cannot be applied to names declared const or static,
853 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000854 switch (DS.getStorageClassSpec()) {
855 case DeclSpec::SCS_unspecified:
856 case DeclSpec::SCS_typedef:
857 case DeclSpec::SCS_static:
858 // FALL THROUGH.
859 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000860 case DeclSpec::SCS_mutable:
861 if (isFunc) {
862 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000863 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000864 else
Chris Lattner3b054132008-11-19 05:08:23 +0000865 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000866
Sebastian Redl8071edb2008-11-17 23:24:37 +0000867 // FIXME: It would be nicer if the keyword was ignored only for this
868 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000869 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000870 }
871 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000872 default:
873 if (DS.getStorageClassSpecLoc().isValid())
874 Diag(DS.getStorageClassSpecLoc(),
875 diag::err_storageclass_invalid_for_member);
876 else
877 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
878 D.getMutableDeclSpec().ClearStorageClassSpecs();
879 }
880
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000881 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
882 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000883 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000884
885 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000886 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000887 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000888 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
889 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000890 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000891 } else {
John McCall48871652010-08-21 09:40:31 +0000892 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000893 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000894 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000895 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000896
897 // Non-instance-fields can't have a bitfield.
898 if (BitWidth) {
899 if (Member->isInvalidDecl()) {
900 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000901 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000902 // C++ 9.6p3: A bit-field shall not be a static member.
903 // "static member 'A' cannot be a bit-field"
904 Diag(Loc, diag::err_static_not_bitfield)
905 << Name << BitWidth->getSourceRange();
906 } else if (isa<TypedefDecl>(Member)) {
907 // "typedef member 'x' cannot be a bit-field"
908 Diag(Loc, diag::err_typedef_not_bitfield)
909 << Name << BitWidth->getSourceRange();
910 } else {
911 // A function typedef ("typedef int f(); f a;").
912 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
913 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000914 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000915 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000916 }
Mike Stump11289f42009-09-09 15:08:12 +0000917
Chris Lattnerd26760a2009-03-05 23:01:03 +0000918 BitWidth = 0;
919 Member->setInvalidDecl();
920 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000921
922 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000923
Douglas Gregor3447e762009-08-20 22:52:58 +0000924 // If we have declared a member function template, set the access of the
925 // templated declaration as well.
926 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
927 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000928 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000929
Douglas Gregor92751d42008-11-17 22:58:34 +0000930 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000931
Douglas Gregor0c880302009-03-11 23:00:04 +0000932 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000933 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000934 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000935 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000936
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000938 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +0000939 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000940 }
John McCall48871652010-08-21 09:40:31 +0000941 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000942}
943
Douglas Gregor15e77a22009-12-31 09:10:24 +0000944/// \brief Find the direct and/or virtual base specifiers that
945/// correspond to the given base type, for use in base initialization
946/// within a constructor.
947static bool FindBaseInitializer(Sema &SemaRef,
948 CXXRecordDecl *ClassDecl,
949 QualType BaseType,
950 const CXXBaseSpecifier *&DirectBaseSpec,
951 const CXXBaseSpecifier *&VirtualBaseSpec) {
952 // First, check for a direct base class.
953 DirectBaseSpec = 0;
954 for (CXXRecordDecl::base_class_const_iterator Base
955 = ClassDecl->bases_begin();
956 Base != ClassDecl->bases_end(); ++Base) {
957 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
958 // We found a direct base of this type. That's what we're
959 // initializing.
960 DirectBaseSpec = &*Base;
961 break;
962 }
963 }
964
965 // Check for a virtual base class.
966 // FIXME: We might be able to short-circuit this if we know in advance that
967 // there are no virtual bases.
968 VirtualBaseSpec = 0;
969 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
970 // We haven't found a base yet; search the class hierarchy for a
971 // virtual base class.
972 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
973 /*DetectVirtual=*/false);
974 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
975 BaseType, Paths)) {
976 for (CXXBasePaths::paths_iterator Path = Paths.begin();
977 Path != Paths.end(); ++Path) {
978 if (Path->back().Base->isVirtual()) {
979 VirtualBaseSpec = Path->back().Base;
980 break;
981 }
982 }
983 }
984 }
985
986 return DirectBaseSpec || VirtualBaseSpec;
987}
988
Douglas Gregore8381c02008-11-05 04:29:56 +0000989/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +0000990MemInitResult
John McCall48871652010-08-21 09:40:31 +0000991Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000992 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000993 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000994 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +0000995 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000996 SourceLocation IdLoc,
997 SourceLocation LParenLoc,
998 ExprTy **Args, unsigned NumArgs,
Douglas Gregore8381c02008-11-05 04:29:56 +0000999 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001000 if (!ConstructorD)
1001 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001003 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001004
1005 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001006 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001007 if (!Constructor) {
1008 // The user wrote a constructor initializer on a function that is
1009 // not a C++ constructor. Ignore the error for now, because we may
1010 // have more member initializers coming; we'll diagnose it just
1011 // once in ActOnMemInitializers.
1012 return true;
1013 }
1014
1015 CXXRecordDecl *ClassDecl = Constructor->getParent();
1016
1017 // C++ [class.base.init]p2:
1018 // Names in a mem-initializer-id are looked up in the scope of the
1019 // constructor’s class and, if not found in that scope, are looked
1020 // up in the scope containing the constructor’s
1021 // definition. [Note: if the constructor’s class contains a member
1022 // with the same name as a direct or virtual base class of the
1023 // class, a mem-initializer-id naming the member or base class and
1024 // composed of a single identifier refers to the class member. A
1025 // mem-initializer-id for the hidden base class may be specified
1026 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001027 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001028 // Look for a member, first.
1029 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001030 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001031 = ClassDecl->lookup(MemberOrBase);
1032 if (Result.first != Result.second)
1033 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001034
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001035 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001036
Eli Friedman8e1433b2009-07-29 19:44:27 +00001037 if (Member)
1038 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001039 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001040 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001041 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001042 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001043 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001044
1045 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001046 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001047 } else {
1048 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1049 LookupParsedName(R, S, &SS);
1050
1051 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1052 if (!TyD) {
1053 if (R.isAmbiguous()) return true;
1054
John McCallda6841b2010-04-09 19:01:14 +00001055 // We don't want access-control diagnostics here.
1056 R.suppressDiagnostics();
1057
Douglas Gregora3b624a2010-01-19 06:46:48 +00001058 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1059 bool NotUnknownSpecialization = false;
1060 DeclContext *DC = computeDeclContext(SS, false);
1061 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1062 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1063
1064 if (!NotUnknownSpecialization) {
1065 // When the scope specifier can refer to a member of an unknown
1066 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001067 BaseType = CheckTypenameType(ETK_None,
1068 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001069 *MemberOrBase, SourceLocation(),
1070 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001071 if (BaseType.isNull())
1072 return true;
1073
Douglas Gregora3b624a2010-01-19 06:46:48 +00001074 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001075 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001076 }
1077 }
1078
Douglas Gregor15e77a22009-12-31 09:10:24 +00001079 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001080 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001081 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1082 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001083 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001084 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001085 // We have found a non-static data member with a similar
1086 // name to what was typed; complain and initialize that
1087 // member.
1088 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1089 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001090 << FixItHint::CreateReplacement(R.getNameLoc(),
1091 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001092 Diag(Member->getLocation(), diag::note_previous_decl)
1093 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001094
1095 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1096 LParenLoc, RParenLoc);
1097 }
1098 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1099 const CXXBaseSpecifier *DirectBaseSpec;
1100 const CXXBaseSpecifier *VirtualBaseSpec;
1101 if (FindBaseInitializer(*this, ClassDecl,
1102 Context.getTypeDeclType(Type),
1103 DirectBaseSpec, VirtualBaseSpec)) {
1104 // We have found a direct or virtual base class with a
1105 // similar name to what was typed; complain and initialize
1106 // that base class.
1107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1108 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001109 << FixItHint::CreateReplacement(R.getNameLoc(),
1110 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001111
1112 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1113 : VirtualBaseSpec;
1114 Diag(BaseSpec->getSourceRange().getBegin(),
1115 diag::note_base_class_specified_here)
1116 << BaseSpec->getType()
1117 << BaseSpec->getSourceRange();
1118
Douglas Gregor15e77a22009-12-31 09:10:24 +00001119 TyD = Type;
1120 }
1121 }
1122 }
1123
Douglas Gregora3b624a2010-01-19 06:46:48 +00001124 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001125 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1126 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1127 return true;
1128 }
John McCallb5a0d312009-12-21 10:41:20 +00001129 }
1130
Douglas Gregora3b624a2010-01-19 06:46:48 +00001131 if (BaseType.isNull()) {
1132 BaseType = Context.getTypeDeclType(TyD);
1133 if (SS.isSet()) {
1134 NestedNameSpecifier *Qualifier =
1135 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001136
Douglas Gregora3b624a2010-01-19 06:46:48 +00001137 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001138 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001139 }
John McCallb5a0d312009-12-21 10:41:20 +00001140 }
1141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
John McCallbcd03502009-12-07 02:54:59 +00001143 if (!TInfo)
1144 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001145
John McCallbcd03502009-12-07 02:54:59 +00001146 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001147 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001148}
1149
John McCalle22a04a2009-11-04 23:02:40 +00001150/// Checks an initializer expression for use of uninitialized fields, such as
1151/// containing the field that is being initialized. Returns true if there is an
1152/// uninitialized field was used an updates the SourceLocation parameter; false
1153/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001154static bool InitExprContainsUninitializedFields(const Stmt *S,
1155 const FieldDecl *LhsField,
1156 SourceLocation *L) {
1157 if (isa<CallExpr>(S)) {
1158 // Do not descend into function calls or constructors, as the use
1159 // of an uninitialized field may be valid. One would have to inspect
1160 // the contents of the function/ctor to determine if it is safe or not.
1161 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1162 // may be safe, depending on what the function/ctor does.
1163 return false;
1164 }
1165 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1166 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001167
1168 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1169 // The member expression points to a static data member.
1170 assert(VD->isStaticDataMember() &&
1171 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001172 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001173 return false;
1174 }
1175
1176 if (isa<EnumConstantDecl>(RhsField)) {
1177 // The member expression points to an enum.
1178 return false;
1179 }
1180
John McCalle22a04a2009-11-04 23:02:40 +00001181 if (RhsField == LhsField) {
1182 // Initializing a field with itself. Throw a warning.
1183 // But wait; there are exceptions!
1184 // Exception #1: The field may not belong to this record.
1185 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001186 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001187 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1188 // Even though the field matches, it does not belong to this record.
1189 return false;
1190 }
1191 // None of the exceptions triggered; return true to indicate an
1192 // uninitialized field was used.
1193 *L = ME->getMemberLoc();
1194 return true;
1195 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001196 } else if (isa<SizeOfAlignOfExpr>(S)) {
1197 // sizeof/alignof doesn't reference contents, do not warn.
1198 return false;
1199 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1200 // address-of doesn't reference contents (the pointer may be dereferenced
1201 // in the same expression but it would be rare; and weird).
1202 if (UOE->getOpcode() == UO_AddrOf)
1203 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001204 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001205 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1206 it != e; ++it) {
1207 if (!*it) {
1208 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001209 continue;
1210 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001211 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1212 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001213 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001214 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001215}
1216
John McCallfaf5fb42010-08-26 23:41:50 +00001217MemInitResult
Eli Friedman8e1433b2009-07-29 19:44:27 +00001218Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1219 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001220 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001221 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001222 // Diagnose value-uses of fields to initialize themselves, e.g.
1223 // foo(foo)
1224 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001225 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001226 for (unsigned i = 0; i < NumArgs; ++i) {
1227 SourceLocation L;
1228 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1229 // FIXME: Return true in the case when other fields are used before being
1230 // uninitialized. For example, let this field be the i'th field. When
1231 // initializing the i'th field, throw a warning if any of the >= i'th
1232 // fields are used, as they are not yet initialized.
1233 // Right now we are only handling the case where the i'th field uses
1234 // itself in its initializer.
1235 Diag(L, diag::warn_field_is_uninit);
1236 }
1237 }
1238
Eli Friedman8e1433b2009-07-29 19:44:27 +00001239 bool HasDependentArg = false;
1240 for (unsigned i = 0; i < NumArgs; i++)
1241 HasDependentArg |= Args[i]->isTypeDependent();
1242
Eli Friedman9255adf2010-07-24 21:19:15 +00001243 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001244 // Can't check initialization for a member of dependent type or when
1245 // any of the arguments are type-dependent expressions.
John McCallb268a282010-08-23 23:25:46 +00001246 Expr *Init
1247 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1248 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001249
1250 // Erase any temporaries within this evaluation context; we're not
1251 // going to track them in the AST, since we'll be rebuilding the
1252 // ASTs during template instantiation.
1253 ExprTemporaries.erase(
1254 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1255 ExprTemporaries.end());
1256
1257 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1258 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001259 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001260 RParenLoc);
1261
Douglas Gregore8381c02008-11-05 04:29:56 +00001262 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001263
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001264 if (Member->isInvalidDecl())
1265 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001266
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001267 // Initialize the member.
1268 InitializedEntity MemberEntity =
1269 InitializedEntity::InitializeMember(Member, 0);
1270 InitializationKind Kind =
1271 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1272
1273 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1274
John McCalldadc5752010-08-24 06:29:42 +00001275 ExprResult MemberInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001276 InitSeq.Perform(*this, MemberEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001277 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001278 if (MemberInit.isInvalid())
1279 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001280
1281 CheckImplicitConversions(MemberInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001282
1283 // C++0x [class.base.init]p7:
1284 // The initialization of each base and member constitutes a
1285 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001286 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001287 if (MemberInit.isInvalid())
1288 return true;
1289
1290 // If we are in a dependent context, template instantiation will
1291 // perform this type-checking again. Just save the arguments that we
1292 // received in a ParenListExpr.
1293 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1294 // of the information that we have about the member
1295 // initializer. However, deconstructing the ASTs is a dicey process,
1296 // and this approach is far more likely to get the corner cases right.
1297 if (CurContext->isDependentContext()) {
1298 // Bump the reference count of all of the arguments.
1299 for (unsigned I = 0; I != NumArgs; ++I)
1300 Args[I]->Retain();
1301
John McCallb268a282010-08-23 23:25:46 +00001302 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1303 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001304 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1305 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001306 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001307 RParenLoc);
1308 }
1309
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001310 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001311 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001312 MemberInit.get(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001313 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001314}
1315
John McCallfaf5fb42010-08-26 23:41:50 +00001316MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001317Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001318 Expr **Args, unsigned NumArgs,
1319 SourceLocation LParenLoc, SourceLocation RParenLoc,
1320 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001321 bool HasDependentArg = false;
1322 for (unsigned i = 0; i < NumArgs; i++)
1323 HasDependentArg |= Args[i]->isTypeDependent();
1324
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001325 SourceLocation BaseLoc
1326 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1327
1328 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1329 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1330 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1331
1332 // C++ [class.base.init]p2:
1333 // [...] Unless the mem-initializer-id names a nonstatic data
1334 // member of the constructor’s class or a direct or virtual base
1335 // of that class, the mem-initializer is ill-formed. A
1336 // mem-initializer-list can initialize a base class using any
1337 // name that denotes that base class type.
1338 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1339
1340 // Check for direct and virtual base classes.
1341 const CXXBaseSpecifier *DirectBaseSpec = 0;
1342 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1343 if (!Dependent) {
1344 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1345 VirtualBaseSpec);
1346
1347 // C++ [base.class.init]p2:
1348 // Unless the mem-initializer-id names a nonstatic data member of the
1349 // constructor's class or a direct or virtual base of that class, the
1350 // mem-initializer is ill-formed.
1351 if (!DirectBaseSpec && !VirtualBaseSpec) {
1352 // If the class has any dependent bases, then it's possible that
1353 // one of those types will resolve to the same type as
1354 // BaseType. Therefore, just treat this as a dependent base
1355 // class initialization. FIXME: Should we try to check the
1356 // initialization anyway? It seems odd.
1357 if (ClassDecl->hasAnyDependentBases())
1358 Dependent = true;
1359 else
1360 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1361 << BaseType << Context.getTypeDeclType(ClassDecl)
1362 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1363 }
1364 }
1365
1366 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001367 // Can't check initialization for a base of dependent type or when
1368 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001369 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001370 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1371 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001372
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001373 // Erase any temporaries within this evaluation context; we're not
1374 // going to track them in the AST, since we'll be rebuilding the
1375 // ASTs during template instantiation.
1376 ExprTemporaries.erase(
1377 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1378 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001379
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001380 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001381 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001382 LParenLoc,
1383 BaseInit.takeAs<Expr>(),
1384 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001385 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001386
1387 // C++ [base.class.init]p2:
1388 // If a mem-initializer-id is ambiguous because it designates both
1389 // a direct non-virtual base class and an inherited virtual base
1390 // class, the mem-initializer is ill-formed.
1391 if (DirectBaseSpec && VirtualBaseSpec)
1392 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001393 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001394
1395 CXXBaseSpecifier *BaseSpec
1396 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1397 if (!BaseSpec)
1398 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1399
1400 // Initialize the base.
1401 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001402 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001403 InitializationKind Kind =
1404 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1405
1406 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1407
John McCalldadc5752010-08-24 06:29:42 +00001408 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001409 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001410 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001411 if (BaseInit.isInvalid())
1412 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001413
1414 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415
1416 // C++0x [class.base.init]p7:
1417 // The initialization of each base and member constitutes a
1418 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001419 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001420 if (BaseInit.isInvalid())
1421 return true;
1422
1423 // If we are in a dependent context, template instantiation will
1424 // perform this type-checking again. Just save the arguments that we
1425 // received in a ParenListExpr.
1426 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1427 // of the information that we have about the base
1428 // initializer. However, deconstructing the ASTs is a dicey process,
1429 // and this approach is far more likely to get the corner cases right.
1430 if (CurContext->isDependentContext()) {
1431 // Bump the reference count of all of the arguments.
1432 for (unsigned I = 0; I != NumArgs; ++I)
1433 Args[I]->Retain();
1434
John McCalldadc5752010-08-24 06:29:42 +00001435 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001436 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1437 RParenLoc));
1438 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001439 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001440 LParenLoc,
1441 Init.takeAs<Expr>(),
1442 RParenLoc);
1443 }
1444
1445 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001446 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001447 LParenLoc,
1448 BaseInit.takeAs<Expr>(),
1449 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001450}
1451
Anders Carlsson1b00e242010-04-23 03:10:23 +00001452/// ImplicitInitializerKind - How an implicit base or member initializer should
1453/// initialize its base or member.
1454enum ImplicitInitializerKind {
1455 IIK_Default,
1456 IIK_Copy,
1457 IIK_Move
1458};
1459
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001460static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001461BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001462 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001463 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001464 bool IsInheritedVirtualBase,
1465 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001466 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001467 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1468 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001469
John McCalldadc5752010-08-24 06:29:42 +00001470 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001471
1472 switch (ImplicitInitKind) {
1473 case IIK_Default: {
1474 InitializationKind InitKind
1475 = InitializationKind::CreateDefault(Constructor->getLocation());
1476 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1477 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001478 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001479 break;
1480 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001481
Anders Carlsson1b00e242010-04-23 03:10:23 +00001482 case IIK_Copy: {
1483 ParmVarDecl *Param = Constructor->getParamDecl(0);
1484 QualType ParamType = Param->getType().getNonReferenceType();
1485
1486 Expr *CopyCtorArg =
1487 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001488 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001489
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001490 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001491 QualType ArgTy =
1492 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1493 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001494
1495 CXXCastPath BasePath;
1496 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001497 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001498 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001499 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001500
Anders Carlsson1b00e242010-04-23 03:10:23 +00001501 InitializationKind InitKind
1502 = InitializationKind::CreateDirect(Constructor->getLocation(),
1503 SourceLocation(), SourceLocation());
1504 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1505 &CopyCtorArg, 1);
1506 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001507 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001508 break;
1509 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001510
Anders Carlsson1b00e242010-04-23 03:10:23 +00001511 case IIK_Move:
1512 assert(false && "Unhandled initializer kind!");
1513 }
John McCallb268a282010-08-23 23:25:46 +00001514
1515 if (BaseInit.isInvalid())
1516 return true;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001517
John McCallb268a282010-08-23 23:25:46 +00001518 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001519 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001520 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001521
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001522 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001523 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1524 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1525 SourceLocation()),
1526 BaseSpec->isVirtual(),
1527 SourceLocation(),
1528 BaseInit.takeAs<Expr>(),
1529 SourceLocation());
1530
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001531 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001532}
1533
Anders Carlsson3c1db572010-04-23 02:15:47 +00001534static bool
1535BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001536 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001537 FieldDecl *Field,
1538 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001539 if (Field->isInvalidDecl())
1540 return true;
1541
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001542 SourceLocation Loc = Constructor->getLocation();
1543
Anders Carlsson423f5d82010-04-23 16:04:08 +00001544 if (ImplicitInitKind == IIK_Copy) {
1545 ParmVarDecl *Param = Constructor->getParamDecl(0);
1546 QualType ParamType = Param->getType().getNonReferenceType();
1547
1548 Expr *MemberExprBase =
1549 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001550 Loc, ParamType, 0);
1551
1552 // Build a reference to this field within the parameter.
1553 CXXScopeSpec SS;
1554 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1555 Sema::LookupMemberName);
1556 MemberLookup.addDecl(Field, AS_public);
1557 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001558 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001559 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001560 ParamType, Loc,
1561 /*IsArrow=*/false,
1562 SS,
1563 /*FirstQualifierInScope=*/0,
1564 MemberLookup,
1565 /*TemplateArgs=*/0);
1566 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001567 return true;
1568
Douglas Gregor94f9a482010-05-05 05:51:00 +00001569 // When the field we are copying is an array, create index variables for
1570 // each dimension of the array. We use these index variables to subscript
1571 // the source array, and other clients (e.g., CodeGen) will perform the
1572 // necessary iteration with these index variables.
1573 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1574 QualType BaseType = Field->getType();
1575 QualType SizeType = SemaRef.Context.getSizeType();
1576 while (const ConstantArrayType *Array
1577 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1578 // Create the iteration variable for this array index.
1579 IdentifierInfo *IterationVarName = 0;
1580 {
1581 llvm::SmallString<8> Str;
1582 llvm::raw_svector_ostream OS(Str);
1583 OS << "__i" << IndexVariables.size();
1584 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1585 }
1586 VarDecl *IterationVar
1587 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1588 IterationVarName, SizeType,
1589 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001590 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001591 IndexVariables.push_back(IterationVar);
1592
1593 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001594 ExprResult IterationVarRef
Douglas Gregor94f9a482010-05-05 05:51:00 +00001595 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1596 assert(!IterationVarRef.isInvalid() &&
1597 "Reference to invented variable cannot fail!");
1598
1599 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001600 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001601 Loc,
John McCallb268a282010-08-23 23:25:46 +00001602 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001603 Loc);
1604 if (CopyCtorArg.isInvalid())
1605 return true;
1606
1607 BaseType = Array->getElementType();
1608 }
1609
1610 // Construct the entity that we will be initializing. For an array, this
1611 // will be first element in the array, which may require several levels
1612 // of array-subscript entities.
1613 llvm::SmallVector<InitializedEntity, 4> Entities;
1614 Entities.reserve(1 + IndexVariables.size());
1615 Entities.push_back(InitializedEntity::InitializeMember(Field));
1616 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1617 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1618 0,
1619 Entities.back()));
1620
1621 // Direct-initialize to use the copy constructor.
1622 InitializationKind InitKind =
1623 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1624
1625 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1626 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1627 &CopyCtorArgE, 1);
1628
John McCalldadc5752010-08-24 06:29:42 +00001629 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001630 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001631 MultiExprArg(&CopyCtorArgE, 1));
John McCallb268a282010-08-23 23:25:46 +00001632 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor94f9a482010-05-05 05:51:00 +00001633 if (MemberInit.isInvalid())
1634 return true;
1635
1636 CXXMemberInit
1637 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1638 MemberInit.takeAs<Expr>(), Loc,
1639 IndexVariables.data(),
1640 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001641 return false;
1642 }
1643
Anders Carlsson423f5d82010-04-23 16:04:08 +00001644 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1645
Anders Carlsson3c1db572010-04-23 02:15:47 +00001646 QualType FieldBaseElementType =
1647 SemaRef.Context.getBaseElementType(Field->getType());
1648
Anders Carlsson3c1db572010-04-23 02:15:47 +00001649 if (FieldBaseElementType->isRecordType()) {
1650 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001651 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001652 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001653
1654 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001655 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001656 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001657 if (MemberInit.isInvalid())
1658 return true;
1659
1660 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001661 if (MemberInit.isInvalid())
1662 return true;
1663
1664 CXXMemberInit =
1665 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001666 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001667 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001668 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001669 return false;
1670 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001671
1672 if (FieldBaseElementType->isReferenceType()) {
1673 SemaRef.Diag(Constructor->getLocation(),
1674 diag::err_uninitialized_member_in_ctor)
1675 << (int)Constructor->isImplicit()
1676 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1677 << 0 << Field->getDeclName();
1678 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1679 return true;
1680 }
1681
1682 if (FieldBaseElementType.isConstQualified()) {
1683 SemaRef.Diag(Constructor->getLocation(),
1684 diag::err_uninitialized_member_in_ctor)
1685 << (int)Constructor->isImplicit()
1686 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1687 << 1 << Field->getDeclName();
1688 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1689 return true;
1690 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001691
1692 // Nothing to initialize.
1693 CXXMemberInit = 0;
1694 return false;
1695}
John McCallbc83b3f2010-05-20 23:23:51 +00001696
1697namespace {
1698struct BaseAndFieldInfo {
1699 Sema &S;
1700 CXXConstructorDecl *Ctor;
1701 bool AnyErrorsInInits;
1702 ImplicitInitializerKind IIK;
1703 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1704 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1705
1706 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1707 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1708 // FIXME: Handle implicit move constructors.
1709 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1710 IIK = IIK_Copy;
1711 else
1712 IIK = IIK_Default;
1713 }
1714};
1715}
1716
Chandler Carruth139e9622010-06-30 02:59:29 +00001717static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1718 FieldDecl *Top, FieldDecl *Field,
1719 CXXBaseOrMemberInitializer *Init) {
1720 // If the member doesn't need to be initialized, Init will still be null.
1721 if (!Init)
1722 return;
1723
1724 Info.AllToInit.push_back(Init);
1725 if (Field != Top) {
1726 Init->setMember(Top);
1727 Init->setAnonUnionMember(Field);
1728 }
1729}
1730
John McCallbc83b3f2010-05-20 23:23:51 +00001731static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1732 FieldDecl *Top, FieldDecl *Field) {
1733
Chandler Carruth139e9622010-06-30 02:59:29 +00001734 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001735 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001736 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001737 return false;
1738 }
1739
1740 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1741 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1742 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001743 CXXRecordDecl *FieldClassDecl
1744 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001745
1746 // Even though union members never have non-trivial default
1747 // constructions in C++03, we still build member initializers for aggregate
1748 // record types which can be union members, and C++0x allows non-trivial
1749 // default constructors for union members, so we ensure that only one
1750 // member is initialized for these.
1751 if (FieldClassDecl->isUnion()) {
1752 // First check for an explicit initializer for one field.
1753 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1754 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1755 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1756 RecordFieldInitializer(Info, Top, *FA, Init);
1757
1758 // Once we've initialized a field of an anonymous union, the union
1759 // field in the class is also initialized, so exit immediately.
1760 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001761 } else if ((*FA)->isAnonymousStructOrUnion()) {
1762 if (CollectFieldInitializer(Info, Top, *FA))
1763 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001764 }
1765 }
1766
1767 // Fallthrough and construct a default initializer for the union as
1768 // a whole, which can call its default constructor if such a thing exists
1769 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1770 // behavior going forward with C++0x, when anonymous unions there are
1771 // finalized, we should revisit this.
1772 } else {
1773 // For structs, we simply descend through to initialize all members where
1774 // necessary.
1775 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1776 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1777 if (CollectFieldInitializer(Info, Top, *FA))
1778 return true;
1779 }
1780 }
John McCallbc83b3f2010-05-20 23:23:51 +00001781 }
1782
1783 // Don't try to build an implicit initializer if there were semantic
1784 // errors in any of the initializers (and therefore we might be
1785 // missing some that the user actually wrote).
1786 if (Info.AnyErrorsInInits)
1787 return false;
1788
1789 CXXBaseOrMemberInitializer *Init = 0;
1790 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1791 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001792
Chandler Carruth139e9622010-06-30 02:59:29 +00001793 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001794 return false;
1795}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001796
Eli Friedman9cf6b592009-11-09 19:20:36 +00001797bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001798Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001799 CXXBaseOrMemberInitializer **Initializers,
1800 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001801 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001802 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001803 // Just store the initializers as written, they will be checked during
1804 // instantiation.
1805 if (NumInitializers > 0) {
1806 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1807 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1808 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1809 memcpy(baseOrMemberInitializers, Initializers,
1810 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1811 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1812 }
1813
1814 return false;
1815 }
1816
John McCallbc83b3f2010-05-20 23:23:51 +00001817 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001818
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001819 // We need to build the initializer AST according to order of construction
1820 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001821 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001822 if (!ClassDecl)
1823 return true;
1824
Eli Friedman9cf6b592009-11-09 19:20:36 +00001825 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001826
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001827 for (unsigned i = 0; i < NumInitializers; i++) {
1828 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001829
1830 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001831 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001832 else
John McCallbc83b3f2010-05-20 23:23:51 +00001833 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001834 }
1835
Anders Carlsson43c64af2010-04-21 19:52:01 +00001836 // Keep track of the direct virtual bases.
1837 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1838 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1839 E = ClassDecl->bases_end(); I != E; ++I) {
1840 if (I->isVirtual())
1841 DirectVBases.insert(I);
1842 }
1843
Anders Carlssondb0a9652010-04-02 06:26:44 +00001844 // Push virtual bases before others.
1845 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1846 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1847
1848 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001849 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1850 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001851 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001852 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001853 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001854 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001855 VBase, IsInheritedVirtualBase,
1856 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001857 HadError = true;
1858 continue;
1859 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001860
John McCallbc83b3f2010-05-20 23:23:51 +00001861 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001862 }
1863 }
Mike Stump11289f42009-09-09 15:08:12 +00001864
John McCallbc83b3f2010-05-20 23:23:51 +00001865 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001866 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1867 E = ClassDecl->bases_end(); Base != E; ++Base) {
1868 // Virtuals are in the virtual base list and already constructed.
1869 if (Base->isVirtual())
1870 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001871
Anders Carlssondb0a9652010-04-02 06:26:44 +00001872 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001873 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1874 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001875 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001876 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001877 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001878 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001879 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001880 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001881 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001882 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001883
John McCallbc83b3f2010-05-20 23:23:51 +00001884 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001885 }
1886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
John McCallbc83b3f2010-05-20 23:23:51 +00001888 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001889 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001890 E = ClassDecl->field_end(); Field != E; ++Field) {
1891 if ((*Field)->getType()->isIncompleteArrayType()) {
1892 assert(ClassDecl->hasFlexibleArrayMember() &&
1893 "Incomplete array type is not valid");
1894 continue;
1895 }
John McCallbc83b3f2010-05-20 23:23:51 +00001896 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001897 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001898 }
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCallbc83b3f2010-05-20 23:23:51 +00001900 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001901 if (NumInitializers > 0) {
1902 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1903 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1904 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001905 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001906 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001907 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001908
John McCalla6309952010-03-16 21:39:52 +00001909 // Constructors implicitly reference the base and member
1910 // destructors.
1911 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1912 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001913 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001914
1915 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001916}
1917
Eli Friedman952c15d2009-07-21 19:28:10 +00001918static void *GetKeyForTopLevelField(FieldDecl *Field) {
1919 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001920 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001921 if (RT->getDecl()->isAnonymousStructOrUnion())
1922 return static_cast<void *>(RT->getDecl());
1923 }
1924 return static_cast<void *>(Field);
1925}
1926
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001927static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1928 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001929}
1930
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001931static void *GetKeyForMember(ASTContext &Context,
1932 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001933 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001934 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001935 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001936
Eli Friedman952c15d2009-07-21 19:28:10 +00001937 // For fields injected into the class via declaration of an anonymous union,
1938 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001939 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001940
Anders Carlssona942dcd2010-03-30 15:39:27 +00001941 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1942 // data member of the class. Data member used in the initializer list is
1943 // in AnonUnionMember field.
1944 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1945 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001946
John McCall23eebd92010-04-10 09:28:51 +00001947 // If the field is a member of an anonymous struct or union, our key
1948 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001949 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001950 if (RD->isAnonymousStructOrUnion()) {
1951 while (true) {
1952 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1953 if (Parent->isAnonymousStructOrUnion())
1954 RD = Parent;
1955 else
1956 break;
1957 }
1958
Anders Carlsson83ac3122010-03-30 16:19:37 +00001959 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001960 }
Mike Stump11289f42009-09-09 15:08:12 +00001961
Anders Carlssona942dcd2010-03-30 15:39:27 +00001962 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001963}
1964
Anders Carlssone857b292010-04-02 03:37:03 +00001965static void
1966DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001967 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001968 CXXBaseOrMemberInitializer **Inits,
1969 unsigned NumInits) {
1970 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001971 return;
Mike Stump11289f42009-09-09 15:08:12 +00001972
John McCallbb7b6582010-04-10 07:37:23 +00001973 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1974 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001975 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001976
John McCallbb7b6582010-04-10 07:37:23 +00001977 // Build the list of bases and members in the order that they'll
1978 // actually be initialized. The explicit initializers should be in
1979 // this same order but may be missing things.
1980 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001982 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1983
John McCallbb7b6582010-04-10 07:37:23 +00001984 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001985 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001986 ClassDecl->vbases_begin(),
1987 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001988 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001989
John McCallbb7b6582010-04-10 07:37:23 +00001990 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001991 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001992 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001993 if (Base->isVirtual())
1994 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001995 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
John McCallbb7b6582010-04-10 07:37:23 +00001998 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001999 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2000 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002001 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002002
John McCallbb7b6582010-04-10 07:37:23 +00002003 unsigned NumIdealInits = IdealInitKeys.size();
2004 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002005
John McCallbb7b6582010-04-10 07:37:23 +00002006 CXXBaseOrMemberInitializer *PrevInit = 0;
2007 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2008 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2009 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2010
2011 // Scan forward to try to find this initializer in the idealized
2012 // initializers list.
2013 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2014 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002015 break;
John McCallbb7b6582010-04-10 07:37:23 +00002016
2017 // If we didn't find this initializer, it must be because we
2018 // scanned past it on a previous iteration. That can only
2019 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002020 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002021 Sema::SemaDiagnosticBuilder D =
2022 SemaRef.Diag(PrevInit->getSourceLocation(),
2023 diag::warn_initializer_out_of_order);
2024
2025 if (PrevInit->isMemberInitializer())
2026 D << 0 << PrevInit->getMember()->getDeclName();
2027 else
2028 D << 1 << PrevInit->getBaseClassInfo()->getType();
2029
2030 if (Init->isMemberInitializer())
2031 D << 0 << Init->getMember()->getDeclName();
2032 else
2033 D << 1 << Init->getBaseClassInfo()->getType();
2034
2035 // Move back to the initializer's location in the ideal list.
2036 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2037 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002038 break;
John McCallbb7b6582010-04-10 07:37:23 +00002039
2040 assert(IdealIndex != NumIdealInits &&
2041 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002042 }
John McCallbb7b6582010-04-10 07:37:23 +00002043
2044 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002045 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002046}
2047
John McCall23eebd92010-04-10 09:28:51 +00002048namespace {
2049bool CheckRedundantInit(Sema &S,
2050 CXXBaseOrMemberInitializer *Init,
2051 CXXBaseOrMemberInitializer *&PrevInit) {
2052 if (!PrevInit) {
2053 PrevInit = Init;
2054 return false;
2055 }
2056
2057 if (FieldDecl *Field = Init->getMember())
2058 S.Diag(Init->getSourceLocation(),
2059 diag::err_multiple_mem_initialization)
2060 << Field->getDeclName()
2061 << Init->getSourceRange();
2062 else {
2063 Type *BaseClass = Init->getBaseClass();
2064 assert(BaseClass && "neither field nor base");
2065 S.Diag(Init->getSourceLocation(),
2066 diag::err_multiple_base_initialization)
2067 << QualType(BaseClass, 0)
2068 << Init->getSourceRange();
2069 }
2070 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2071 << 0 << PrevInit->getSourceRange();
2072
2073 return true;
2074}
2075
2076typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2077typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2078
2079bool CheckRedundantUnionInit(Sema &S,
2080 CXXBaseOrMemberInitializer *Init,
2081 RedundantUnionMap &Unions) {
2082 FieldDecl *Field = Init->getMember();
2083 RecordDecl *Parent = Field->getParent();
2084 if (!Parent->isAnonymousStructOrUnion())
2085 return false;
2086
2087 NamedDecl *Child = Field;
2088 do {
2089 if (Parent->isUnion()) {
2090 UnionEntry &En = Unions[Parent];
2091 if (En.first && En.first != Child) {
2092 S.Diag(Init->getSourceLocation(),
2093 diag::err_multiple_mem_union_initialization)
2094 << Field->getDeclName()
2095 << Init->getSourceRange();
2096 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2097 << 0 << En.second->getSourceRange();
2098 return true;
2099 } else if (!En.first) {
2100 En.first = Child;
2101 En.second = Init;
2102 }
2103 }
2104
2105 Child = Parent;
2106 Parent = cast<RecordDecl>(Parent->getDeclContext());
2107 } while (Parent->isAnonymousStructOrUnion());
2108
2109 return false;
2110}
2111}
2112
Anders Carlssone857b292010-04-02 03:37:03 +00002113/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002114void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002115 SourceLocation ColonLoc,
2116 MemInitTy **meminits, unsigned NumMemInits,
2117 bool AnyErrors) {
2118 if (!ConstructorDecl)
2119 return;
2120
2121 AdjustDeclIfTemplate(ConstructorDecl);
2122
2123 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002124 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002125
2126 if (!Constructor) {
2127 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2128 return;
2129 }
2130
2131 CXXBaseOrMemberInitializer **MemInits =
2132 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002133
2134 // Mapping for the duplicate initializers check.
2135 // For member initializers, this is keyed with a FieldDecl*.
2136 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002137 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002138
2139 // Mapping for the inconsistent anonymous-union initializers check.
2140 RedundantUnionMap MemberUnions;
2141
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002142 bool HadError = false;
2143 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002144 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002145
Abramo Bagnara341d7832010-05-26 18:09:23 +00002146 // Set the source order index.
2147 Init->setSourceOrder(i);
2148
John McCall23eebd92010-04-10 09:28:51 +00002149 if (Init->isMemberInitializer()) {
2150 FieldDecl *Field = Init->getMember();
2151 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2152 CheckRedundantUnionInit(*this, Init, MemberUnions))
2153 HadError = true;
2154 } else {
2155 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2156 if (CheckRedundantInit(*this, Init, Members[Key]))
2157 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002158 }
Anders Carlssone857b292010-04-02 03:37:03 +00002159 }
2160
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002161 if (HadError)
2162 return;
2163
Anders Carlssone857b292010-04-02 03:37:03 +00002164 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002165
2166 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002167}
2168
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002169void
John McCalla6309952010-03-16 21:39:52 +00002170Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2171 CXXRecordDecl *ClassDecl) {
2172 // Ignore dependent contexts.
2173 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002174 return;
John McCall1064d7e2010-03-16 05:22:47 +00002175
2176 // FIXME: all the access-control diagnostics are positioned on the
2177 // field/base declaration. That's probably good; that said, the
2178 // user might reasonably want to know why the destructor is being
2179 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002180
Anders Carlssondee9a302009-11-17 04:44:12 +00002181 // Non-static data members.
2182 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2183 E = ClassDecl->field_end(); I != E; ++I) {
2184 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002185 if (Field->isInvalidDecl())
2186 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002187 QualType FieldType = Context.getBaseElementType(Field->getType());
2188
2189 const RecordType* RT = FieldType->getAs<RecordType>();
2190 if (!RT)
2191 continue;
2192
2193 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2194 if (FieldClassDecl->hasTrivialDestructor())
2195 continue;
2196
Douglas Gregore71edda2010-07-01 22:47:18 +00002197 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002198 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002199 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002200 << Field->getDeclName()
2201 << FieldType);
2202
John McCalla6309952010-03-16 21:39:52 +00002203 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002204 }
2205
John McCall1064d7e2010-03-16 05:22:47 +00002206 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2207
Anders Carlssondee9a302009-11-17 04:44:12 +00002208 // Bases.
2209 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2210 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002211 // Bases are always records in a well-formed non-dependent class.
2212 const RecordType *RT = Base->getType()->getAs<RecordType>();
2213
2214 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002215 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002216 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002217
2218 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002219 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002220 if (BaseClassDecl->hasTrivialDestructor())
2221 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002222
Douglas Gregore71edda2010-07-01 22:47:18 +00002223 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002224
2225 // FIXME: caret should be on the start of the class name
2226 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002227 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002228 << Base->getType()
2229 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002230
John McCalla6309952010-03-16 21:39:52 +00002231 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002232 }
2233
2234 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002235 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2236 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002237
2238 // Bases are always records in a well-formed non-dependent class.
2239 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2240
2241 // Ignore direct virtual bases.
2242 if (DirectVirtualBases.count(RT))
2243 continue;
2244
Anders Carlssondee9a302009-11-17 04:44:12 +00002245 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002246 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002247 if (BaseClassDecl->hasTrivialDestructor())
2248 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002249
Douglas Gregore71edda2010-07-01 22:47:18 +00002250 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002251 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002252 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002253 << VBase->getType());
2254
John McCalla6309952010-03-16 21:39:52 +00002255 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002256 }
2257}
2258
John McCall48871652010-08-21 09:40:31 +00002259void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002260 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002261 return;
Mike Stump11289f42009-09-09 15:08:12 +00002262
Mike Stump11289f42009-09-09 15:08:12 +00002263 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002264 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002265 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002266}
2267
Mike Stump11289f42009-09-09 15:08:12 +00002268bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002269 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002270 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002271 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002272 else
John McCall02db245d2010-08-18 09:41:07 +00002273 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002274}
2275
Anders Carlssoneabf7702009-08-27 00:13:57 +00002276bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002277 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002278 if (!getLangOptions().CPlusPlus)
2279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002280
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002281 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002282 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002283
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002284 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002285 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002286 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002287 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002288
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002289 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002290 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002291 }
Mike Stump11289f42009-09-09 15:08:12 +00002292
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002293 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002294 if (!RT)
2295 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002296
John McCall67da35c2010-02-04 22:26:26 +00002297 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002298
John McCall02db245d2010-08-18 09:41:07 +00002299 // We can't answer whether something is abstract until it has a
2300 // definition. If it's currently being defined, we'll walk back
2301 // over all the declarations when we have a full definition.
2302 const CXXRecordDecl *Def = RD->getDefinition();
2303 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002304 return false;
2305
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002306 if (!RD->isAbstract())
2307 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002308
Anders Carlssoneabf7702009-08-27 00:13:57 +00002309 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002310 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002311
John McCall02db245d2010-08-18 09:41:07 +00002312 return true;
2313}
2314
2315void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2316 // Check if we've already emitted the list of pure virtual functions
2317 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002318 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002319 return;
Mike Stump11289f42009-09-09 15:08:12 +00002320
Douglas Gregor4165bd62010-03-23 23:47:56 +00002321 CXXFinalOverriderMap FinalOverriders;
2322 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002323
Anders Carlssona2f74f32010-06-03 01:00:02 +00002324 // Keep a set of seen pure methods so we won't diagnose the same method
2325 // more than once.
2326 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2327
Douglas Gregor4165bd62010-03-23 23:47:56 +00002328 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2329 MEnd = FinalOverriders.end();
2330 M != MEnd;
2331 ++M) {
2332 for (OverridingMethods::iterator SO = M->second.begin(),
2333 SOEnd = M->second.end();
2334 SO != SOEnd; ++SO) {
2335 // C++ [class.abstract]p4:
2336 // A class is abstract if it contains or inherits at least one
2337 // pure virtual function for which the final overrider is pure
2338 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002339
Douglas Gregor4165bd62010-03-23 23:47:56 +00002340 //
2341 if (SO->second.size() != 1)
2342 continue;
2343
2344 if (!SO->second.front().Method->isPure())
2345 continue;
2346
Anders Carlssona2f74f32010-06-03 01:00:02 +00002347 if (!SeenPureMethods.insert(SO->second.front().Method))
2348 continue;
2349
Douglas Gregor4165bd62010-03-23 23:47:56 +00002350 Diag(SO->second.front().Method->getLocation(),
2351 diag::note_pure_virtual_function)
2352 << SO->second.front().Method->getDeclName();
2353 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002354 }
2355
2356 if (!PureVirtualClassDiagSet)
2357 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2358 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002359}
2360
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002361namespace {
John McCall02db245d2010-08-18 09:41:07 +00002362struct AbstractUsageInfo {
2363 Sema &S;
2364 CXXRecordDecl *Record;
2365 CanQualType AbstractType;
2366 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002367
John McCall02db245d2010-08-18 09:41:07 +00002368 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2369 : S(S), Record(Record),
2370 AbstractType(S.Context.getCanonicalType(
2371 S.Context.getTypeDeclType(Record))),
2372 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002373
John McCall02db245d2010-08-18 09:41:07 +00002374 void DiagnoseAbstractType() {
2375 if (Invalid) return;
2376 S.DiagnoseAbstractType(Record);
2377 Invalid = true;
2378 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002379
John McCall02db245d2010-08-18 09:41:07 +00002380 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2381};
2382
2383struct CheckAbstractUsage {
2384 AbstractUsageInfo &Info;
2385 const NamedDecl *Ctx;
2386
2387 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2388 : Info(Info), Ctx(Ctx) {}
2389
2390 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2391 switch (TL.getTypeLocClass()) {
2392#define ABSTRACT_TYPELOC(CLASS, PARENT)
2393#define TYPELOC(CLASS, PARENT) \
2394 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2395#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002396 }
John McCall02db245d2010-08-18 09:41:07 +00002397 }
Mike Stump11289f42009-09-09 15:08:12 +00002398
John McCall02db245d2010-08-18 09:41:07 +00002399 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2400 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2401 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2402 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2403 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002404 }
John McCall02db245d2010-08-18 09:41:07 +00002405 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002406
John McCall02db245d2010-08-18 09:41:07 +00002407 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2408 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2409 }
Mike Stump11289f42009-09-09 15:08:12 +00002410
John McCall02db245d2010-08-18 09:41:07 +00002411 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2412 // Visit the type parameters from a permissive context.
2413 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2414 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2415 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2416 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2417 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2418 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002419 }
John McCall02db245d2010-08-18 09:41:07 +00002420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
John McCall02db245d2010-08-18 09:41:07 +00002422 // Visit pointee types from a permissive context.
2423#define CheckPolymorphic(Type) \
2424 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2425 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2426 }
2427 CheckPolymorphic(PointerTypeLoc)
2428 CheckPolymorphic(ReferenceTypeLoc)
2429 CheckPolymorphic(MemberPointerTypeLoc)
2430 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002431
John McCall02db245d2010-08-18 09:41:07 +00002432 /// Handle all the types we haven't given a more specific
2433 /// implementation for above.
2434 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2435 // Every other kind of type that we haven't called out already
2436 // that has an inner type is either (1) sugar or (2) contains that
2437 // inner type in some way as a subobject.
2438 if (TypeLoc Next = TL.getNextTypeLoc())
2439 return Visit(Next, Sel);
2440
2441 // If there's no inner type and we're in a permissive context,
2442 // don't diagnose.
2443 if (Sel == Sema::AbstractNone) return;
2444
2445 // Check whether the type matches the abstract type.
2446 QualType T = TL.getType();
2447 if (T->isArrayType()) {
2448 Sel = Sema::AbstractArrayType;
2449 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002450 }
John McCall02db245d2010-08-18 09:41:07 +00002451 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2452 if (CT != Info.AbstractType) return;
2453
2454 // It matched; do some magic.
2455 if (Sel == Sema::AbstractArrayType) {
2456 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2457 << T << TL.getSourceRange();
2458 } else {
2459 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2460 << Sel << T << TL.getSourceRange();
2461 }
2462 Info.DiagnoseAbstractType();
2463 }
2464};
2465
2466void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2467 Sema::AbstractDiagSelID Sel) {
2468 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2469}
2470
2471}
2472
2473/// Check for invalid uses of an abstract type in a method declaration.
2474static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2475 CXXMethodDecl *MD) {
2476 // No need to do the check on definitions, which require that
2477 // the return/param types be complete.
2478 if (MD->isThisDeclarationADefinition())
2479 return;
2480
2481 // For safety's sake, just ignore it if we don't have type source
2482 // information. This should never happen for non-implicit methods,
2483 // but...
2484 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2485 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2486}
2487
2488/// Check for invalid uses of an abstract type within a class definition.
2489static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2490 CXXRecordDecl *RD) {
2491 for (CXXRecordDecl::decl_iterator
2492 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2493 Decl *D = *I;
2494 if (D->isImplicit()) continue;
2495
2496 // Methods and method templates.
2497 if (isa<CXXMethodDecl>(D)) {
2498 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2499 } else if (isa<FunctionTemplateDecl>(D)) {
2500 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2501 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2502
2503 // Fields and static variables.
2504 } else if (isa<FieldDecl>(D)) {
2505 FieldDecl *FD = cast<FieldDecl>(D);
2506 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2507 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2508 } else if (isa<VarDecl>(D)) {
2509 VarDecl *VD = cast<VarDecl>(D);
2510 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2511 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2512
2513 // Nested classes and class templates.
2514 } else if (isa<CXXRecordDecl>(D)) {
2515 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2516 } else if (isa<ClassTemplateDecl>(D)) {
2517 CheckAbstractClassUsage(Info,
2518 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2519 }
2520 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002521}
2522
Douglas Gregorc99f1552009-12-03 18:33:45 +00002523/// \brief Perform semantic checks on a class definition that has been
2524/// completing, introducing implicitly-declared members, checking for
2525/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002526void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002527 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002528 return;
2529
John McCall02db245d2010-08-18 09:41:07 +00002530 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2531 AbstractUsageInfo Info(*this, Record);
2532 CheckAbstractClassUsage(Info, Record);
2533 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002534
2535 // If this is not an aggregate type and has no user-declared constructor,
2536 // complain about any non-static data members of reference or const scalar
2537 // type, since they will never get initializers.
2538 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2539 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2540 bool Complained = false;
2541 for (RecordDecl::field_iterator F = Record->field_begin(),
2542 FEnd = Record->field_end();
2543 F != FEnd; ++F) {
2544 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002545 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002546 if (!Complained) {
2547 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2548 << Record->getTagKind() << Record;
2549 Complained = true;
2550 }
2551
2552 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2553 << F->getType()->isReferenceType()
2554 << F->getDeclName();
2555 }
2556 }
2557 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002558
2559 if (Record->isDynamicClass())
2560 DynamicClasses.push_back(Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002561}
2562
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002563void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002564 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002565 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002566 SourceLocation RBrac,
2567 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002568 if (!TagDecl)
2569 return;
Mike Stump11289f42009-09-09 15:08:12 +00002570
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002571 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002572
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002573 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002574 // strict aliasing violation!
2575 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002576 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002577
Douglas Gregor0be31a22010-07-02 17:43:08 +00002578 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002579 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002580}
2581
Douglas Gregor95755162010-07-01 05:10:53 +00002582namespace {
2583 /// \brief Helper class that collects exception specifications for
2584 /// implicitly-declared special member functions.
2585 class ImplicitExceptionSpecification {
2586 ASTContext &Context;
2587 bool AllowsAllExceptions;
2588 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2589 llvm::SmallVector<QualType, 4> Exceptions;
2590
2591 public:
2592 explicit ImplicitExceptionSpecification(ASTContext &Context)
2593 : Context(Context), AllowsAllExceptions(false) { }
2594
2595 /// \brief Whether the special member function should have any
2596 /// exception specification at all.
2597 bool hasExceptionSpecification() const {
2598 return !AllowsAllExceptions;
2599 }
2600
2601 /// \brief Whether the special member function should have a
2602 /// throw(...) exception specification (a Microsoft extension).
2603 bool hasAnyExceptionSpecification() const {
2604 return false;
2605 }
2606
2607 /// \brief The number of exceptions in the exception specification.
2608 unsigned size() const { return Exceptions.size(); }
2609
2610 /// \brief The set of exceptions in the exception specification.
2611 const QualType *data() const { return Exceptions.data(); }
2612
2613 /// \brief Note that
2614 void CalledDecl(CXXMethodDecl *Method) {
2615 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002616 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002617 return;
2618
2619 const FunctionProtoType *Proto
2620 = Method->getType()->getAs<FunctionProtoType>();
2621
2622 // If this function can throw any exceptions, make a note of that.
2623 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2624 AllowsAllExceptions = true;
2625 ExceptionsSeen.clear();
2626 Exceptions.clear();
2627 return;
2628 }
2629
2630 // Record the exceptions in this function's exception specification.
2631 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2632 EEnd = Proto->exception_end();
2633 E != EEnd; ++E)
2634 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2635 Exceptions.push_back(*E);
2636 }
2637 };
2638}
2639
2640
Douglas Gregor05379422008-11-03 17:51:48 +00002641/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2642/// special functions, such as the default constructor, copy
2643/// constructor, or destructor, to the given C++ class (C++
2644/// [special]p1). This routine can only be executed just before the
2645/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002646void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002647 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002648 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002649
Douglas Gregor54be3392010-07-01 17:57:27 +00002650 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002651 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002652
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002653 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2654 ++ASTContext::NumImplicitCopyAssignmentOperators;
2655
2656 // If we have a dynamic class, then the copy assignment operator may be
2657 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2658 // it shows up in the right place in the vtable and that we diagnose
2659 // problems with the implicit exception specification.
2660 if (ClassDecl->isDynamicClass())
2661 DeclareImplicitCopyAssignment(ClassDecl);
2662 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002663
Douglas Gregor7454c562010-07-02 20:37:36 +00002664 if (!ClassDecl->hasUserDeclaredDestructor()) {
2665 ++ASTContext::NumImplicitDestructors;
2666
2667 // If we have a dynamic class, then the destructor may be virtual, so we
2668 // have to declare the destructor immediately. This ensures that, e.g., it
2669 // shows up in the right place in the vtable and that we diagnose problems
2670 // with the implicit exception specification.
2671 if (ClassDecl->isDynamicClass())
2672 DeclareImplicitDestructor(ClassDecl);
2673 }
Douglas Gregor05379422008-11-03 17:51:48 +00002674}
2675
John McCall48871652010-08-21 09:40:31 +00002676void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002677 if (!D)
2678 return;
2679
2680 TemplateParameterList *Params = 0;
2681 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2682 Params = Template->getTemplateParameters();
2683 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2684 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2685 Params = PartialSpec->getTemplateParameters();
2686 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002687 return;
2688
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002689 for (TemplateParameterList::iterator Param = Params->begin(),
2690 ParamEnd = Params->end();
2691 Param != ParamEnd; ++Param) {
2692 NamedDecl *Named = cast<NamedDecl>(*Param);
2693 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002694 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002695 IdResolver.AddDecl(Named);
2696 }
2697 }
2698}
2699
John McCall48871652010-08-21 09:40:31 +00002700void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002701 if (!RecordD) return;
2702 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002703 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002704 PushDeclContext(S, Record);
2705}
2706
John McCall48871652010-08-21 09:40:31 +00002707void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002708 if (!RecordD) return;
2709 PopDeclContext();
2710}
2711
Douglas Gregor4d87df52008-12-16 21:30:33 +00002712/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2713/// parsing a top-level (non-nested) C++ class, and we are now
2714/// parsing those parts of the given Method declaration that could
2715/// not be parsed earlier (C++ [class.mem]p2), such as default
2716/// arguments. This action should enter the scope of the given
2717/// Method declaration as if we had just parsed the qualified method
2718/// name. However, it should not bring the parameters into scope;
2719/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002720void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002721}
2722
2723/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2724/// C++ method declaration. We're (re-)introducing the given
2725/// function parameter into scope for use in parsing later parts of
2726/// the method declaration. For example, we could see an
2727/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002728void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002729 if (!ParamD)
2730 return;
Mike Stump11289f42009-09-09 15:08:12 +00002731
John McCall48871652010-08-21 09:40:31 +00002732 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002733
2734 // If this parameter has an unparsed default argument, clear it out
2735 // to make way for the parsed default argument.
2736 if (Param->hasUnparsedDefaultArg())
2737 Param->setDefaultArg(0);
2738
John McCall48871652010-08-21 09:40:31 +00002739 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002740 if (Param->getDeclName())
2741 IdResolver.AddDecl(Param);
2742}
2743
2744/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2745/// processing the delayed method declaration for Method. The method
2746/// declaration is now considered finished. There may be a separate
2747/// ActOnStartOfFunctionDef action later (not necessarily
2748/// immediately!) for this method, if it was also defined inside the
2749/// class body.
John McCall48871652010-08-21 09:40:31 +00002750void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002751 if (!MethodD)
2752 return;
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002754 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002755
John McCall48871652010-08-21 09:40:31 +00002756 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002757
2758 // Now that we have our default arguments, check the constructor
2759 // again. It could produce additional diagnostics or affect whether
2760 // the class has implicitly-declared destructors, among other
2761 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002762 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2763 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002764
2765 // Check the default arguments, which we may have added.
2766 if (!Method->isInvalidDecl())
2767 CheckCXXDefaultArguments(Method);
2768}
2769
Douglas Gregor831c93f2008-11-05 20:51:48 +00002770/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002771/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002772/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002773/// emit diagnostics and set the invalid bit to true. In any case, the type
2774/// will be updated to reflect a well-formed type for the constructor and
2775/// returned.
2776QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002777 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002778 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002779
2780 // C++ [class.ctor]p3:
2781 // A constructor shall not be virtual (10.3) or static (9.4). A
2782 // constructor can be invoked for a const, volatile or const
2783 // volatile object. A constructor shall not be declared const,
2784 // volatile, or const volatile (9.3.2).
2785 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002786 if (!D.isInvalidType())
2787 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2788 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2789 << SourceRange(D.getIdentifierLoc());
2790 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002791 }
John McCall8e7d6562010-08-26 03:08:43 +00002792 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002793 if (!D.isInvalidType())
2794 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2795 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2796 << SourceRange(D.getIdentifierLoc());
2797 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002798 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002799 }
Mike Stump11289f42009-09-09 15:08:12 +00002800
Chris Lattner38378bf2009-04-25 08:28:21 +00002801 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2802 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002803 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002804 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2805 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002806 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002807 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2808 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002809 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002810 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2811 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002812 }
Mike Stump11289f42009-09-09 15:08:12 +00002813
Douglas Gregor831c93f2008-11-05 20:51:48 +00002814 // Rebuild the function type "R" without any type qualifiers (in
2815 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002816 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002817 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002818 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2819 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002820 Proto->isVariadic(), 0,
2821 Proto->hasExceptionSpec(),
2822 Proto->hasAnyExceptionSpec(),
2823 Proto->getNumExceptions(),
2824 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002825 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002826}
2827
Douglas Gregor4d87df52008-12-16 21:30:33 +00002828/// CheckConstructor - Checks a fully-formed constructor for
2829/// well-formedness, issuing any diagnostics required. Returns true if
2830/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002831void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002832 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002833 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2834 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002835 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002836
2837 // C++ [class.copy]p3:
2838 // A declaration of a constructor for a class X is ill-formed if
2839 // its first parameter is of type (optionally cv-qualified) X and
2840 // either there are no other parameters or else all other
2841 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002842 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002843 ((Constructor->getNumParams() == 1) ||
2844 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002845 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2846 Constructor->getTemplateSpecializationKind()
2847 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002848 QualType ParamType = Constructor->getParamDecl(0)->getType();
2849 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2850 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002851 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002852 const char *ConstRef
2853 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2854 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002855 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002856 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002857
2858 // FIXME: Rather that making the constructor invalid, we should endeavor
2859 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002860 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002861 }
2862 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002863}
2864
John McCalldeb646e2010-08-04 01:04:25 +00002865/// CheckDestructor - Checks a fully-formed destructor definition for
2866/// well-formedness, issuing any diagnostics required. Returns true
2867/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002868bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002869 CXXRecordDecl *RD = Destructor->getParent();
2870
2871 if (Destructor->isVirtual()) {
2872 SourceLocation Loc;
2873
2874 if (!Destructor->isImplicit())
2875 Loc = Destructor->getLocation();
2876 else
2877 Loc = RD->getLocation();
2878
2879 // If we have a virtual destructor, look up the deallocation function
2880 FunctionDecl *OperatorDelete = 0;
2881 DeclarationName Name =
2882 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002883 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002884 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002885
2886 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002887
2888 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002889 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002890
2891 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002892}
2893
Mike Stump11289f42009-09-09 15:08:12 +00002894static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002895FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2896 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2897 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002898 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002899}
2900
Douglas Gregor831c93f2008-11-05 20:51:48 +00002901/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2902/// the well-formednes of the destructor declarator @p D with type @p
2903/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002904/// emit diagnostics and set the declarator to invalid. Even if this happens,
2905/// will be updated to reflect a well-formed type for the destructor and
2906/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002907QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002908 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002909 // C++ [class.dtor]p1:
2910 // [...] A typedef-name that names a class is a class-name
2911 // (7.1.3); however, a typedef-name that names a class shall not
2912 // be used as the identifier in the declarator for a destructor
2913 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002914 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002915 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002916 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002917 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002918
2919 // C++ [class.dtor]p2:
2920 // A destructor is used to destroy objects of its class type. A
2921 // destructor takes no parameters, and no return type can be
2922 // specified for it (not even void). The address of a destructor
2923 // shall not be taken. A destructor shall not be static. A
2924 // destructor can be invoked for a const, volatile or const
2925 // volatile object. A destructor shall not be declared const,
2926 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002927 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002928 if (!D.isInvalidType())
2929 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2930 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002931 << SourceRange(D.getIdentifierLoc())
2932 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2933
John McCall8e7d6562010-08-26 03:08:43 +00002934 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002935 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002936 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002937 // Destructors don't have return types, but the parser will
2938 // happily parse something like:
2939 //
2940 // class X {
2941 // float ~X();
2942 // };
2943 //
2944 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002945 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2946 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2947 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002948 }
Mike Stump11289f42009-09-09 15:08:12 +00002949
Chris Lattner38378bf2009-04-25 08:28:21 +00002950 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2951 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002952 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002953 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2954 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002955 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002956 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2957 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002958 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002959 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2960 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002961 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002962 }
2963
2964 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002965 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002966 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2967
2968 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002969 FTI.freeArgs();
2970 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002971 }
2972
Mike Stump11289f42009-09-09 15:08:12 +00002973 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002974 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002975 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002976 D.setInvalidType();
2977 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002978
2979 // Rebuild the function type "R" without any type qualifiers or
2980 // parameters (in case any of the errors above fired) and with
2981 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00002982 // types.
2983 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2984 if (!Proto)
2985 return QualType();
2986
Douglas Gregor36c569f2010-02-21 22:15:06 +00002987 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00002988 Proto->hasExceptionSpec(),
2989 Proto->hasAnyExceptionSpec(),
2990 Proto->getNumExceptions(),
2991 Proto->exception_begin(),
2992 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002993}
2994
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002995/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2996/// well-formednes of the conversion function declarator @p D with
2997/// type @p R. If there are any errors in the declarator, this routine
2998/// will emit diagnostics and return true. Otherwise, it will return
2999/// false. Either way, the type @p R will be updated to reflect a
3000/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003001void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003002 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003003 // C++ [class.conv.fct]p1:
3004 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003005 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003006 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003007 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003008 if (!D.isInvalidType())
3009 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3010 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3011 << SourceRange(D.getIdentifierLoc());
3012 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003013 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003014 }
John McCall212fa2e2010-04-13 00:04:31 +00003015
3016 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3017
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003018 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003019 // Conversion functions don't have return types, but the parser will
3020 // happily parse something like:
3021 //
3022 // class X {
3023 // float operator bool();
3024 // };
3025 //
3026 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003027 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3028 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3029 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003030 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003031 }
3032
John McCall212fa2e2010-04-13 00:04:31 +00003033 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3034
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003035 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003036 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003037 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3038
3039 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003040 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003041 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003042 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003043 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003044 D.setInvalidType();
3045 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003046
John McCall212fa2e2010-04-13 00:04:31 +00003047 // Diagnose "&operator bool()" and other such nonsense. This
3048 // is actually a gcc extension which we don't support.
3049 if (Proto->getResultType() != ConvType) {
3050 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3051 << Proto->getResultType();
3052 D.setInvalidType();
3053 ConvType = Proto->getResultType();
3054 }
3055
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003056 // C++ [class.conv.fct]p4:
3057 // The conversion-type-id shall not represent a function type nor
3058 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003059 if (ConvType->isArrayType()) {
3060 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3061 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003062 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003063 } else if (ConvType->isFunctionType()) {
3064 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3065 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003066 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003067 }
3068
3069 // Rebuild the function type "R" without any parameters (in case any
3070 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003071 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003072 if (D.isInvalidType()) {
3073 R = Context.getFunctionType(ConvType, 0, 0, false,
3074 Proto->getTypeQuals(),
3075 Proto->hasExceptionSpec(),
3076 Proto->hasAnyExceptionSpec(),
3077 Proto->getNumExceptions(),
3078 Proto->exception_begin(),
3079 Proto->getExtInfo());
3080 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003081
Douglas Gregor5fb53972009-01-14 15:45:31 +00003082 // C++0x explicit conversion operators.
3083 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003084 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003085 diag::warn_explicit_conversion_functions)
3086 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003087}
3088
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003089/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3090/// the declaration of the given C++ conversion function. This routine
3091/// is responsible for recording the conversion function in the C++
3092/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003093Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003094 assert(Conversion && "Expected to receive a conversion function declaration");
3095
Douglas Gregor4287b372008-12-12 08:25:50 +00003096 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003097
3098 // Make sure we aren't redeclaring the conversion function.
3099 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003100
3101 // C++ [class.conv.fct]p1:
3102 // [...] A conversion function is never used to convert a
3103 // (possibly cv-qualified) object to the (possibly cv-qualified)
3104 // same object type (or a reference to it), to a (possibly
3105 // cv-qualified) base class of that type (or a reference to it),
3106 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003107 // FIXME: Suppress this warning if the conversion function ends up being a
3108 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003109 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003110 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003111 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003112 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003113 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3114 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003115 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003116 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003117 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3118 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003119 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003120 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003121 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003122 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003123 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003124 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003125 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003126 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003127 }
3128
Douglas Gregor457104e2010-09-29 04:25:11 +00003129 if (FunctionTemplateDecl *ConversionTemplate
3130 = Conversion->getDescribedFunctionTemplate())
3131 return ConversionTemplate;
3132
John McCall48871652010-08-21 09:40:31 +00003133 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003134}
3135
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003136//===----------------------------------------------------------------------===//
3137// Namespace Handling
3138//===----------------------------------------------------------------------===//
3139
John McCallb1be5232010-08-26 09:15:37 +00003140
3141
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003142/// ActOnStartNamespaceDef - This is called at the start of a namespace
3143/// definition.
John McCall48871652010-08-21 09:40:31 +00003144Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003145 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003146 SourceLocation IdentLoc,
3147 IdentifierInfo *II,
3148 SourceLocation LBrace,
3149 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003150 // anonymous namespace starts at its left brace
3151 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3152 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003153 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003154 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003155
3156 Scope *DeclRegionScope = NamespcScope->getParent();
3157
Anders Carlssona7bcade2010-02-07 01:09:23 +00003158 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3159
Eli Friedman570024a2010-08-05 06:57:20 +00003160 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallb1be5232010-08-26 09:15:37 +00003161 PushVisibilityAttr(attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003162
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003163 if (II) {
3164 // C++ [namespace.def]p2:
3165 // The identifier in an original-namespace-definition shall not have been
3166 // previously defined in the declarative region in which the
3167 // original-namespace-definition appears. The identifier in an
3168 // original-namespace-definition is the name of the namespace. Subsequently
3169 // in that declarative region, it is treated as an original-namespace-name.
3170
John McCall9f3059a2009-10-09 21:13:30 +00003171 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003172 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003173 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003174
Douglas Gregor91f84212008-12-11 16:49:14 +00003175 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3176 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003177 if (Namespc->isInline() != OrigNS->isInline()) {
3178 // inline-ness must match
3179 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3180 << Namespc->isInline();
3181 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3182 Namespc->setInvalidDecl();
3183 // Recover by ignoring the new namespace's inline status.
3184 Namespc->setInline(OrigNS->isInline());
3185 }
3186
Douglas Gregor91f84212008-12-11 16:49:14 +00003187 // Attach this namespace decl to the chain of extended namespace
3188 // definitions.
3189 OrigNS->setNextNamespace(Namespc);
3190 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003191
Mike Stump11289f42009-09-09 15:08:12 +00003192 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003193 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003194 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003195 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003196 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003197 } else if (PrevDecl) {
3198 // This is an invalid name redefinition.
3199 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3200 << Namespc->getDeclName();
3201 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3202 Namespc->setInvalidDecl();
3203 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003204 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003205 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003206 // This is the first "real" definition of the namespace "std", so update
3207 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003208 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003209 // We had already defined a dummy namespace "std". Link this new
3210 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003211 StdNS->setNextNamespace(Namespc);
3212 StdNS->setLocation(IdentLoc);
3213 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003214 }
3215
3216 // Make our StdNamespace cache point at the first real definition of the
3217 // "std" namespace.
3218 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003219 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003220
3221 PushOnScopeChains(Namespc, DeclRegionScope);
3222 } else {
John McCall4fa53422009-10-01 00:25:31 +00003223 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003224 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003225
3226 // Link the anonymous namespace into its parent.
3227 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003228 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003229 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3230 PrevDecl = TU->getAnonymousNamespace();
3231 TU->setAnonymousNamespace(Namespc);
3232 } else {
3233 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3234 PrevDecl = ND->getAnonymousNamespace();
3235 ND->setAnonymousNamespace(Namespc);
3236 }
3237
3238 // Link the anonymous namespace with its previous declaration.
3239 if (PrevDecl) {
3240 assert(PrevDecl->isAnonymousNamespace());
3241 assert(!PrevDecl->getNextNamespace());
3242 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3243 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003244
3245 if (Namespc->isInline() != PrevDecl->isInline()) {
3246 // inline-ness must match
3247 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3248 << Namespc->isInline();
3249 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3250 Namespc->setInvalidDecl();
3251 // Recover by ignoring the new namespace's inline status.
3252 Namespc->setInline(PrevDecl->isInline());
3253 }
John McCall0db42252009-12-16 02:06:49 +00003254 }
John McCall4fa53422009-10-01 00:25:31 +00003255
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003256 CurContext->addDecl(Namespc);
3257
John McCall4fa53422009-10-01 00:25:31 +00003258 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3259 // behaves as if it were replaced by
3260 // namespace unique { /* empty body */ }
3261 // using namespace unique;
3262 // namespace unique { namespace-body }
3263 // where all occurrences of 'unique' in a translation unit are
3264 // replaced by the same identifier and this identifier differs
3265 // from all other identifiers in the entire program.
3266
3267 // We just create the namespace with an empty name and then add an
3268 // implicit using declaration, just like the standard suggests.
3269 //
3270 // CodeGen enforces the "universally unique" aspect by giving all
3271 // declarations semantically contained within an anonymous
3272 // namespace internal linkage.
3273
John McCall0db42252009-12-16 02:06:49 +00003274 if (!PrevDecl) {
3275 UsingDirectiveDecl* UD
3276 = UsingDirectiveDecl::Create(Context, CurContext,
3277 /* 'using' */ LBrace,
3278 /* 'namespace' */ SourceLocation(),
3279 /* qualifier */ SourceRange(),
3280 /* NNS */ NULL,
3281 /* identifier */ SourceLocation(),
3282 Namespc,
3283 /* Ancestor */ CurContext);
3284 UD->setImplicit();
3285 CurContext->addDecl(UD);
3286 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003287 }
3288
3289 // Although we could have an invalid decl (i.e. the namespace name is a
3290 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003291 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3292 // for the namespace has the declarations that showed up in that particular
3293 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003294 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003295 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003296}
3297
Sebastian Redla6602e92009-11-23 15:34:23 +00003298/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3299/// is a namespace alias, returns the namespace it points to.
3300static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3301 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3302 return AD->getNamespace();
3303 return dyn_cast_or_null<NamespaceDecl>(D);
3304}
3305
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003306/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3307/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003308void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003309 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3310 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3311 Namespc->setRBracLoc(RBrace);
3312 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003313 if (Namespc->hasAttr<VisibilityAttr>())
3314 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003315}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003316
John McCall28a0cf72010-08-25 07:42:41 +00003317CXXRecordDecl *Sema::getStdBadAlloc() const {
3318 return cast_or_null<CXXRecordDecl>(
3319 StdBadAlloc.get(Context.getExternalSource()));
3320}
3321
3322NamespaceDecl *Sema::getStdNamespace() const {
3323 return cast_or_null<NamespaceDecl>(
3324 StdNamespace.get(Context.getExternalSource()));
3325}
3326
Douglas Gregorcdf87022010-06-29 17:53:46 +00003327/// \brief Retrieve the special "std" namespace, which may require us to
3328/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003329NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003330 if (!StdNamespace) {
3331 // The "std" namespace has not yet been defined, so build one implicitly.
3332 StdNamespace = NamespaceDecl::Create(Context,
3333 Context.getTranslationUnitDecl(),
3334 SourceLocation(),
3335 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003336 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003337 }
3338
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003339 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003340}
3341
John McCall48871652010-08-21 09:40:31 +00003342Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003343 SourceLocation UsingLoc,
3344 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003345 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003346 SourceLocation IdentLoc,
3347 IdentifierInfo *NamespcName,
3348 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003349 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3350 assert(NamespcName && "Invalid NamespcName.");
3351 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003352 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003353
Douglas Gregor889ceb72009-02-03 19:21:40 +00003354 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003355 NestedNameSpecifier *Qualifier = 0;
3356 if (SS.isSet())
3357 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3358
Douglas Gregor34074322009-01-14 22:20:51 +00003359 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003360 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3361 LookupParsedName(R, S, &SS);
3362 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003363 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003364
Douglas Gregorcdf87022010-06-29 17:53:46 +00003365 if (R.empty()) {
3366 // Allow "using namespace std;" or "using namespace ::std;" even if
3367 // "std" hasn't been defined yet, for GCC compatibility.
3368 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3369 NamespcName->isStr("std")) {
3370 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003371 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003372 R.resolveKind();
3373 }
3374 // Otherwise, attempt typo correction.
3375 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3376 CTC_NoKeywords, 0)) {
3377 if (R.getAsSingle<NamespaceDecl>() ||
3378 R.getAsSingle<NamespaceAliasDecl>()) {
3379 if (DeclContext *DC = computeDeclContext(SS, false))
3380 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3381 << NamespcName << DC << Corrected << SS.getRange()
3382 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3383 else
3384 Diag(IdentLoc, diag::err_using_directive_suggest)
3385 << NamespcName << Corrected
3386 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3387 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3388 << Corrected;
3389
3390 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003391 } else {
3392 R.clear();
3393 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003394 }
3395 }
3396 }
3397
John McCall9f3059a2009-10-09 21:13:30 +00003398 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003399 NamedDecl *Named = R.getFoundDecl();
3400 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3401 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003402 // C++ [namespace.udir]p1:
3403 // A using-directive specifies that the names in the nominated
3404 // namespace can be used in the scope in which the
3405 // using-directive appears after the using-directive. During
3406 // unqualified name lookup (3.4.1), the names appear as if they
3407 // were declared in the nearest enclosing namespace which
3408 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003409 // namespace. [Note: in this context, "contains" means "contains
3410 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003411
3412 // Find enclosing context containing both using-directive and
3413 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003414 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003415 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3416 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3417 CommonAncestor = CommonAncestor->getParent();
3418
Sebastian Redla6602e92009-11-23 15:34:23 +00003419 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003420 SS.getRange(),
3421 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003422 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003423 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003424 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003425 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003426 }
3427
Douglas Gregor889ceb72009-02-03 19:21:40 +00003428 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003429 delete AttrList;
John McCall48871652010-08-21 09:40:31 +00003430 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003431}
3432
3433void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3434 // If scope has associated entity, then using directive is at namespace
3435 // or translation unit scope. We add UsingDirectiveDecls, into
3436 // it's lookup structure.
3437 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003438 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003439 else
3440 // Otherwise it is block-sope. using-directives will affect lookup
3441 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003442 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003443}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003444
Douglas Gregorfec52632009-06-20 00:51:54 +00003445
John McCall48871652010-08-21 09:40:31 +00003446Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003447 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003448 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003449 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003450 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003451 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003452 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003453 bool IsTypeName,
3454 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003455 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003456
Douglas Gregor220f4272009-11-04 16:30:06 +00003457 switch (Name.getKind()) {
3458 case UnqualifiedId::IK_Identifier:
3459 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003460 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003461 case UnqualifiedId::IK_ConversionFunctionId:
3462 break;
3463
3464 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003465 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003466 // C++0x inherited constructors.
3467 if (getLangOptions().CPlusPlus0x) break;
3468
Douglas Gregor220f4272009-11-04 16:30:06 +00003469 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3470 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003471 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003472
3473 case UnqualifiedId::IK_DestructorName:
3474 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3475 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003476 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003477
3478 case UnqualifiedId::IK_TemplateId:
3479 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3480 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003481 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003482 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003483
3484 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3485 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003486 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003487 return 0;
John McCall3969e302009-12-08 07:46:18 +00003488
John McCalla0097262009-12-11 02:10:03 +00003489 // Warn about using declarations.
3490 // TODO: store that the declaration was written without 'using' and
3491 // talk about access decls instead of using decls in the
3492 // diagnostics.
3493 if (!HasUsingKeyword) {
3494 UsingLoc = Name.getSourceRange().getBegin();
3495
3496 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003497 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003498 }
3499
John McCall3f746822009-11-17 05:59:44 +00003500 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003501 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003502 /* IsInstantiation */ false,
3503 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003504 if (UD)
3505 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003506
John McCall48871652010-08-21 09:40:31 +00003507 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003508}
3509
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003510/// \brief Determine whether a using declaration considers the given
3511/// declarations as "equivalent", e.g., if they are redeclarations of
3512/// the same entity or are both typedefs of the same type.
3513static bool
3514IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3515 bool &SuppressRedeclaration) {
3516 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3517 SuppressRedeclaration = false;
3518 return true;
3519 }
3520
3521 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3522 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3523 SuppressRedeclaration = true;
3524 return Context.hasSameType(TD1->getUnderlyingType(),
3525 TD2->getUnderlyingType());
3526 }
3527
3528 return false;
3529}
3530
3531
John McCall84d87672009-12-10 09:41:52 +00003532/// Determines whether to create a using shadow decl for a particular
3533/// decl, given the set of decls existing prior to this using lookup.
3534bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3535 const LookupResult &Previous) {
3536 // Diagnose finding a decl which is not from a base class of the
3537 // current class. We do this now because there are cases where this
3538 // function will silently decide not to build a shadow decl, which
3539 // will pre-empt further diagnostics.
3540 //
3541 // We don't need to do this in C++0x because we do the check once on
3542 // the qualifier.
3543 //
3544 // FIXME: diagnose the following if we care enough:
3545 // struct A { int foo; };
3546 // struct B : A { using A::foo; };
3547 // template <class T> struct C : A {};
3548 // template <class T> struct D : C<T> { using B::foo; } // <---
3549 // This is invalid (during instantiation) in C++03 because B::foo
3550 // resolves to the using decl in B, which is not a base class of D<T>.
3551 // We can't diagnose it immediately because C<T> is an unknown
3552 // specialization. The UsingShadowDecl in D<T> then points directly
3553 // to A::foo, which will look well-formed when we instantiate.
3554 // The right solution is to not collapse the shadow-decl chain.
3555 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3556 DeclContext *OrigDC = Orig->getDeclContext();
3557
3558 // Handle enums and anonymous structs.
3559 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3560 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3561 while (OrigRec->isAnonymousStructOrUnion())
3562 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3563
3564 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3565 if (OrigDC == CurContext) {
3566 Diag(Using->getLocation(),
3567 diag::err_using_decl_nested_name_specifier_is_current_class)
3568 << Using->getNestedNameRange();
3569 Diag(Orig->getLocation(), diag::note_using_decl_target);
3570 return true;
3571 }
3572
3573 Diag(Using->getNestedNameRange().getBegin(),
3574 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3575 << Using->getTargetNestedNameDecl()
3576 << cast<CXXRecordDecl>(CurContext)
3577 << Using->getNestedNameRange();
3578 Diag(Orig->getLocation(), diag::note_using_decl_target);
3579 return true;
3580 }
3581 }
3582
3583 if (Previous.empty()) return false;
3584
3585 NamedDecl *Target = Orig;
3586 if (isa<UsingShadowDecl>(Target))
3587 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3588
John McCalla17e83e2009-12-11 02:33:26 +00003589 // If the target happens to be one of the previous declarations, we
3590 // don't have a conflict.
3591 //
3592 // FIXME: but we might be increasing its access, in which case we
3593 // should redeclare it.
3594 NamedDecl *NonTag = 0, *Tag = 0;
3595 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3596 I != E; ++I) {
3597 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003598 bool Result;
3599 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3600 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003601
3602 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3603 }
3604
John McCall84d87672009-12-10 09:41:52 +00003605 if (Target->isFunctionOrFunctionTemplate()) {
3606 FunctionDecl *FD;
3607 if (isa<FunctionTemplateDecl>(Target))
3608 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3609 else
3610 FD = cast<FunctionDecl>(Target);
3611
3612 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003613 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003614 case Ovl_Overload:
3615 return false;
3616
3617 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003618 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003619 break;
3620
3621 // We found a decl with the exact signature.
3622 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003623 // If we're in a record, we want to hide the target, so we
3624 // return true (without a diagnostic) to tell the caller not to
3625 // build a shadow decl.
3626 if (CurContext->isRecord())
3627 return true;
3628
3629 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003630 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003631 break;
3632 }
3633
3634 Diag(Target->getLocation(), diag::note_using_decl_target);
3635 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3636 return true;
3637 }
3638
3639 // Target is not a function.
3640
John McCall84d87672009-12-10 09:41:52 +00003641 if (isa<TagDecl>(Target)) {
3642 // No conflict between a tag and a non-tag.
3643 if (!Tag) return false;
3644
John McCalle29c5cd2009-12-10 19:51:03 +00003645 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003646 Diag(Target->getLocation(), diag::note_using_decl_target);
3647 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3648 return true;
3649 }
3650
3651 // No conflict between a tag and a non-tag.
3652 if (!NonTag) return false;
3653
John McCalle29c5cd2009-12-10 19:51:03 +00003654 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003655 Diag(Target->getLocation(), diag::note_using_decl_target);
3656 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3657 return true;
3658}
3659
John McCall3f746822009-11-17 05:59:44 +00003660/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003661UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003662 UsingDecl *UD,
3663 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003664
3665 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003666 NamedDecl *Target = Orig;
3667 if (isa<UsingShadowDecl>(Target)) {
3668 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3669 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003670 }
3671
3672 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003673 = UsingShadowDecl::Create(Context, CurContext,
3674 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003675 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003676
3677 Shadow->setAccess(UD->getAccess());
3678 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3679 Shadow->setInvalidDecl();
3680
John McCall3f746822009-11-17 05:59:44 +00003681 if (S)
John McCall3969e302009-12-08 07:46:18 +00003682 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003683 else
John McCall3969e302009-12-08 07:46:18 +00003684 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003685
John McCall3969e302009-12-08 07:46:18 +00003686
John McCall84d87672009-12-10 09:41:52 +00003687 return Shadow;
3688}
John McCall3969e302009-12-08 07:46:18 +00003689
John McCall84d87672009-12-10 09:41:52 +00003690/// Hides a using shadow declaration. This is required by the current
3691/// using-decl implementation when a resolvable using declaration in a
3692/// class is followed by a declaration which would hide or override
3693/// one or more of the using decl's targets; for example:
3694///
3695/// struct Base { void foo(int); };
3696/// struct Derived : Base {
3697/// using Base::foo;
3698/// void foo(int);
3699/// };
3700///
3701/// The governing language is C++03 [namespace.udecl]p12:
3702///
3703/// When a using-declaration brings names from a base class into a
3704/// derived class scope, member functions in the derived class
3705/// override and/or hide member functions with the same name and
3706/// parameter types in a base class (rather than conflicting).
3707///
3708/// There are two ways to implement this:
3709/// (1) optimistically create shadow decls when they're not hidden
3710/// by existing declarations, or
3711/// (2) don't create any shadow decls (or at least don't make them
3712/// visible) until we've fully parsed/instantiated the class.
3713/// The problem with (1) is that we might have to retroactively remove
3714/// a shadow decl, which requires several O(n) operations because the
3715/// decl structures are (very reasonably) not designed for removal.
3716/// (2) avoids this but is very fiddly and phase-dependent.
3717void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003718 if (Shadow->getDeclName().getNameKind() ==
3719 DeclarationName::CXXConversionFunctionName)
3720 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3721
John McCall84d87672009-12-10 09:41:52 +00003722 // Remove it from the DeclContext...
3723 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003724
John McCall84d87672009-12-10 09:41:52 +00003725 // ...and the scope, if applicable...
3726 if (S) {
John McCall48871652010-08-21 09:40:31 +00003727 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003728 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003729 }
3730
John McCall84d87672009-12-10 09:41:52 +00003731 // ...and the using decl.
3732 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3733
3734 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003735 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003736}
3737
John McCalle61f2ba2009-11-18 02:36:19 +00003738/// Builds a using declaration.
3739///
3740/// \param IsInstantiation - Whether this call arises from an
3741/// instantiation of an unresolved using declaration. We treat
3742/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003743NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3744 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003745 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003746 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003747 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003748 bool IsInstantiation,
3749 bool IsTypeName,
3750 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003751 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003752 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003753 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003754
Anders Carlssonf038fc22009-08-28 05:49:21 +00003755 // FIXME: We ignore attributes for now.
3756 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003757
Anders Carlsson59140b32009-08-28 03:16:11 +00003758 if (SS.isEmpty()) {
3759 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003760 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003761 }
Mike Stump11289f42009-09-09 15:08:12 +00003762
John McCall84d87672009-12-10 09:41:52 +00003763 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003764 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003765 ForRedeclaration);
3766 Previous.setHideTags(false);
3767 if (S) {
3768 LookupName(Previous, S);
3769
3770 // It is really dumb that we have to do this.
3771 LookupResult::Filter F = Previous.makeFilter();
3772 while (F.hasNext()) {
3773 NamedDecl *D = F.next();
3774 if (!isDeclInScope(D, CurContext, S))
3775 F.erase();
3776 }
3777 F.done();
3778 } else {
3779 assert(IsInstantiation && "no scope in non-instantiation");
3780 assert(CurContext->isRecord() && "scope not record in instantiation");
3781 LookupQualifiedName(Previous, CurContext);
3782 }
3783
Mike Stump11289f42009-09-09 15:08:12 +00003784 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003785 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3786
John McCall84d87672009-12-10 09:41:52 +00003787 // Check for invalid redeclarations.
3788 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3789 return 0;
3790
3791 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003792 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3793 return 0;
3794
John McCall84c16cf2009-11-12 03:15:40 +00003795 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003796 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003797 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003798 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003799 // FIXME: not all declaration name kinds are legal here
3800 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3801 UsingLoc, TypenameLoc,
3802 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003803 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003804 } else {
3805 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003806 UsingLoc, SS.getRange(),
3807 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003808 }
John McCallb96ec562009-12-04 22:46:56 +00003809 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003810 D = UsingDecl::Create(Context, CurContext,
3811 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003812 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003813 }
John McCallb96ec562009-12-04 22:46:56 +00003814 D->setAccess(AS);
3815 CurContext->addDecl(D);
3816
3817 if (!LookupContext) return D;
3818 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003819
John McCall0b66eb32010-05-01 00:40:08 +00003820 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003821 UD->setInvalidDecl();
3822 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003823 }
3824
John McCall3969e302009-12-08 07:46:18 +00003825 // Look up the target name.
3826
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003827 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003828
John McCall3969e302009-12-08 07:46:18 +00003829 // Unlike most lookups, we don't always want to hide tag
3830 // declarations: tag names are visible through the using declaration
3831 // even if hidden by ordinary names, *except* in a dependent context
3832 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003833 if (!IsInstantiation)
3834 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003835
John McCall27b18f82009-11-17 02:14:36 +00003836 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003837
John McCall9f3059a2009-10-09 21:13:30 +00003838 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003839 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003840 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003841 UD->setInvalidDecl();
3842 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003843 }
3844
John McCallb96ec562009-12-04 22:46:56 +00003845 if (R.isAmbiguous()) {
3846 UD->setInvalidDecl();
3847 return UD;
3848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
John McCalle61f2ba2009-11-18 02:36:19 +00003850 if (IsTypeName) {
3851 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003852 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003853 Diag(IdentLoc, diag::err_using_typename_non_type);
3854 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3855 Diag((*I)->getUnderlyingDecl()->getLocation(),
3856 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003857 UD->setInvalidDecl();
3858 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003859 }
3860 } else {
3861 // If we asked for a non-typename and we got a type, error out,
3862 // but only if this is an instantiation of an unresolved using
3863 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003864 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003865 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3866 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003867 UD->setInvalidDecl();
3868 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003869 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003870 }
3871
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003872 // C++0x N2914 [namespace.udecl]p6:
3873 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003874 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003875 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3876 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003877 UD->setInvalidDecl();
3878 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003879 }
Mike Stump11289f42009-09-09 15:08:12 +00003880
John McCall84d87672009-12-10 09:41:52 +00003881 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3882 if (!CheckUsingShadowDecl(UD, *I, Previous))
3883 BuildUsingShadowDecl(S, UD, *I);
3884 }
John McCall3f746822009-11-17 05:59:44 +00003885
3886 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003887}
3888
John McCall84d87672009-12-10 09:41:52 +00003889/// Checks that the given using declaration is not an invalid
3890/// redeclaration. Note that this is checking only for the using decl
3891/// itself, not for any ill-formedness among the UsingShadowDecls.
3892bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3893 bool isTypeName,
3894 const CXXScopeSpec &SS,
3895 SourceLocation NameLoc,
3896 const LookupResult &Prev) {
3897 // C++03 [namespace.udecl]p8:
3898 // C++0x [namespace.udecl]p10:
3899 // A using-declaration is a declaration and can therefore be used
3900 // repeatedly where (and only where) multiple declarations are
3901 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003902 //
3903 // That's in non-member contexts.
Sebastian Redl50c68252010-08-31 00:36:30 +00003904 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003905 return false;
3906
3907 NestedNameSpecifier *Qual
3908 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3909
3910 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3911 NamedDecl *D = *I;
3912
3913 bool DTypename;
3914 NestedNameSpecifier *DQual;
3915 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3916 DTypename = UD->isTypeName();
3917 DQual = UD->getTargetNestedNameDecl();
3918 } else if (UnresolvedUsingValueDecl *UD
3919 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3920 DTypename = false;
3921 DQual = UD->getTargetNestedNameSpecifier();
3922 } else if (UnresolvedUsingTypenameDecl *UD
3923 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3924 DTypename = true;
3925 DQual = UD->getTargetNestedNameSpecifier();
3926 } else continue;
3927
3928 // using decls differ if one says 'typename' and the other doesn't.
3929 // FIXME: non-dependent using decls?
3930 if (isTypeName != DTypename) continue;
3931
3932 // using decls differ if they name different scopes (but note that
3933 // template instantiation can cause this check to trigger when it
3934 // didn't before instantiation).
3935 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3936 Context.getCanonicalNestedNameSpecifier(DQual))
3937 continue;
3938
3939 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003940 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003941 return true;
3942 }
3943
3944 return false;
3945}
3946
John McCall3969e302009-12-08 07:46:18 +00003947
John McCallb96ec562009-12-04 22:46:56 +00003948/// Checks that the given nested-name qualifier used in a using decl
3949/// in the current context is appropriately related to the current
3950/// scope. If an error is found, diagnoses it and returns true.
3951bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3952 const CXXScopeSpec &SS,
3953 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003954 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003955
John McCall3969e302009-12-08 07:46:18 +00003956 if (!CurContext->isRecord()) {
3957 // C++03 [namespace.udecl]p3:
3958 // C++0x [namespace.udecl]p8:
3959 // A using-declaration for a class member shall be a member-declaration.
3960
3961 // If we weren't able to compute a valid scope, it must be a
3962 // dependent class scope.
3963 if (!NamedContext || NamedContext->isRecord()) {
3964 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3965 << SS.getRange();
3966 return true;
3967 }
3968
3969 // Otherwise, everything is known to be fine.
3970 return false;
3971 }
3972
3973 // The current scope is a record.
3974
3975 // If the named context is dependent, we can't decide much.
3976 if (!NamedContext) {
3977 // FIXME: in C++0x, we can diagnose if we can prove that the
3978 // nested-name-specifier does not refer to a base class, which is
3979 // still possible in some cases.
3980
3981 // Otherwise we have to conservatively report that things might be
3982 // okay.
3983 return false;
3984 }
3985
3986 if (!NamedContext->isRecord()) {
3987 // Ideally this would point at the last name in the specifier,
3988 // but we don't have that level of source info.
3989 Diag(SS.getRange().getBegin(),
3990 diag::err_using_decl_nested_name_specifier_is_not_class)
3991 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3992 return true;
3993 }
3994
3995 if (getLangOptions().CPlusPlus0x) {
3996 // C++0x [namespace.udecl]p3:
3997 // In a using-declaration used as a member-declaration, the
3998 // nested-name-specifier shall name a base class of the class
3999 // being defined.
4000
4001 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4002 cast<CXXRecordDecl>(NamedContext))) {
4003 if (CurContext == NamedContext) {
4004 Diag(NameLoc,
4005 diag::err_using_decl_nested_name_specifier_is_current_class)
4006 << SS.getRange();
4007 return true;
4008 }
4009
4010 Diag(SS.getRange().getBegin(),
4011 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4012 << (NestedNameSpecifier*) SS.getScopeRep()
4013 << cast<CXXRecordDecl>(CurContext)
4014 << SS.getRange();
4015 return true;
4016 }
4017
4018 return false;
4019 }
4020
4021 // C++03 [namespace.udecl]p4:
4022 // A using-declaration used as a member-declaration shall refer
4023 // to a member of a base class of the class being defined [etc.].
4024
4025 // Salient point: SS doesn't have to name a base class as long as
4026 // lookup only finds members from base classes. Therefore we can
4027 // diagnose here only if we can prove that that can't happen,
4028 // i.e. if the class hierarchies provably don't intersect.
4029
4030 // TODO: it would be nice if "definitely valid" results were cached
4031 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4032 // need to be repeated.
4033
4034 struct UserData {
4035 llvm::DenseSet<const CXXRecordDecl*> Bases;
4036
4037 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4038 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4039 Data->Bases.insert(Base);
4040 return true;
4041 }
4042
4043 bool hasDependentBases(const CXXRecordDecl *Class) {
4044 return !Class->forallBases(collect, this);
4045 }
4046
4047 /// Returns true if the base is dependent or is one of the
4048 /// accumulated base classes.
4049 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4050 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4051 return !Data->Bases.count(Base);
4052 }
4053
4054 bool mightShareBases(const CXXRecordDecl *Class) {
4055 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4056 }
4057 };
4058
4059 UserData Data;
4060
4061 // Returns false if we find a dependent base.
4062 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4063 return false;
4064
4065 // Returns false if the class has a dependent base or if it or one
4066 // of its bases is present in the base set of the current context.
4067 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4068 return false;
4069
4070 Diag(SS.getRange().getBegin(),
4071 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4072 << (NestedNameSpecifier*) SS.getScopeRep()
4073 << cast<CXXRecordDecl>(CurContext)
4074 << SS.getRange();
4075
4076 return true;
John McCallb96ec562009-12-04 22:46:56 +00004077}
4078
John McCall48871652010-08-21 09:40:31 +00004079Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004080 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004081 SourceLocation AliasLoc,
4082 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004083 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004084 SourceLocation IdentLoc,
4085 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004086
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004087 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004088 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4089 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004090
Anders Carlssondca83c42009-03-28 06:23:46 +00004091 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004092 NamedDecl *PrevDecl
4093 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4094 ForRedeclaration);
4095 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4096 PrevDecl = 0;
4097
4098 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004099 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004100 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004101 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004102 // FIXME: At some point, we'll want to create the (redundant)
4103 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004104 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004105 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004106 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004107 }
Mike Stump11289f42009-09-09 15:08:12 +00004108
Anders Carlssondca83c42009-03-28 06:23:46 +00004109 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4110 diag::err_redefinition_different_kind;
4111 Diag(AliasLoc, DiagID) << Alias;
4112 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004113 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004114 }
4115
John McCall27b18f82009-11-17 02:14:36 +00004116 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004117 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004118
John McCall9f3059a2009-10-09 21:13:30 +00004119 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004120 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4121 CTC_NoKeywords, 0)) {
4122 if (R.getAsSingle<NamespaceDecl>() ||
4123 R.getAsSingle<NamespaceAliasDecl>()) {
4124 if (DeclContext *DC = computeDeclContext(SS, false))
4125 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4126 << Ident << DC << Corrected << SS.getRange()
4127 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4128 else
4129 Diag(IdentLoc, diag::err_using_directive_suggest)
4130 << Ident << Corrected
4131 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4132
4133 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4134 << Corrected;
4135
4136 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004137 } else {
4138 R.clear();
4139 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004140 }
4141 }
4142
4143 if (R.empty()) {
4144 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004145 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004146 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004147 }
Mike Stump11289f42009-09-09 15:08:12 +00004148
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004149 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004150 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4151 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004152 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004153 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004154
John McCalld8d0d432010-02-16 06:53:13 +00004155 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004156 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004157}
4158
Douglas Gregora57478e2010-05-01 15:04:51 +00004159namespace {
4160 /// \brief Scoped object used to handle the state changes required in Sema
4161 /// to implicitly define the body of a C++ member function;
4162 class ImplicitlyDefinedFunctionScope {
4163 Sema &S;
4164 DeclContext *PreviousContext;
4165
4166 public:
4167 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4168 : S(S), PreviousContext(S.CurContext)
4169 {
4170 S.CurContext = Method;
4171 S.PushFunctionScope();
4172 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4173 }
4174
4175 ~ImplicitlyDefinedFunctionScope() {
4176 S.PopExpressionEvaluationContext();
4177 S.PopFunctionOrBlockScope();
4178 S.CurContext = PreviousContext;
4179 }
4180 };
4181}
4182
Sebastian Redlc15c3262010-09-13 22:02:47 +00004183static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4184 CXXRecordDecl *D) {
4185 ASTContext &Context = Self.Context;
4186 QualType ClassType = Context.getTypeDeclType(D);
4187 DeclarationName ConstructorName
4188 = Context.DeclarationNames.getCXXConstructorName(
4189 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4190
4191 DeclContext::lookup_const_iterator Con, ConEnd;
4192 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4193 Con != ConEnd; ++Con) {
4194 // FIXME: In C++0x, a constructor template can be a default constructor.
4195 if (isa<FunctionTemplateDecl>(*Con))
4196 continue;
4197
4198 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4199 if (Constructor->isDefaultConstructor())
4200 return Constructor;
4201 }
4202 return 0;
4203}
4204
Douglas Gregor0be31a22010-07-02 17:43:08 +00004205CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4206 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004207 // C++ [class.ctor]p5:
4208 // A default constructor for a class X is a constructor of class X
4209 // that can be called without an argument. If there is no
4210 // user-declared constructor for class X, a default constructor is
4211 // implicitly declared. An implicitly-declared default constructor
4212 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004213 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4214 "Should not build implicit default constructor!");
4215
Douglas Gregor6d880b12010-07-01 22:31:05 +00004216 // C++ [except.spec]p14:
4217 // An implicitly declared special member function (Clause 12) shall have an
4218 // exception-specification. [...]
4219 ImplicitExceptionSpecification ExceptSpec(Context);
4220
4221 // Direct base-class destructors.
4222 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4223 BEnd = ClassDecl->bases_end();
4224 B != BEnd; ++B) {
4225 if (B->isVirtual()) // Handled below.
4226 continue;
4227
Douglas Gregor9672f922010-07-03 00:47:00 +00004228 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4229 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4230 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4231 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004232 else if (CXXConstructorDecl *Constructor
4233 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004234 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004235 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004236 }
4237
4238 // Virtual base-class destructors.
4239 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4240 BEnd = ClassDecl->vbases_end();
4241 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004242 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4243 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4244 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4245 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4246 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004247 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004248 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004249 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004250 }
4251
4252 // Field destructors.
4253 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4254 FEnd = ClassDecl->field_end();
4255 F != FEnd; ++F) {
4256 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004257 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4258 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4259 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4260 ExceptSpec.CalledDecl(
4261 DeclareImplicitDefaultConstructor(FieldClassDecl));
4262 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004263 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004264 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004265 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004266 }
4267
4268
4269 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004270 CanQualType ClassType
4271 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4272 DeclarationName Name
4273 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004274 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004275 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004276 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004277 Context.getFunctionType(Context.VoidTy,
4278 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004279 ExceptSpec.hasExceptionSpecification(),
4280 ExceptSpec.hasAnyExceptionSpecification(),
4281 ExceptSpec.size(),
4282 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004283 FunctionType::ExtInfo()),
4284 /*TInfo=*/0,
4285 /*isExplicit=*/false,
4286 /*isInline=*/true,
4287 /*isImplicitlyDeclared=*/true);
4288 DefaultCon->setAccess(AS_public);
4289 DefaultCon->setImplicit();
4290 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004291
4292 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004293 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4294
Douglas Gregor0be31a22010-07-02 17:43:08 +00004295 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004296 PushOnScopeChains(DefaultCon, S, false);
4297 ClassDecl->addDecl(DefaultCon);
4298
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004299 return DefaultCon;
4300}
4301
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004302void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4303 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004304 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004305 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004306 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004307
Anders Carlsson423f5d82010-04-23 16:04:08 +00004308 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004309 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004310
Douglas Gregora57478e2010-05-01 15:04:51 +00004311 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004312 ErrorTrap Trap(*this);
4313 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4314 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004315 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004316 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004317 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004318 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004319 }
Douglas Gregor73193272010-09-20 16:48:21 +00004320
4321 SourceLocation Loc = Constructor->getLocation();
4322 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4323
4324 Constructor->setUsed();
4325 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004326}
4327
Douglas Gregor0be31a22010-07-02 17:43:08 +00004328CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004329 // C++ [class.dtor]p2:
4330 // If a class has no user-declared destructor, a destructor is
4331 // declared implicitly. An implicitly-declared destructor is an
4332 // inline public member of its class.
4333
4334 // C++ [except.spec]p14:
4335 // An implicitly declared special member function (Clause 12) shall have
4336 // an exception-specification.
4337 ImplicitExceptionSpecification ExceptSpec(Context);
4338
4339 // Direct base-class destructors.
4340 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4341 BEnd = ClassDecl->bases_end();
4342 B != BEnd; ++B) {
4343 if (B->isVirtual()) // Handled below.
4344 continue;
4345
4346 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4347 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004348 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004349 }
4350
4351 // Virtual base-class destructors.
4352 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4353 BEnd = ClassDecl->vbases_end();
4354 B != BEnd; ++B) {
4355 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4356 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004357 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004358 }
4359
4360 // Field destructors.
4361 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4362 FEnd = ClassDecl->field_end();
4363 F != FEnd; ++F) {
4364 if (const RecordType *RecordTy
4365 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4366 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004367 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004368 }
4369
Douglas Gregor7454c562010-07-02 20:37:36 +00004370 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004371 QualType Ty = Context.getFunctionType(Context.VoidTy,
4372 0, 0, false, 0,
4373 ExceptSpec.hasExceptionSpecification(),
4374 ExceptSpec.hasAnyExceptionSpecification(),
4375 ExceptSpec.size(),
4376 ExceptSpec.data(),
4377 FunctionType::ExtInfo());
4378
4379 CanQualType ClassType
4380 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4381 DeclarationName Name
4382 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004383 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004384 CXXDestructorDecl *Destructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004385 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorf1203042010-07-01 19:09:28 +00004386 /*isInline=*/true,
4387 /*isImplicitlyDeclared=*/true);
4388 Destructor->setAccess(AS_public);
4389 Destructor->setImplicit();
4390 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004391
4392 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004393 ++ASTContext::NumImplicitDestructorsDeclared;
4394
4395 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004396 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004397 PushOnScopeChains(Destructor, S, false);
4398 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004399
4400 // This could be uniqued if it ever proves significant.
4401 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4402
4403 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004404
Douglas Gregorf1203042010-07-01 19:09:28 +00004405 return Destructor;
4406}
4407
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004408void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004409 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004410 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004411 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004412 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004413 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004414
Douglas Gregor54818f02010-05-12 16:39:35 +00004415 if (Destructor->isInvalidDecl())
4416 return;
4417
Douglas Gregora57478e2010-05-01 15:04:51 +00004418 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004419
Douglas Gregor54818f02010-05-12 16:39:35 +00004420 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004421 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4422 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004423
Douglas Gregor54818f02010-05-12 16:39:35 +00004424 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004425 Diag(CurrentLocation, diag::note_member_synthesized_at)
4426 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4427
4428 Destructor->setInvalidDecl();
4429 return;
4430 }
4431
Douglas Gregor73193272010-09-20 16:48:21 +00004432 SourceLocation Loc = Destructor->getLocation();
4433 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4434
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004435 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004436 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004437}
4438
Douglas Gregorb139cd52010-05-01 20:49:11 +00004439/// \brief Builds a statement that copies the given entity from \p From to
4440/// \c To.
4441///
4442/// This routine is used to copy the members of a class with an
4443/// implicitly-declared copy assignment operator. When the entities being
4444/// copied are arrays, this routine builds for loops to copy them.
4445///
4446/// \param S The Sema object used for type-checking.
4447///
4448/// \param Loc The location where the implicit copy is being generated.
4449///
4450/// \param T The type of the expressions being copied. Both expressions must
4451/// have this type.
4452///
4453/// \param To The expression we are copying to.
4454///
4455/// \param From The expression we are copying from.
4456///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004457/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4458/// Otherwise, it's a non-static member subobject.
4459///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004460/// \param Depth Internal parameter recording the depth of the recursion.
4461///
4462/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004463static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004464BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004465 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004466 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004467 // C++0x [class.copy]p30:
4468 // Each subobject is assigned in the manner appropriate to its type:
4469 //
4470 // - if the subobject is of class type, the copy assignment operator
4471 // for the class is used (as if by explicit qualification; that is,
4472 // ignoring any possible virtual overriding functions in more derived
4473 // classes);
4474 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4475 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4476
4477 // Look for operator=.
4478 DeclarationName Name
4479 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4480 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4481 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4482
4483 // Filter out any result that isn't a copy-assignment operator.
4484 LookupResult::Filter F = OpLookup.makeFilter();
4485 while (F.hasNext()) {
4486 NamedDecl *D = F.next();
4487 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4488 if (Method->isCopyAssignmentOperator())
4489 continue;
4490
4491 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004492 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004493 F.done();
4494
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004495 // Suppress the protected check (C++ [class.protected]) for each of the
4496 // assignment operators we found. This strange dance is required when
4497 // we're assigning via a base classes's copy-assignment operator. To
4498 // ensure that we're getting the right base class subobject (without
4499 // ambiguities), we need to cast "this" to that subobject type; to
4500 // ensure that we don't go through the virtual call mechanism, we need
4501 // to qualify the operator= name with the base class (see below). However,
4502 // this means that if the base class has a protected copy assignment
4503 // operator, the protected member access check will fail. So, we
4504 // rewrite "protected" access to "public" access in this case, since we
4505 // know by construction that we're calling from a derived class.
4506 if (CopyingBaseSubobject) {
4507 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4508 L != LEnd; ++L) {
4509 if (L.getAccess() == AS_protected)
4510 L.setAccess(AS_public);
4511 }
4512 }
4513
Douglas Gregorb139cd52010-05-01 20:49:11 +00004514 // Create the nested-name-specifier that will be used to qualify the
4515 // reference to operator=; this is required to suppress the virtual
4516 // call mechanism.
4517 CXXScopeSpec SS;
4518 SS.setRange(Loc);
4519 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4520 T.getTypePtr()));
4521
4522 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004523 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004524 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004525 /*FirstQualifierInScope=*/0, OpLookup,
4526 /*TemplateArgs=*/0,
4527 /*SuppressQualifierCheck=*/true);
4528 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004529 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004530
4531 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004532
John McCalldadc5752010-08-24 06:29:42 +00004533 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004534 OpEqualRef.takeAs<Expr>(),
4535 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004536 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004537 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004538
4539 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004540 }
John McCallab8c2732010-03-16 06:11:48 +00004541
Douglas Gregorb139cd52010-05-01 20:49:11 +00004542 // - if the subobject is of scalar type, the built-in assignment
4543 // operator is used.
4544 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4545 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004546 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004547 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004548 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004549
4550 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004551 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004552
4553 // - if the subobject is an array, each element is assigned, in the
4554 // manner appropriate to the element type;
4555
4556 // Construct a loop over the array bounds, e.g.,
4557 //
4558 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4559 //
4560 // that will copy each of the array elements.
4561 QualType SizeType = S.Context.getSizeType();
4562
4563 // Create the iteration variable.
4564 IdentifierInfo *IterationVarName = 0;
4565 {
4566 llvm::SmallString<8> Str;
4567 llvm::raw_svector_ostream OS(Str);
4568 OS << "__i" << Depth;
4569 IterationVarName = &S.Context.Idents.get(OS.str());
4570 }
4571 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4572 IterationVarName, SizeType,
4573 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004574 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004575
4576 // Initialize the iteration variable to zero.
4577 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004578 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004579
4580 // Create a reference to the iteration variable; we'll use this several
4581 // times throughout.
4582 Expr *IterationVarRef
4583 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4584 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4585
4586 // Create the DeclStmt that holds the iteration variable.
4587 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4588
4589 // Create the comparison against the array bound.
4590 llvm::APInt Upper = ArrayTy->getSize();
4591 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004592 Expr *Comparison
4593 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004594 IntegerLiteral::Create(S.Context,
4595 Upper, SizeType, Loc),
4596 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004597
4598 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004599 Expr *Increment
4600 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCalle3027922010-08-25 11:45:40 +00004601 UO_PreInc,
John McCallb268a282010-08-23 23:25:46 +00004602 SizeType, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004603
4604 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004605 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4606 IterationVarRef, Loc));
4607 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4608 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004609
4610 // Build the copy for an individual element of the array.
John McCalldadc5752010-08-24 06:29:42 +00004611 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004612 ArrayTy->getElementType(),
John McCallb268a282010-08-23 23:25:46 +00004613 To, From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004614 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004615 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004616 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004617
4618 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004619 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004620 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004621 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004622 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004623}
4624
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004625/// \brief Determine whether the given class has a copy assignment operator
4626/// that accepts a const-qualified argument.
4627static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4628 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4629
4630 if (!Class->hasDeclaredCopyAssignment())
4631 S.DeclareImplicitCopyAssignment(Class);
4632
4633 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4634 DeclarationName OpName
4635 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4636
4637 DeclContext::lookup_const_iterator Op, OpEnd;
4638 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4639 // C++ [class.copy]p9:
4640 // A user-declared copy assignment operator is a non-static non-template
4641 // member function of class X with exactly one parameter of type X, X&,
4642 // const X&, volatile X& or const volatile X&.
4643 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4644 if (!Method)
4645 continue;
4646
4647 if (Method->isStatic())
4648 continue;
4649 if (Method->getPrimaryTemplate())
4650 continue;
4651 const FunctionProtoType *FnType =
4652 Method->getType()->getAs<FunctionProtoType>();
4653 assert(FnType && "Overloaded operator has no prototype.");
4654 // Don't assert on this; an invalid decl might have been left in the AST.
4655 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4656 continue;
4657 bool AcceptsConst = true;
4658 QualType ArgType = FnType->getArgType(0);
4659 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4660 ArgType = Ref->getPointeeType();
4661 // Is it a non-const lvalue reference?
4662 if (!ArgType.isConstQualified())
4663 AcceptsConst = false;
4664 }
4665 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4666 continue;
4667
4668 // We have a single argument of type cv X or cv X&, i.e. we've found the
4669 // copy assignment operator. Return whether it accepts const arguments.
4670 return AcceptsConst;
4671 }
4672 assert(Class->isInvalidDecl() &&
4673 "No copy assignment operator declared in valid code.");
4674 return false;
4675}
4676
Douglas Gregor0be31a22010-07-02 17:43:08 +00004677CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004678 // Note: The following rules are largely analoguous to the copy
4679 // constructor rules. Note that virtual bases are not taken into account
4680 // for determining the argument type of the operator. Note also that
4681 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004682
4683
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004684 // C++ [class.copy]p10:
4685 // If the class definition does not explicitly declare a copy
4686 // assignment operator, one is declared implicitly.
4687 // The implicitly-defined copy assignment operator for a class X
4688 // will have the form
4689 //
4690 // X& X::operator=(const X&)
4691 //
4692 // if
4693 bool HasConstCopyAssignment = true;
4694
4695 // -- each direct base class B of X has a copy assignment operator
4696 // whose parameter is of type const B&, const volatile B& or B,
4697 // and
4698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4699 BaseEnd = ClassDecl->bases_end();
4700 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4701 assert(!Base->getType()->isDependentType() &&
4702 "Cannot generate implicit members for class with dependent bases.");
4703 const CXXRecordDecl *BaseClassDecl
4704 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004705 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004706 }
4707
4708 // -- for all the nonstatic data members of X that are of a class
4709 // type M (or array thereof), each such class type has a copy
4710 // assignment operator whose parameter is of type const M&,
4711 // const volatile M& or M.
4712 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4713 FieldEnd = ClassDecl->field_end();
4714 HasConstCopyAssignment && Field != FieldEnd;
4715 ++Field) {
4716 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4717 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4718 const CXXRecordDecl *FieldClassDecl
4719 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004720 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004721 }
4722 }
4723
4724 // Otherwise, the implicitly declared copy assignment operator will
4725 // have the form
4726 //
4727 // X& X::operator=(X&)
4728 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4729 QualType RetType = Context.getLValueReferenceType(ArgType);
4730 if (HasConstCopyAssignment)
4731 ArgType = ArgType.withConst();
4732 ArgType = Context.getLValueReferenceType(ArgType);
4733
Douglas Gregor68e11362010-07-01 17:48:08 +00004734 // C++ [except.spec]p14:
4735 // An implicitly declared special member function (Clause 12) shall have an
4736 // exception-specification. [...]
4737 ImplicitExceptionSpecification ExceptSpec(Context);
4738 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4739 BaseEnd = ClassDecl->bases_end();
4740 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004741 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004742 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004743
4744 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4745 DeclareImplicitCopyAssignment(BaseClassDecl);
4746
Douglas Gregor68e11362010-07-01 17:48:08 +00004747 if (CXXMethodDecl *CopyAssign
4748 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4749 ExceptSpec.CalledDecl(CopyAssign);
4750 }
4751 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4752 FieldEnd = ClassDecl->field_end();
4753 Field != FieldEnd;
4754 ++Field) {
4755 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4756 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004757 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004758 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004759
4760 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4761 DeclareImplicitCopyAssignment(FieldClassDecl);
4762
Douglas Gregor68e11362010-07-01 17:48:08 +00004763 if (CXXMethodDecl *CopyAssign
4764 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4765 ExceptSpec.CalledDecl(CopyAssign);
4766 }
4767 }
4768
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004769 // An implicitly-declared copy assignment operator is an inline public
4770 // member of its class.
4771 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004772 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004773 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004774 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004775 Context.getFunctionType(RetType, &ArgType, 1,
4776 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004777 ExceptSpec.hasExceptionSpecification(),
4778 ExceptSpec.hasAnyExceptionSpecification(),
4779 ExceptSpec.size(),
4780 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004781 FunctionType::ExtInfo()),
4782 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004783 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004784 /*isInline=*/true);
4785 CopyAssignment->setAccess(AS_public);
4786 CopyAssignment->setImplicit();
4787 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004788
4789 // Add the parameter to the operator.
4790 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4791 ClassDecl->getLocation(),
4792 /*Id=*/0,
4793 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004794 SC_None,
4795 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004796 CopyAssignment->setParams(&FromParam, 1);
4797
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004798 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004799 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4800
Douglas Gregor0be31a22010-07-02 17:43:08 +00004801 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004802 PushOnScopeChains(CopyAssignment, S, false);
4803 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004804
4805 AddOverriddenMethods(ClassDecl, CopyAssignment);
4806 return CopyAssignment;
4807}
4808
Douglas Gregorb139cd52010-05-01 20:49:11 +00004809void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4810 CXXMethodDecl *CopyAssignOperator) {
4811 assert((CopyAssignOperator->isImplicit() &&
4812 CopyAssignOperator->isOverloadedOperator() &&
4813 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004814 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004815 "DefineImplicitCopyAssignment called for wrong function");
4816
4817 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4818
4819 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4820 CopyAssignOperator->setInvalidDecl();
4821 return;
4822 }
4823
4824 CopyAssignOperator->setUsed();
4825
4826 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004827 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004828
4829 // C++0x [class.copy]p30:
4830 // The implicitly-defined or explicitly-defaulted copy assignment operator
4831 // for a non-union class X performs memberwise copy assignment of its
4832 // subobjects. The direct base classes of X are assigned first, in the
4833 // order of their declaration in the base-specifier-list, and then the
4834 // immediate non-static data members of X are assigned, in the order in
4835 // which they were declared in the class definition.
4836
4837 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004838 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004839
4840 // The parameter for the "other" object, which we are copying from.
4841 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4842 Qualifiers OtherQuals = Other->getType().getQualifiers();
4843 QualType OtherRefType = Other->getType();
4844 if (const LValueReferenceType *OtherRef
4845 = OtherRefType->getAs<LValueReferenceType>()) {
4846 OtherRefType = OtherRef->getPointeeType();
4847 OtherQuals = OtherRefType.getQualifiers();
4848 }
4849
4850 // Our location for everything implicitly-generated.
4851 SourceLocation Loc = CopyAssignOperator->getLocation();
4852
4853 // Construct a reference to the "other" object. We'll be using this
4854 // throughout the generated ASTs.
4855 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4856 assert(OtherRef && "Reference to parameter cannot fail!");
4857
4858 // Construct the "this" pointer. We'll be using this throughout the generated
4859 // ASTs.
4860 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4861 assert(This && "Reference to this cannot fail!");
4862
4863 // Assign base classes.
4864 bool Invalid = false;
4865 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4866 E = ClassDecl->bases_end(); Base != E; ++Base) {
4867 // Form the assignment:
4868 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4869 QualType BaseType = Base->getType().getUnqualifiedType();
4870 CXXRecordDecl *BaseClassDecl = 0;
4871 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4872 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4873 else {
4874 Invalid = true;
4875 continue;
4876 }
4877
John McCallcf142162010-08-07 06:22:56 +00004878 CXXCastPath BasePath;
4879 BasePath.push_back(Base);
4880
Douglas Gregorb139cd52010-05-01 20:49:11 +00004881 // Construct the "from" expression, which is an implicit cast to the
4882 // appropriately-qualified base type.
4883 Expr *From = OtherRef->Retain();
4884 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004885 CK_UncheckedDerivedToBase,
4886 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004887
4888 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004889 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004890
4891 // Implicitly cast "this" to the appropriately-qualified base type.
4892 Expr *ToE = To.takeAs<Expr>();
4893 ImpCastExprToType(ToE,
4894 Context.getCVRQualifiedType(BaseType,
4895 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004896 CK_UncheckedDerivedToBase,
4897 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004898 To = Owned(ToE);
4899
4900 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004901 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004902 To.get(), From,
4903 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004904 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004905 Diag(CurrentLocation, diag::note_member_synthesized_at)
4906 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4907 CopyAssignOperator->setInvalidDecl();
4908 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004909 }
4910
4911 // Success! Record the copy.
4912 Statements.push_back(Copy.takeAs<Expr>());
4913 }
4914
4915 // \brief Reference to the __builtin_memcpy function.
4916 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004917 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004918 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004919
4920 // Assign non-static members.
4921 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4922 FieldEnd = ClassDecl->field_end();
4923 Field != FieldEnd; ++Field) {
4924 // Check for members of reference type; we can't copy those.
4925 if (Field->getType()->isReferenceType()) {
4926 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4927 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4928 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004929 Diag(CurrentLocation, diag::note_member_synthesized_at)
4930 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004931 Invalid = true;
4932 continue;
4933 }
4934
4935 // Check for members of const-qualified, non-class type.
4936 QualType BaseType = Context.getBaseElementType(Field->getType());
4937 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4938 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4939 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4940 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004941 Diag(CurrentLocation, diag::note_member_synthesized_at)
4942 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004943 Invalid = true;
4944 continue;
4945 }
4946
4947 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004948 if (FieldType->isIncompleteArrayType()) {
4949 assert(ClassDecl->hasFlexibleArrayMember() &&
4950 "Incomplete array type is not valid");
4951 continue;
4952 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004953
4954 // Build references to the field in the object we're copying from and to.
4955 CXXScopeSpec SS; // Intentionally empty
4956 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4957 LookupMemberName);
4958 MemberLookup.addDecl(*Field);
4959 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00004960 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004961 Loc, /*IsArrow=*/false,
4962 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00004963 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00004964 Loc, /*IsArrow=*/true,
4965 SS, 0, MemberLookup, 0);
4966 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4967 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4968
4969 // If the field should be copied with __builtin_memcpy rather than via
4970 // explicit assignments, do so. This optimization only applies for arrays
4971 // of scalars and arrays of class type with trivial copy-assignment
4972 // operators.
4973 if (FieldType->isArrayType() &&
4974 (!BaseType->isRecordType() ||
4975 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4976 ->hasTrivialCopyAssignment())) {
4977 // Compute the size of the memory buffer to be copied.
4978 QualType SizeType = Context.getSizeType();
4979 llvm::APInt Size(Context.getTypeSize(SizeType),
4980 Context.getTypeSizeInChars(BaseType).getQuantity());
4981 for (const ConstantArrayType *Array
4982 = Context.getAsConstantArrayType(FieldType);
4983 Array;
4984 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4985 llvm::APInt ArraySize = Array->getSize();
4986 ArraySize.zextOrTrunc(Size.getBitWidth());
4987 Size *= ArraySize;
4988 }
4989
4990 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00004991 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
4992 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004993
4994 bool NeedsCollectableMemCpy =
4995 (BaseType->isRecordType() &&
4996 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
4997
4998 if (NeedsCollectableMemCpy) {
4999 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005000 // Create a reference to the __builtin_objc_memmove_collectable function.
5001 LookupResult R(*this,
5002 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005003 Loc, LookupOrdinaryName);
5004 LookupName(R, TUScope, true);
5005
5006 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5007 if (!CollectableMemCpy) {
5008 // Something went horribly wrong earlier, and we will have
5009 // complained about it.
5010 Invalid = true;
5011 continue;
5012 }
5013
5014 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5015 CollectableMemCpy->getType(),
5016 Loc, 0).takeAs<Expr>();
5017 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5018 }
5019 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005020 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005021 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005022 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5023 LookupOrdinaryName);
5024 LookupName(R, TUScope, true);
5025
5026 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5027 if (!BuiltinMemCpy) {
5028 // Something went horribly wrong earlier, and we will have complained
5029 // about it.
5030 Invalid = true;
5031 continue;
5032 }
5033
5034 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5035 BuiltinMemCpy->getType(),
5036 Loc, 0).takeAs<Expr>();
5037 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5038 }
5039
John McCall37ad5512010-08-23 06:44:23 +00005040 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005041 CallArgs.push_back(To.takeAs<Expr>());
5042 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005043 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005044 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005045 if (NeedsCollectableMemCpy)
5046 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005047 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005048 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005049 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005050 else
5051 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005052 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005053 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005054 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005055
Douglas Gregorb139cd52010-05-01 20:49:11 +00005056 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5057 Statements.push_back(Call.takeAs<Expr>());
5058 continue;
5059 }
5060
5061 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005062 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005063 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005064 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005065 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005066 Diag(CurrentLocation, diag::note_member_synthesized_at)
5067 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5068 CopyAssignOperator->setInvalidDecl();
5069 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005070 }
5071
5072 // Success! Record the copy.
5073 Statements.push_back(Copy.takeAs<Stmt>());
5074 }
5075
5076 if (!Invalid) {
5077 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005078 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005079
John McCalldadc5752010-08-24 06:29:42 +00005080 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005081 if (Return.isInvalid())
5082 Invalid = true;
5083 else {
5084 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005085
5086 if (Trap.hasErrorOccurred()) {
5087 Diag(CurrentLocation, diag::note_member_synthesized_at)
5088 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5089 Invalid = true;
5090 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005091 }
5092 }
5093
5094 if (Invalid) {
5095 CopyAssignOperator->setInvalidDecl();
5096 return;
5097 }
5098
John McCalldadc5752010-08-24 06:29:42 +00005099 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005100 /*isStmtExpr=*/false);
5101 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5102 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005103}
5104
Douglas Gregor0be31a22010-07-02 17:43:08 +00005105CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5106 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005107 // C++ [class.copy]p4:
5108 // If the class definition does not explicitly declare a copy
5109 // constructor, one is declared implicitly.
5110
Douglas Gregor54be3392010-07-01 17:57:27 +00005111 // C++ [class.copy]p5:
5112 // The implicitly-declared copy constructor for a class X will
5113 // have the form
5114 //
5115 // X::X(const X&)
5116 //
5117 // if
5118 bool HasConstCopyConstructor = true;
5119
5120 // -- each direct or virtual base class B of X has a copy
5121 // constructor whose first parameter is of type const B& or
5122 // const volatile B&, and
5123 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5124 BaseEnd = ClassDecl->bases_end();
5125 HasConstCopyConstructor && Base != BaseEnd;
5126 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005127 // Virtual bases are handled below.
5128 if (Base->isVirtual())
5129 continue;
5130
Douglas Gregora6d69502010-07-02 23:41:54 +00005131 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005132 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005133 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5134 DeclareImplicitCopyConstructor(BaseClassDecl);
5135
Douglas Gregorcfe68222010-07-01 18:27:03 +00005136 HasConstCopyConstructor
5137 = BaseClassDecl->hasConstCopyConstructor(Context);
5138 }
5139
5140 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5141 BaseEnd = ClassDecl->vbases_end();
5142 HasConstCopyConstructor && Base != BaseEnd;
5143 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005144 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005145 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005146 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5147 DeclareImplicitCopyConstructor(BaseClassDecl);
5148
Douglas Gregor54be3392010-07-01 17:57:27 +00005149 HasConstCopyConstructor
5150 = BaseClassDecl->hasConstCopyConstructor(Context);
5151 }
5152
5153 // -- for all the nonstatic data members of X that are of a
5154 // class type M (or array thereof), each such class type
5155 // has a copy constructor whose first parameter is of type
5156 // const M& or const volatile M&.
5157 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5158 FieldEnd = ClassDecl->field_end();
5159 HasConstCopyConstructor && Field != FieldEnd;
5160 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005161 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005162 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005163 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005164 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005165 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5166 DeclareImplicitCopyConstructor(FieldClassDecl);
5167
Douglas Gregor54be3392010-07-01 17:57:27 +00005168 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005169 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005170 }
5171 }
5172
5173 // Otherwise, the implicitly declared copy constructor will have
5174 // the form
5175 //
5176 // X::X(X&)
5177 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5178 QualType ArgType = ClassType;
5179 if (HasConstCopyConstructor)
5180 ArgType = ArgType.withConst();
5181 ArgType = Context.getLValueReferenceType(ArgType);
5182
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005183 // C++ [except.spec]p14:
5184 // An implicitly declared special member function (Clause 12) shall have an
5185 // exception-specification. [...]
5186 ImplicitExceptionSpecification ExceptSpec(Context);
5187 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5189 BaseEnd = ClassDecl->bases_end();
5190 Base != BaseEnd;
5191 ++Base) {
5192 // Virtual bases are handled below.
5193 if (Base->isVirtual())
5194 continue;
5195
Douglas Gregora6d69502010-07-02 23:41:54 +00005196 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005197 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005198 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5199 DeclareImplicitCopyConstructor(BaseClassDecl);
5200
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005201 if (CXXConstructorDecl *CopyConstructor
5202 = BaseClassDecl->getCopyConstructor(Context, Quals))
5203 ExceptSpec.CalledDecl(CopyConstructor);
5204 }
5205 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5206 BaseEnd = ClassDecl->vbases_end();
5207 Base != BaseEnd;
5208 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005209 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005210 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005211 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5212 DeclareImplicitCopyConstructor(BaseClassDecl);
5213
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005214 if (CXXConstructorDecl *CopyConstructor
5215 = BaseClassDecl->getCopyConstructor(Context, Quals))
5216 ExceptSpec.CalledDecl(CopyConstructor);
5217 }
5218 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5219 FieldEnd = ClassDecl->field_end();
5220 Field != FieldEnd;
5221 ++Field) {
5222 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5223 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005224 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005225 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005226 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5227 DeclareImplicitCopyConstructor(FieldClassDecl);
5228
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005229 if (CXXConstructorDecl *CopyConstructor
5230 = FieldClassDecl->getCopyConstructor(Context, Quals))
5231 ExceptSpec.CalledDecl(CopyConstructor);
5232 }
5233 }
5234
Douglas Gregor54be3392010-07-01 17:57:27 +00005235 // An implicitly-declared copy constructor is an inline public
5236 // member of its class.
5237 DeclarationName Name
5238 = Context.DeclarationNames.getCXXConstructorName(
5239 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005240 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005241 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005242 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005243 Context.getFunctionType(Context.VoidTy,
5244 &ArgType, 1,
5245 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005246 ExceptSpec.hasExceptionSpecification(),
5247 ExceptSpec.hasAnyExceptionSpecification(),
5248 ExceptSpec.size(),
5249 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005250 FunctionType::ExtInfo()),
5251 /*TInfo=*/0,
5252 /*isExplicit=*/false,
5253 /*isInline=*/true,
5254 /*isImplicitlyDeclared=*/true);
5255 CopyConstructor->setAccess(AS_public);
5256 CopyConstructor->setImplicit();
5257 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5258
Douglas Gregora6d69502010-07-02 23:41:54 +00005259 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005260 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5261
Douglas Gregor54be3392010-07-01 17:57:27 +00005262 // Add the parameter to the constructor.
5263 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5264 ClassDecl->getLocation(),
5265 /*IdentifierInfo=*/0,
5266 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005267 SC_None,
5268 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005269 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005270 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005271 PushOnScopeChains(CopyConstructor, S, false);
5272 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005273
5274 return CopyConstructor;
5275}
5276
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005277void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5278 CXXConstructorDecl *CopyConstructor,
5279 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005280 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005281 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005282 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005283 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005284
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005285 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005286 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005287
Douglas Gregora57478e2010-05-01 15:04:51 +00005288 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005289 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005290
Douglas Gregor54818f02010-05-12 16:39:35 +00005291 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5292 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005293 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005294 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005295 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005296 } else {
5297 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5298 CopyConstructor->getLocation(),
5299 MultiStmtArg(*this, 0, 0),
5300 /*isStmtExpr=*/false)
5301 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005302 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005303
5304 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005305}
5306
John McCalldadc5752010-08-24 06:29:42 +00005307ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005308Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005309 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005310 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005311 bool RequiresZeroInit,
John McCallbfd822c2010-08-24 07:32:53 +00005312 unsigned ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005313 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005314
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005315 // C++0x [class.copy]p34:
5316 // When certain criteria are met, an implementation is allowed to
5317 // omit the copy/move construction of a class object, even if the
5318 // copy/move constructor and/or destructor for the object have
5319 // side effects. [...]
5320 // - when a temporary class object that has not been bound to a
5321 // reference (12.2) would be copied/moved to a class object
5322 // with the same cv-unqualified type, the copy/move operation
5323 // can be omitted by constructing the temporary object
5324 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005325 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5326 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005327 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005328 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005329 }
Mike Stump11289f42009-09-09 15:08:12 +00005330
5331 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005332 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005333 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00005334}
5335
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005336/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5337/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005338ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005339Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5340 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005341 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005342 bool RequiresZeroInit,
John McCallbfd822c2010-08-24 07:32:53 +00005343 unsigned ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005344 unsigned NumExprs = ExprArgs.size();
5345 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005346
Douglas Gregor27381f32009-11-23 12:27:39 +00005347 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005348 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005349 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005350 RequiresZeroInit,
5351 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005352}
5353
Mike Stump11289f42009-09-09 15:08:12 +00005354bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005355 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005356 MultiExprArg Exprs) {
John McCalldadc5752010-08-24 06:29:42 +00005357 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005358 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00005359 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005360 if (TempResult.isInvalid())
5361 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005362
Anders Carlsson6eb55572009-08-25 05:12:04 +00005363 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005364 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005365 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005366 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005367 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005368
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005369 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005370}
5371
John McCall03c48482010-02-02 09:10:11 +00005372void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5373 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005374 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005375 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005376 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005377 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005378 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005379 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005380 << VD->getDeclName()
5381 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005382
John McCall386dfc72010-09-18 05:25:11 +00005383 // TODO: this should be re-enabled for static locals by !CXAAtExit
5384 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005385 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005386 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005387}
5388
Mike Stump11289f42009-09-09 15:08:12 +00005389/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005390/// ActOnDeclarator, when a C++ direct initializer is present.
5391/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005392void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005393 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005394 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005395 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005396 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005397
5398 // If there is no declaration, there was an error parsing it. Just ignore
5399 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005400 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005401 return;
Mike Stump11289f42009-09-09 15:08:12 +00005402
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005403 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5404 if (!VDecl) {
5405 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5406 RealDecl->setInvalidDecl();
5407 return;
5408 }
5409
Douglas Gregor402250f2009-08-26 21:14:46 +00005410 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005411 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005412 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5413 //
5414 // Clients that want to distinguish between the two forms, can check for
5415 // direct initializer using VarDecl::hasCXXDirectInitializer().
5416 // A major benefit is that clients that don't particularly care about which
5417 // exactly form was it (like the CodeGen) can handle both cases without
5418 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005419
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005420 // C++ 8.5p11:
5421 // The form of initialization (using parentheses or '=') is generally
5422 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005423 // class type.
5424
Douglas Gregor50dc2192010-02-11 22:55:30 +00005425 if (!VDecl->getType()->isDependentType() &&
5426 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005427 diag::err_typecheck_decl_incomplete_type)) {
5428 VDecl->setInvalidDecl();
5429 return;
5430 }
5431
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005432 // The variable can not have an abstract class type.
5433 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5434 diag::err_abstract_type_in_decl,
5435 AbstractVariableType))
5436 VDecl->setInvalidDecl();
5437
Sebastian Redl5ca79842010-02-01 20:16:42 +00005438 const VarDecl *Def;
5439 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005440 Diag(VDecl->getLocation(), diag::err_redefinition)
5441 << VDecl->getDeclName();
5442 Diag(Def->getLocation(), diag::note_previous_definition);
5443 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005444 return;
5445 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005446
Douglas Gregorf0f83692010-08-24 05:27:49 +00005447 // C++ [class.static.data]p4
5448 // If a static data member is of const integral or const
5449 // enumeration type, its declaration in the class definition can
5450 // specify a constant-initializer which shall be an integral
5451 // constant expression (5.19). In that case, the member can appear
5452 // in integral constant expressions. The member shall still be
5453 // defined in a namespace scope if it is used in the program and the
5454 // namespace scope definition shall not contain an initializer.
5455 //
5456 // We already performed a redefinition check above, but for static
5457 // data members we also need to check whether there was an in-class
5458 // declaration with an initializer.
5459 const VarDecl* PrevInit = 0;
5460 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5461 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5462 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5463 return;
5464 }
5465
Douglas Gregor50dc2192010-02-11 22:55:30 +00005466 // If either the declaration has a dependent type or if any of the
5467 // expressions is type-dependent, we represent the initialization
5468 // via a ParenListExpr for later use during template instantiation.
5469 if (VDecl->getType()->isDependentType() ||
5470 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5471 // Let clients know that initialization was done with a direct initializer.
5472 VDecl->setCXXDirectInitializer(true);
5473
5474 // Store the initialization expressions as a ParenListExpr.
5475 unsigned NumExprs = Exprs.size();
5476 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5477 (Expr **)Exprs.release(),
5478 NumExprs, RParenLoc));
5479 return;
5480 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005481
5482 // Capture the variable that is being initialized and the style of
5483 // initialization.
5484 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5485
5486 // FIXME: Poor source location information.
5487 InitializationKind Kind
5488 = InitializationKind::CreateDirect(VDecl->getLocation(),
5489 LParenLoc, RParenLoc);
5490
5491 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005492 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005493 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005494 if (Result.isInvalid()) {
5495 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005496 return;
5497 }
John McCallacf0ee52010-10-08 02:01:28 +00005498
5499 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005500
John McCallb268a282010-08-23 23:25:46 +00005501 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregord5058122010-02-11 01:19:42 +00005502 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005503 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005504
John McCall8b0f4ff2010-08-02 21:13:48 +00005505 if (!VDecl->isInvalidDecl() &&
5506 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005507 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005508 !VDecl->getInit()->isConstantInitializer(Context,
5509 VDecl->getType()->isReferenceType()))
5510 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5511 << VDecl->getInit()->getSourceRange();
5512
John McCall03c48482010-02-02 09:10:11 +00005513 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5514 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005515}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005516
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005517/// \brief Given a constructor and the set of arguments provided for the
5518/// constructor, convert the arguments and add any required default arguments
5519/// to form a proper call to this constructor.
5520///
5521/// \returns true if an error occurred, false otherwise.
5522bool
5523Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5524 MultiExprArg ArgsPtr,
5525 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005526 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005527 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5528 unsigned NumArgs = ArgsPtr.size();
5529 Expr **Args = (Expr **)ArgsPtr.get();
5530
5531 const FunctionProtoType *Proto
5532 = Constructor->getType()->getAs<FunctionProtoType>();
5533 assert(Proto && "Constructor without a prototype?");
5534 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005535
5536 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005537 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005538 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005539 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005540 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005541
5542 VariadicCallType CallType =
5543 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5544 llvm::SmallVector<Expr *, 8> AllArgs;
5545 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5546 Proto, 0, Args, NumArgs, AllArgs,
5547 CallType);
5548 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5549 ConvertedArgs.push_back(AllArgs[i]);
5550 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005551}
5552
Anders Carlssone363c8e2009-12-12 00:32:00 +00005553static inline bool
5554CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5555 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005556 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005557 if (isa<NamespaceDecl>(DC)) {
5558 return SemaRef.Diag(FnDecl->getLocation(),
5559 diag::err_operator_new_delete_declared_in_namespace)
5560 << FnDecl->getDeclName();
5561 }
5562
5563 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005564 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005565 return SemaRef.Diag(FnDecl->getLocation(),
5566 diag::err_operator_new_delete_declared_static)
5567 << FnDecl->getDeclName();
5568 }
5569
Anders Carlsson60659a82009-12-12 02:43:16 +00005570 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005571}
5572
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005573static inline bool
5574CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5575 CanQualType ExpectedResultType,
5576 CanQualType ExpectedFirstParamType,
5577 unsigned DependentParamTypeDiag,
5578 unsigned InvalidParamTypeDiag) {
5579 QualType ResultType =
5580 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5581
5582 // Check that the result type is not dependent.
5583 if (ResultType->isDependentType())
5584 return SemaRef.Diag(FnDecl->getLocation(),
5585 diag::err_operator_new_delete_dependent_result_type)
5586 << FnDecl->getDeclName() << ExpectedResultType;
5587
5588 // Check that the result type is what we expect.
5589 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5590 return SemaRef.Diag(FnDecl->getLocation(),
5591 diag::err_operator_new_delete_invalid_result_type)
5592 << FnDecl->getDeclName() << ExpectedResultType;
5593
5594 // A function template must have at least 2 parameters.
5595 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5596 return SemaRef.Diag(FnDecl->getLocation(),
5597 diag::err_operator_new_delete_template_too_few_parameters)
5598 << FnDecl->getDeclName();
5599
5600 // The function decl must have at least 1 parameter.
5601 if (FnDecl->getNumParams() == 0)
5602 return SemaRef.Diag(FnDecl->getLocation(),
5603 diag::err_operator_new_delete_too_few_parameters)
5604 << FnDecl->getDeclName();
5605
5606 // Check the the first parameter type is not dependent.
5607 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5608 if (FirstParamType->isDependentType())
5609 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5610 << FnDecl->getDeclName() << ExpectedFirstParamType;
5611
5612 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005613 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005614 ExpectedFirstParamType)
5615 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5616 << FnDecl->getDeclName() << ExpectedFirstParamType;
5617
5618 return false;
5619}
5620
Anders Carlsson12308f42009-12-11 23:23:22 +00005621static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005622CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005623 // C++ [basic.stc.dynamic.allocation]p1:
5624 // A program is ill-formed if an allocation function is declared in a
5625 // namespace scope other than global scope or declared static in global
5626 // scope.
5627 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5628 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005629
5630 CanQualType SizeTy =
5631 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5632
5633 // C++ [basic.stc.dynamic.allocation]p1:
5634 // The return type shall be void*. The first parameter shall have type
5635 // std::size_t.
5636 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5637 SizeTy,
5638 diag::err_operator_new_dependent_param_type,
5639 diag::err_operator_new_param_type))
5640 return true;
5641
5642 // C++ [basic.stc.dynamic.allocation]p1:
5643 // The first parameter shall not have an associated default argument.
5644 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005645 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005646 diag::err_operator_new_default_arg)
5647 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5648
5649 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005650}
5651
5652static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005653CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5654 // C++ [basic.stc.dynamic.deallocation]p1:
5655 // A program is ill-formed if deallocation functions are declared in a
5656 // namespace scope other than global scope or declared static in global
5657 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005658 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5659 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005660
5661 // C++ [basic.stc.dynamic.deallocation]p2:
5662 // Each deallocation function shall return void and its first parameter
5663 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005664 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5665 SemaRef.Context.VoidPtrTy,
5666 diag::err_operator_delete_dependent_param_type,
5667 diag::err_operator_delete_param_type))
5668 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005669
Anders Carlsson12308f42009-12-11 23:23:22 +00005670 return false;
5671}
5672
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005673/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5674/// of this overloaded operator is well-formed. If so, returns false;
5675/// otherwise, emits appropriate diagnostics and returns true.
5676bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005677 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005678 "Expected an overloaded operator declaration");
5679
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005680 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5681
Mike Stump11289f42009-09-09 15:08:12 +00005682 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005683 // The allocation and deallocation functions, operator new,
5684 // operator new[], operator delete and operator delete[], are
5685 // described completely in 3.7.3. The attributes and restrictions
5686 // found in the rest of this subclause do not apply to them unless
5687 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005688 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005689 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005690
Anders Carlsson22f443f2009-12-12 00:26:23 +00005691 if (Op == OO_New || Op == OO_Array_New)
5692 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005693
5694 // C++ [over.oper]p6:
5695 // An operator function shall either be a non-static member
5696 // function or be a non-member function and have at least one
5697 // parameter whose type is a class, a reference to a class, an
5698 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005699 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5700 if (MethodDecl->isStatic())
5701 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005702 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005703 } else {
5704 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005705 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5706 ParamEnd = FnDecl->param_end();
5707 Param != ParamEnd; ++Param) {
5708 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005709 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5710 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005711 ClassOrEnumParam = true;
5712 break;
5713 }
5714 }
5715
Douglas Gregord69246b2008-11-17 16:14:12 +00005716 if (!ClassOrEnumParam)
5717 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005718 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005719 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005720 }
5721
5722 // C++ [over.oper]p8:
5723 // An operator function cannot have default arguments (8.3.6),
5724 // except where explicitly stated below.
5725 //
Mike Stump11289f42009-09-09 15:08:12 +00005726 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005727 // (C++ [over.call]p1).
5728 if (Op != OO_Call) {
5729 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5730 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005731 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005732 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005733 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005734 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005735 }
5736 }
5737
Douglas Gregor6cf08062008-11-10 13:38:07 +00005738 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5739 { false, false, false }
5740#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5741 , { Unary, Binary, MemberOnly }
5742#include "clang/Basic/OperatorKinds.def"
5743 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005744
Douglas Gregor6cf08062008-11-10 13:38:07 +00005745 bool CanBeUnaryOperator = OperatorUses[Op][0];
5746 bool CanBeBinaryOperator = OperatorUses[Op][1];
5747 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005748
5749 // C++ [over.oper]p8:
5750 // [...] Operator functions cannot have more or fewer parameters
5751 // than the number required for the corresponding operator, as
5752 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005753 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005754 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005755 if (Op != OO_Call &&
5756 ((NumParams == 1 && !CanBeUnaryOperator) ||
5757 (NumParams == 2 && !CanBeBinaryOperator) ||
5758 (NumParams < 1) || (NumParams > 2))) {
5759 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005760 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005761 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005762 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005763 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005764 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005765 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005766 assert(CanBeBinaryOperator &&
5767 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005768 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005769 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005770
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005771 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005772 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005773 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005774
Douglas Gregord69246b2008-11-17 16:14:12 +00005775 // Overloaded operators other than operator() cannot be variadic.
5776 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005777 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005778 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005779 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005780 }
5781
5782 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005783 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5784 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005785 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005786 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005787 }
5788
5789 // C++ [over.inc]p1:
5790 // The user-defined function called operator++ implements the
5791 // prefix and postfix ++ operator. If this function is a member
5792 // function with no parameters, or a non-member function with one
5793 // parameter of class or enumeration type, it defines the prefix
5794 // increment operator ++ for objects of that type. If the function
5795 // is a member function with one parameter (which shall be of type
5796 // int) or a non-member function with two parameters (the second
5797 // of which shall be of type int), it defines the postfix
5798 // increment operator ++ for objects of that type.
5799 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5800 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5801 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005802 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005803 ParamIsInt = BT->getKind() == BuiltinType::Int;
5804
Chris Lattner2b786902008-11-21 07:50:02 +00005805 if (!ParamIsInt)
5806 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005807 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005808 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005809 }
5810
Douglas Gregord69246b2008-11-17 16:14:12 +00005811 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005812}
Chris Lattner3b024a32008-12-17 07:09:26 +00005813
Alexis Huntc88db062010-01-13 09:01:02 +00005814/// CheckLiteralOperatorDeclaration - Check whether the declaration
5815/// of this literal operator function is well-formed. If so, returns
5816/// false; otherwise, emits appropriate diagnostics and returns true.
5817bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5818 DeclContext *DC = FnDecl->getDeclContext();
5819 Decl::Kind Kind = DC->getDeclKind();
5820 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5821 Kind != Decl::LinkageSpec) {
5822 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5823 << FnDecl->getDeclName();
5824 return true;
5825 }
5826
5827 bool Valid = false;
5828
Alexis Hunt7dd26172010-04-07 23:11:06 +00005829 // template <char...> type operator "" name() is the only valid template
5830 // signature, and the only valid signature with no parameters.
5831 if (FnDecl->param_size() == 0) {
5832 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5833 // Must have only one template parameter
5834 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5835 if (Params->size() == 1) {
5836 NonTypeTemplateParmDecl *PmDecl =
5837 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005838
Alexis Hunt7dd26172010-04-07 23:11:06 +00005839 // The template parameter must be a char parameter pack.
5840 // FIXME: This test will always fail because non-type parameter packs
5841 // have not been implemented.
5842 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5843 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5844 Valid = true;
5845 }
5846 }
5847 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005848 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005849 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5850
Alexis Huntc88db062010-01-13 09:01:02 +00005851 QualType T = (*Param)->getType();
5852
Alexis Hunt079a6f72010-04-07 22:57:35 +00005853 // unsigned long long int, long double, and any character type are allowed
5854 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005855 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5856 Context.hasSameType(T, Context.LongDoubleTy) ||
5857 Context.hasSameType(T, Context.CharTy) ||
5858 Context.hasSameType(T, Context.WCharTy) ||
5859 Context.hasSameType(T, Context.Char16Ty) ||
5860 Context.hasSameType(T, Context.Char32Ty)) {
5861 if (++Param == FnDecl->param_end())
5862 Valid = true;
5863 goto FinishedParams;
5864 }
5865
Alexis Hunt079a6f72010-04-07 22:57:35 +00005866 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005867 const PointerType *PT = T->getAs<PointerType>();
5868 if (!PT)
5869 goto FinishedParams;
5870 T = PT->getPointeeType();
5871 if (!T.isConstQualified())
5872 goto FinishedParams;
5873 T = T.getUnqualifiedType();
5874
5875 // Move on to the second parameter;
5876 ++Param;
5877
5878 // If there is no second parameter, the first must be a const char *
5879 if (Param == FnDecl->param_end()) {
5880 if (Context.hasSameType(T, Context.CharTy))
5881 Valid = true;
5882 goto FinishedParams;
5883 }
5884
5885 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5886 // are allowed as the first parameter to a two-parameter function
5887 if (!(Context.hasSameType(T, Context.CharTy) ||
5888 Context.hasSameType(T, Context.WCharTy) ||
5889 Context.hasSameType(T, Context.Char16Ty) ||
5890 Context.hasSameType(T, Context.Char32Ty)))
5891 goto FinishedParams;
5892
5893 // The second and final parameter must be an std::size_t
5894 T = (*Param)->getType().getUnqualifiedType();
5895 if (Context.hasSameType(T, Context.getSizeType()) &&
5896 ++Param == FnDecl->param_end())
5897 Valid = true;
5898 }
5899
5900 // FIXME: This diagnostic is absolutely terrible.
5901FinishedParams:
5902 if (!Valid) {
5903 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5904 << FnDecl->getDeclName();
5905 return true;
5906 }
5907
5908 return false;
5909}
5910
Douglas Gregor07665a62009-01-05 19:45:36 +00005911/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5912/// linkage specification, including the language and (if present)
5913/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5914/// the location of the language string literal, which is provided
5915/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5916/// the '{' brace. Otherwise, this linkage specification does not
5917/// have any braces.
John McCall48871652010-08-21 09:40:31 +00005918Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005919 SourceLocation ExternLoc,
5920 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005921 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005922 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005923 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005924 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005925 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005926 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005927 Language = LinkageSpecDecl::lang_cxx;
5928 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005929 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00005930 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00005931 }
Mike Stump11289f42009-09-09 15:08:12 +00005932
Chris Lattner438e5012008-12-17 07:13:27 +00005933 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005934
Douglas Gregor07665a62009-01-05 19:45:36 +00005935 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005936 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005937 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005938 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005939 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00005940 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00005941}
5942
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00005943/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00005944/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5945/// valid, it's the position of the closing '}' brace in a linkage
5946/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00005947Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
5948 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00005949 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005950 if (LinkageSpec)
5951 PopDeclContext();
5952 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005953}
5954
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005955/// \brief Perform semantic analysis for the variable declaration that
5956/// occurs within a C++ catch clause, returning the newly-created
5957/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005958VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00005959 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005960 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005961 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005962 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005963 QualType ExDeclType = TInfo->getType();
5964
Sebastian Redl54c04d42008-12-22 19:15:10 +00005965 // Arrays and functions decay.
5966 if (ExDeclType->isArrayType())
5967 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5968 else if (ExDeclType->isFunctionType())
5969 ExDeclType = Context.getPointerType(ExDeclType);
5970
5971 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5972 // The exception-declaration shall not denote a pointer or reference to an
5973 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005974 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005975 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005976 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00005977 Invalid = true;
5978 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005979
Douglas Gregor104ee002010-03-08 01:47:36 +00005980 // GCC allows catching pointers and references to incomplete types
5981 // as an extension; so do we, but we warn by default.
5982
Sebastian Redl54c04d42008-12-22 19:15:10 +00005983 QualType BaseType = ExDeclType;
5984 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005985 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005986 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005987 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005988 BaseType = Ptr->getPointeeType();
5989 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005990 DK = diag::ext_catch_incomplete_ptr;
5991 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005992 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005993 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005994 BaseType = Ref->getPointeeType();
5995 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005996 DK = diag::ext_catch_incomplete_ref;
5997 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005998 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005999 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006000 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6001 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006002 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006003
Mike Stump11289f42009-09-09 15:08:12 +00006004 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006005 RequireNonAbstractType(Loc, ExDeclType,
6006 diag::err_abstract_type_in_decl,
6007 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006008 Invalid = true;
6009
John McCall2ca705e2010-07-24 00:37:23 +00006010 // Only the non-fragile NeXT runtime currently supports C++ catches
6011 // of ObjC types, and no runtime supports catching ObjC types by value.
6012 if (!Invalid && getLangOptions().ObjC1) {
6013 QualType T = ExDeclType;
6014 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6015 T = RT->getPointeeType();
6016
6017 if (T->isObjCObjectType()) {
6018 Diag(Loc, diag::err_objc_object_catch);
6019 Invalid = true;
6020 } else if (T->isObjCObjectPointerType()) {
6021 if (!getLangOptions().NeXTRuntime) {
6022 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6023 Invalid = true;
6024 } else if (!getLangOptions().ObjCNonFragileABI) {
6025 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6026 Invalid = true;
6027 }
6028 }
6029 }
6030
Mike Stump11289f42009-09-09 15:08:12 +00006031 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006032 Name, ExDeclType, TInfo, SC_None,
6033 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006034 ExDecl->setExceptionVariable(true);
6035
Douglas Gregor6de584c2010-03-05 23:38:39 +00006036 if (!Invalid) {
6037 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6038 // C++ [except.handle]p16:
6039 // The object declared in an exception-declaration or, if the
6040 // exception-declaration does not specify a name, a temporary (12.2) is
6041 // copy-initialized (8.5) from the exception object. [...]
6042 // The object is destroyed when the handler exits, after the destruction
6043 // of any automatic objects initialized within the handler.
6044 //
6045 // We just pretend to initialize the object with itself, then make sure
6046 // it can be destroyed later.
6047 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6048 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6049 Loc, ExDeclType, 0);
6050 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6051 SourceLocation());
6052 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006053 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006054 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006055 if (Result.isInvalid())
6056 Invalid = true;
6057 else
6058 FinalizeVarWithDestructor(ExDecl, RecordTy);
6059 }
6060 }
6061
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006062 if (Invalid)
6063 ExDecl->setInvalidDecl();
6064
6065 return ExDecl;
6066}
6067
6068/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6069/// handler.
John McCall48871652010-08-21 09:40:31 +00006070Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006071 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6072 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006073
6074 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006075 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006076 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006077 LookupOrdinaryName,
6078 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006079 // The scope should be freshly made just for us. There is just no way
6080 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006081 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006082 if (PrevDecl->isTemplateParameter()) {
6083 // Maybe we will complain about the shadowed template parameter.
6084 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006085 }
6086 }
6087
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006088 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006089 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6090 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006091 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006092 }
6093
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006094 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006095 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006096 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006097
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006098 if (Invalid)
6099 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006100
Sebastian Redl54c04d42008-12-22 19:15:10 +00006101 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006102 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006103 PushOnScopeChains(ExDecl, S);
6104 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006105 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006106
Douglas Gregor758a8692009-06-17 21:51:59 +00006107 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006108 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006109}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006110
John McCall48871652010-08-21 09:40:31 +00006111Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006112 Expr *AssertExpr,
6113 Expr *AssertMessageExpr_) {
6114 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006115
Anders Carlsson54b26982009-03-14 00:33:21 +00006116 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6117 llvm::APSInt Value(32);
6118 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6119 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6120 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006121 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006122 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006123
Anders Carlsson54b26982009-03-14 00:33:21 +00006124 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006125 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006126 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006127 }
6128 }
Mike Stump11289f42009-09-09 15:08:12 +00006129
Mike Stump11289f42009-09-09 15:08:12 +00006130 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006131 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006132
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006133 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006134 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006135}
Sebastian Redlf769df52009-03-24 22:27:57 +00006136
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006137/// \brief Perform semantic analysis of the given friend type declaration.
6138///
6139/// \returns A friend declaration that.
6140FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6141 TypeSourceInfo *TSInfo) {
6142 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6143
6144 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006145 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006146
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006147 if (!getLangOptions().CPlusPlus0x) {
6148 // C++03 [class.friend]p2:
6149 // An elaborated-type-specifier shall be used in a friend declaration
6150 // for a class.*
6151 //
6152 // * The class-key of the elaborated-type-specifier is required.
6153 if (!ActiveTemplateInstantiations.empty()) {
6154 // Do not complain about the form of friend template types during
6155 // template instantiation; we will already have complained when the
6156 // template was declared.
6157 } else if (!T->isElaboratedTypeSpecifier()) {
6158 // If we evaluated the type to a record type, suggest putting
6159 // a tag in front.
6160 if (const RecordType *RT = T->getAs<RecordType>()) {
6161 RecordDecl *RD = RT->getDecl();
6162
6163 std::string InsertionText = std::string(" ") + RD->getKindName();
6164
6165 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6166 << (unsigned) RD->getTagKind()
6167 << T
6168 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6169 InsertionText);
6170 } else {
6171 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6172 << T
6173 << SourceRange(FriendLoc, TypeRange.getEnd());
6174 }
6175 } else if (T->getAs<EnumType>()) {
6176 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006177 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006178 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006179 }
6180 }
6181
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006182 // C++0x [class.friend]p3:
6183 // If the type specifier in a friend declaration designates a (possibly
6184 // cv-qualified) class type, that class is declared as a friend; otherwise,
6185 // the friend declaration is ignored.
6186
6187 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6188 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006189
6190 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6191}
6192
John McCall11083da2009-09-16 22:47:08 +00006193/// Handle a friend type declaration. This works in tandem with
6194/// ActOnTag.
6195///
6196/// Notes on friend class templates:
6197///
6198/// We generally treat friend class declarations as if they were
6199/// declaring a class. So, for example, the elaborated type specifier
6200/// in a friend declaration is required to obey the restrictions of a
6201/// class-head (i.e. no typedefs in the scope chain), template
6202/// parameters are required to match up with simple template-ids, &c.
6203/// However, unlike when declaring a template specialization, it's
6204/// okay to refer to a template specialization without an empty
6205/// template parameter declaration, e.g.
6206/// friend class A<T>::B<unsigned>;
6207/// We permit this as a special case; if there are any template
6208/// parameters present at all, require proper matching, i.e.
6209/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006210Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00006211 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006212 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006213
6214 assert(DS.isFriendSpecified());
6215 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6216
John McCall11083da2009-09-16 22:47:08 +00006217 // Try to convert the decl specifier to a type. This works for
6218 // friend templates because ActOnTag never produces a ClassTemplateDecl
6219 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006220 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006221 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6222 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006223 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006224 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006225
John McCall11083da2009-09-16 22:47:08 +00006226 // This is definitely an error in C++98. It's probably meant to
6227 // be forbidden in C++0x, too, but the specification is just
6228 // poorly written.
6229 //
6230 // The problem is with declarations like the following:
6231 // template <T> friend A<T>::foo;
6232 // where deciding whether a class C is a friend or not now hinges
6233 // on whether there exists an instantiation of A that causes
6234 // 'foo' to equal C. There are restrictions on class-heads
6235 // (which we declare (by fiat) elaborated friend declarations to
6236 // be) that makes this tractable.
6237 //
6238 // FIXME: handle "template <> friend class A<T>;", which
6239 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006240 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006241 Diag(Loc, diag::err_tagless_friend_type_template)
6242 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006243 return 0;
John McCall11083da2009-09-16 22:47:08 +00006244 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006245
John McCallaa74a0c2009-08-28 07:59:38 +00006246 // C++98 [class.friend]p1: A friend of a class is a function
6247 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006248 // This is fixed in DR77, which just barely didn't make the C++03
6249 // deadline. It's also a very silly restriction that seriously
6250 // affects inner classes and which nobody else seems to implement;
6251 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006252 //
6253 // But note that we could warn about it: it's always useless to
6254 // friend one of your own members (it's not, however, worthless to
6255 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006256
John McCall11083da2009-09-16 22:47:08 +00006257 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006258 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006259 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006260 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00006261 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006262 TSI,
John McCall11083da2009-09-16 22:47:08 +00006263 DS.getFriendSpecLoc());
6264 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006265 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6266
6267 if (!D)
John McCall48871652010-08-21 09:40:31 +00006268 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006269
John McCall11083da2009-09-16 22:47:08 +00006270 D->setAccess(AS_public);
6271 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006272
John McCall48871652010-08-21 09:40:31 +00006273 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006274}
6275
John McCall48871652010-08-21 09:40:31 +00006276Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6277 Declarator &D,
6278 bool IsDefinition,
John McCall2f212b32009-09-11 21:02:39 +00006279 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006280 const DeclSpec &DS = D.getDeclSpec();
6281
6282 assert(DS.isFriendSpecified());
6283 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6284
6285 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006286 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6287 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006288
6289 // C++ [class.friend]p1
6290 // A friend of a class is a function or class....
6291 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006292 // It *doesn't* see through dependent types, which is correct
6293 // according to [temp.arg.type]p3:
6294 // If a declaration acquires a function type through a
6295 // type dependent on a template-parameter and this causes
6296 // a declaration that does not use the syntactic form of a
6297 // function declarator to have a function type, the program
6298 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006299 if (!T->isFunctionType()) {
6300 Diag(Loc, diag::err_unexpected_friend);
6301
6302 // It might be worthwhile to try to recover by creating an
6303 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006304 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006305 }
6306
6307 // C++ [namespace.memdef]p3
6308 // - If a friend declaration in a non-local class first declares a
6309 // class or function, the friend class or function is a member
6310 // of the innermost enclosing namespace.
6311 // - The name of the friend is not found by simple name lookup
6312 // until a matching declaration is provided in that namespace
6313 // scope (either before or after the class declaration granting
6314 // friendship).
6315 // - If a friend function is called, its name may be found by the
6316 // name lookup that considers functions from namespaces and
6317 // classes associated with the types of the function arguments.
6318 // - When looking for a prior declaration of a class or a function
6319 // declared as a friend, scopes outside the innermost enclosing
6320 // namespace scope are not considered.
6321
John McCallaa74a0c2009-08-28 07:59:38 +00006322 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006323 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6324 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006325 assert(Name);
6326
John McCall07e91c02009-08-06 02:15:43 +00006327 // The context we found the declaration in, or in which we should
6328 // create the declaration.
6329 DeclContext *DC;
6330
6331 // FIXME: handle local classes
6332
6333 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006334 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006335 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006336 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6337 DC = computeDeclContext(ScopeQual);
6338
6339 // FIXME: handle dependent contexts
John McCall48871652010-08-21 09:40:31 +00006340 if (!DC) return 0;
6341 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall07e91c02009-08-06 02:15:43 +00006342
John McCall1f82f242009-11-18 22:49:29 +00006343 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006344
John McCall45831862010-05-28 01:41:47 +00006345 // Ignore things found implicitly in the wrong scope.
John McCall07e91c02009-08-06 02:15:43 +00006346 // TODO: better diagnostics for this case. Suggesting the right
6347 // qualified scope would be nice...
John McCall45831862010-05-28 01:41:47 +00006348 LookupResult::Filter F = Previous.makeFilter();
6349 while (F.hasNext()) {
6350 NamedDecl *D = F.next();
Sebastian Redl50c68252010-08-31 00:36:30 +00006351 if (!DC->InEnclosingNamespaceSetOf(
6352 D->getDeclContext()->getRedeclContext()))
John McCall45831862010-05-28 01:41:47 +00006353 F.erase();
6354 }
6355 F.done();
6356
6357 if (Previous.empty()) {
John McCallaa74a0c2009-08-28 07:59:38 +00006358 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00006359 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCall48871652010-08-21 09:40:31 +00006360 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006361 }
6362
6363 // C++ [class.friend]p1: A friend of a class is a function or
6364 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006365 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00006366 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6367
John McCall07e91c02009-08-06 02:15:43 +00006368 // Otherwise walk out to the nearest namespace scope looking for matches.
6369 } else {
6370 // TODO: handle local class contexts.
6371
6372 DC = CurContext;
6373 while (true) {
6374 // Skip class contexts. If someone can cite chapter and verse
6375 // for this behavior, that would be nice --- it's what GCC and
6376 // EDG do, and it seems like a reasonable intent, but the spec
6377 // really only says that checks for unqualified existing
6378 // declarations should stop at the nearest enclosing namespace,
6379 // not that they should only consider the nearest enclosing
6380 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006381 while (DC->isRecord())
6382 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006383
John McCall1f82f242009-11-18 22:49:29 +00006384 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006385
6386 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00006387 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006388 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006389
John McCall07e91c02009-08-06 02:15:43 +00006390 if (DC->isFileContext()) break;
6391 DC = DC->getParent();
6392 }
6393
6394 // C++ [class.friend]p1: A friend of a class is a function or
6395 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006396 // C++0x changes this for both friend types and functions.
6397 // Most C++ 98 compilers do seem to give an error here, so
6398 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006399 if (!Previous.empty() && DC->Equals(CurContext)
6400 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006401 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6402 }
6403
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006404 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00006405 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006406 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6407 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6408 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006409 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006410 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6411 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006412 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006413 }
John McCall07e91c02009-08-06 02:15:43 +00006414 }
6415
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006416 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00006417 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006418 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006419 IsDefinition,
6420 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006421 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006422
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006423 assert(ND->getDeclContext() == DC);
6424 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006425
John McCall759e32b2009-08-31 22:39:49 +00006426 // Add the function declaration to the appropriate lookup tables,
6427 // adjusting the redeclarations list as necessary. We don't
6428 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006429 //
John McCall759e32b2009-08-31 22:39:49 +00006430 // Also update the scope-based lookup if the target context's
6431 // lookup context is in lexical scope.
6432 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006433 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006434 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006435 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006436 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006437 }
John McCallaa74a0c2009-08-28 07:59:38 +00006438
6439 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006440 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006441 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006442 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006443 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006444
John McCall48871652010-08-21 09:40:31 +00006445 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006446}
6447
John McCall48871652010-08-21 09:40:31 +00006448void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6449 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006450
Sebastian Redlf769df52009-03-24 22:27:57 +00006451 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6452 if (!Fn) {
6453 Diag(DelLoc, diag::err_deleted_non_function);
6454 return;
6455 }
6456 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6457 Diag(DelLoc, diag::err_deleted_decl_not_first);
6458 Diag(Prev->getLocation(), diag::note_previous_declaration);
6459 // If the declaration wasn't the first, we delete the function anyway for
6460 // recovery.
6461 }
6462 Fn->setDeleted();
6463}
Sebastian Redl4c018662009-04-27 21:33:24 +00006464
6465static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6466 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6467 ++CI) {
6468 Stmt *SubStmt = *CI;
6469 if (!SubStmt)
6470 continue;
6471 if (isa<ReturnStmt>(SubStmt))
6472 Self.Diag(SubStmt->getSourceRange().getBegin(),
6473 diag::err_return_in_constructor_handler);
6474 if (!isa<Expr>(SubStmt))
6475 SearchForReturnInStmt(Self, SubStmt);
6476 }
6477}
6478
6479void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6480 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6481 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6482 SearchForReturnInStmt(*this, Handler);
6483 }
6484}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006485
Mike Stump11289f42009-09-09 15:08:12 +00006486bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006487 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006488 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6489 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006490
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006491 if (Context.hasSameType(NewTy, OldTy) ||
6492 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006493 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006494
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006495 // Check if the return types are covariant
6496 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006497
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006498 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006499 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6500 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006501 NewClassTy = NewPT->getPointeeType();
6502 OldClassTy = OldPT->getPointeeType();
6503 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006504 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6505 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6506 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6507 NewClassTy = NewRT->getPointeeType();
6508 OldClassTy = OldRT->getPointeeType();
6509 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006510 }
6511 }
Mike Stump11289f42009-09-09 15:08:12 +00006512
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006513 // The return types aren't either both pointers or references to a class type.
6514 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006515 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006516 diag::err_different_return_type_for_overriding_virtual_function)
6517 << New->getDeclName() << NewTy << OldTy;
6518 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006519
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006520 return true;
6521 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006522
Anders Carlssone60365b2009-12-31 18:34:24 +00006523 // C++ [class.virtual]p6:
6524 // If the return type of D::f differs from the return type of B::f, the
6525 // class type in the return type of D::f shall be complete at the point of
6526 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006527 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6528 if (!RT->isBeingDefined() &&
6529 RequireCompleteType(New->getLocation(), NewClassTy,
6530 PDiag(diag::err_covariant_return_incomplete)
6531 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006532 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006533 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006534
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006535 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006536 // Check if the new class derives from the old class.
6537 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6538 Diag(New->getLocation(),
6539 diag::err_covariant_return_not_derived)
6540 << New->getDeclName() << NewTy << OldTy;
6541 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6542 return true;
6543 }
Mike Stump11289f42009-09-09 15:08:12 +00006544
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006545 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006546 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006547 diag::err_covariant_return_inaccessible_base,
6548 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6549 // FIXME: Should this point to the return type?
6550 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006551 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6552 return true;
6553 }
6554 }
Mike Stump11289f42009-09-09 15:08:12 +00006555
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006556 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006557 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006558 Diag(New->getLocation(),
6559 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006560 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006561 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6562 return true;
6563 };
Mike Stump11289f42009-09-09 15:08:12 +00006564
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006565
6566 // The new class type must have the same or less qualifiers as the old type.
6567 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6568 Diag(New->getLocation(),
6569 diag::err_covariant_return_type_class_type_more_qualified)
6570 << New->getDeclName() << NewTy << OldTy;
6571 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6572 return true;
6573 };
Mike Stump11289f42009-09-09 15:08:12 +00006574
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006575 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006576}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006577
Alexis Hunt96d5c762009-11-21 08:43:09 +00006578bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6579 const CXXMethodDecl *Old)
6580{
6581 if (Old->hasAttr<FinalAttr>()) {
6582 Diag(New->getLocation(), diag::err_final_function_overridden)
6583 << New->getDeclName();
6584 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6585 return true;
6586 }
6587
6588 return false;
6589}
6590
Douglas Gregor21920e372009-12-01 17:24:26 +00006591/// \brief Mark the given method pure.
6592///
6593/// \param Method the method to be marked pure.
6594///
6595/// \param InitRange the source range that covers the "0" initializer.
6596bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6597 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6598 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006599 return false;
6600 }
6601
6602 if (!Method->isInvalidDecl())
6603 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6604 << Method->getDeclName() << InitRange;
6605 return true;
6606}
6607
John McCall1f4ee7b2009-12-19 09:28:58 +00006608/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6609/// an initializer for the out-of-line declaration 'Dcl'. The scope
6610/// is a fresh scope pushed for just this purpose.
6611///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006612/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6613/// static data member of class X, names should be looked up in the scope of
6614/// class X.
John McCall48871652010-08-21 09:40:31 +00006615void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006616 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006617 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006618
John McCall1f4ee7b2009-12-19 09:28:58 +00006619 // We should only get called for declarations with scope specifiers, like:
6620 // int foo::bar;
6621 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006622 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006623}
6624
6625/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006626/// initializer for the out-of-line declaration 'D'.
6627void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006628 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006629 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006630
John McCall1f4ee7b2009-12-19 09:28:58 +00006631 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006632 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006633}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006634
6635/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6636/// C++ if/switch/while/for statement.
6637/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006638DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006639 // C++ 6.4p2:
6640 // The declarator shall not specify a function or an array.
6641 // The type-specifier-seq shall not contain typedef and shall not declare a
6642 // new class or enumeration.
6643 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6644 "Parser allowed 'typedef' as storage class of condition decl.");
6645
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006646 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006647 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6648 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006649
6650 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6651 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6652 // would be created and CXXConditionDeclExpr wants a VarDecl.
6653 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6654 << D.getSourceRange();
6655 return DeclResult();
6656 } else if (OwnedTag && OwnedTag->isDefinition()) {
6657 // The type-specifier-seq shall not declare a new class or enumeration.
6658 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6659 }
6660
John McCall48871652010-08-21 09:40:31 +00006661 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006662 if (!Dcl)
6663 return DeclResult();
6664
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006665 return Dcl;
6666}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006667
Douglas Gregor88d292c2010-05-13 16:44:06 +00006668void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6669 bool DefinitionRequired) {
6670 // Ignore any vtable uses in unevaluated operands or for classes that do
6671 // not have a vtable.
6672 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6673 CurContext->isDependentContext() ||
6674 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006675 return;
6676
Douglas Gregor88d292c2010-05-13 16:44:06 +00006677 // Try to insert this class into the map.
6678 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6679 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6680 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6681 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006682 // If we already had an entry, check to see if we are promoting this vtable
6683 // to required a definition. If so, we need to reappend to the VTableUses
6684 // list, since we may have already processed the first entry.
6685 if (DefinitionRequired && !Pos.first->second) {
6686 Pos.first->second = true;
6687 } else {
6688 // Otherwise, we can early exit.
6689 return;
6690 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006691 }
6692
6693 // Local classes need to have their virtual members marked
6694 // immediately. For all other classes, we mark their virtual members
6695 // at the end of the translation unit.
6696 if (Class->isLocalClass())
6697 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006698 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006699 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006700}
6701
Douglas Gregor88d292c2010-05-13 16:44:06 +00006702bool Sema::DefineUsedVTables() {
6703 // If any dynamic classes have their key function defined within
6704 // this translation unit, then those vtables are considered "used" and must
6705 // be emitted.
6706 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6707 if (const CXXMethodDecl *KeyFunction
6708 = Context.getKeyFunction(DynamicClasses[I])) {
6709 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006710 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006711 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6712 }
6713 }
6714
6715 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006716 return false;
6717
Douglas Gregor88d292c2010-05-13 16:44:06 +00006718 // Note: The VTableUses vector could grow as a result of marking
6719 // the members of a class as "used", so we check the size each
6720 // time through the loop and prefer indices (with are stable) to
6721 // iterators (which are not).
6722 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006723 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006724 if (!Class)
6725 continue;
6726
6727 SourceLocation Loc = VTableUses[I].second;
6728
6729 // If this class has a key function, but that key function is
6730 // defined in another translation unit, we don't need to emit the
6731 // vtable even though we're using it.
6732 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006733 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006734 switch (KeyFunction->getTemplateSpecializationKind()) {
6735 case TSK_Undeclared:
6736 case TSK_ExplicitSpecialization:
6737 case TSK_ExplicitInstantiationDeclaration:
6738 // The key function is in another translation unit.
6739 continue;
6740
6741 case TSK_ExplicitInstantiationDefinition:
6742 case TSK_ImplicitInstantiation:
6743 // We will be instantiating the key function.
6744 break;
6745 }
6746 } else if (!KeyFunction) {
6747 // If we have a class with no key function that is the subject
6748 // of an explicit instantiation declaration, suppress the
6749 // vtable; it will live with the explicit instantiation
6750 // definition.
6751 bool IsExplicitInstantiationDeclaration
6752 = Class->getTemplateSpecializationKind()
6753 == TSK_ExplicitInstantiationDeclaration;
6754 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6755 REnd = Class->redecls_end();
6756 R != REnd; ++R) {
6757 TemplateSpecializationKind TSK
6758 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6759 if (TSK == TSK_ExplicitInstantiationDeclaration)
6760 IsExplicitInstantiationDeclaration = true;
6761 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6762 IsExplicitInstantiationDeclaration = false;
6763 break;
6764 }
6765 }
6766
6767 if (IsExplicitInstantiationDeclaration)
6768 continue;
6769 }
6770
6771 // Mark all of the virtual members of this class as referenced, so
6772 // that we can build a vtable. Then, tell the AST consumer that a
6773 // vtable for this class is required.
6774 MarkVirtualMembersReferenced(Loc, Class);
6775 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6776 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6777
6778 // Optionally warn if we're emitting a weak vtable.
6779 if (Class->getLinkage() == ExternalLinkage &&
6780 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006781 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006782 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6783 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006784 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006785 VTableUses.clear();
6786
Anders Carlsson82fccd02009-12-07 08:24:59 +00006787 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006788}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006789
Rafael Espindola5b334082010-03-26 00:36:59 +00006790void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6791 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006792 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6793 e = RD->method_end(); i != e; ++i) {
6794 CXXMethodDecl *MD = *i;
6795
6796 // C++ [basic.def.odr]p2:
6797 // [...] A virtual member function is used if it is not pure. [...]
6798 if (MD->isVirtual() && !MD->isPure())
6799 MarkDeclarationReferenced(Loc, MD);
6800 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006801
6802 // Only classes that have virtual bases need a VTT.
6803 if (RD->getNumVBases() == 0)
6804 return;
6805
6806 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6807 e = RD->bases_end(); i != e; ++i) {
6808 const CXXRecordDecl *Base =
6809 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00006810 if (Base->getNumVBases() == 0)
6811 continue;
6812 MarkVirtualMembersReferenced(Loc, Base);
6813 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006814}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006815
6816/// SetIvarInitializers - This routine builds initialization ASTs for the
6817/// Objective-C implementation whose ivars need be initialized.
6818void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6819 if (!getLangOptions().CPlusPlus)
6820 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00006821 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006822 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6823 CollectIvarsToConstructOrDestruct(OID, ivars);
6824 if (ivars.empty())
6825 return;
6826 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6827 for (unsigned i = 0; i < ivars.size(); i++) {
6828 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00006829 if (Field->isInvalidDecl())
6830 continue;
6831
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006832 CXXBaseOrMemberInitializer *Member;
6833 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6834 InitializationKind InitKind =
6835 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6836
6837 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00006838 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00006839 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00006840 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006841 // Note, MemberInit could actually come back empty if no initialization
6842 // is required (e.g., because it would call a trivial default constructor)
6843 if (!MemberInit.get() || MemberInit.isInvalid())
6844 continue;
John McCallacf0ee52010-10-08 02:01:28 +00006845
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006846 Member =
6847 new (Context) CXXBaseOrMemberInitializer(Context,
6848 Field, SourceLocation(),
6849 SourceLocation(),
6850 MemberInit.takeAs<Expr>(),
6851 SourceLocation());
6852 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00006853
6854 // Be sure that the destructor is accessible and is marked as referenced.
6855 if (const RecordType *RecordTy
6856 = Context.getBaseElementType(Field->getType())
6857 ->getAs<RecordType>()) {
6858 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00006859 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00006860 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6861 CheckDestructorAccess(Field->getLocation(), Destructor,
6862 PDiag(diag::err_access_dtor_ivar)
6863 << Context.getBaseElementType(Field->getType()));
6864 }
6865 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006866 }
6867 ObjCImplementation->setIvarInitializers(Context,
6868 AllToInit.data(), AllToInit.size());
6869 }
6870}