blob: 49be40c5e400167f1f599764e1c9fee368174582 [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.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
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,
Nico Weber20c9f1d2010-11-28 22:53:37 +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);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(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
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregor752a5952011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000524 // C++ [class.derived]p2:
525 // If a class is marked with the class-virt-specifier final and it appears
526 // as a base-type-specifier in a base-clause (10 class.derived), the program
527 // is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000528 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000529 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
530 << CXXBaseDecl->getDeclName();
531 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
532 << CXXBaseDecl->getDeclName();
533 return 0;
534 }
535
John McCall3696dcb2010-08-17 07:23:57 +0000536 if (BaseDecl->isInvalidDecl())
537 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000538
539 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000540 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000541 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000542 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000543}
544
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
546/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000547/// example:
548/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000549/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000550BaseResult
John McCall48871652010-08-21 09:40:31 +0000551Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000552 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000553 ParsedType basetype, SourceLocation BaseLoc,
554 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000555 if (!classdecl)
556 return true;
557
Douglas Gregorc40290e2009-03-09 23:48:35 +0000558 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000559 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000560 if (!Class)
561 return true;
562
Nick Lewycky19b9f952010-07-26 16:56:01 +0000563 TypeSourceInfo *TInfo = 0;
564 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000565
Douglas Gregor752a5952011-01-03 22:36:02 +0000566 if (EllipsisLoc.isInvalid() &&
567 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000568 UPPC_BaseType))
569 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000570
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000572 Virtual, Access, TInfo,
573 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000574 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000577}
Douglas Gregor556877c2008-04-13 21:30:24 +0000578
Douglas Gregor463421d2009-03-03 04:44:36 +0000579/// \brief Performs the actual work of attaching the given base class
580/// specifiers to a C++ class.
581bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
582 unsigned NumBases) {
583 if (NumBases == 0)
584 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000585
586 // Used to keep track of which base types we have already seen, so
587 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000588 // that the key is always the unqualified canonical type of the base
589 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000590 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
591
592 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000593 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000594 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000595 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000598 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000599 if (!Class->hasObjectMember()) {
600 if (const RecordType *FDTTy =
601 NewBaseType.getTypePtr()->getAs<RecordType>())
602 if (FDTTy->getDecl()->hasObjectMember())
603 Class->setHasObjectMember(true);
604 }
605
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 if (KnownBaseTypes[NewBaseType]) {
607 // C++ [class.mi]p3:
608 // A class shall not be specified as a direct base class of a
609 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000611 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000613 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000617 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000618
619 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 } else {
621 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 KnownBaseTypes[NewBaseType] = Bases[idx];
623 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000624 }
625 }
626
627 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000628 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000629
630 // Delete the remaining (good) base class specifiers, since their
631 // data has been copied into the CXXRecordDecl.
632 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000634
635 return Invalid;
636}
637
638/// ActOnBaseSpecifiers - Attach the given base specifiers to the
639/// class, after checking whether there are any duplicate base
640/// classes.
John McCall48871652010-08-21 09:40:31 +0000641void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000642 unsigned NumBases) {
643 if (!ClassDecl || !Bases || !NumBases)
644 return;
645
646 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000647 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000649}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000650
John McCalle78aac42010-03-10 03:28:59 +0000651static CXXRecordDecl *GetClassForType(QualType T) {
652 if (const RecordType *RT = T->getAs<RecordType>())
653 return cast<CXXRecordDecl>(RT->getDecl());
654 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
655 return ICT->getDecl();
656 else
657 return 0;
658}
659
Douglas Gregor36d1b142009-10-06 17:59:45 +0000660/// \brief Determine whether the type \p Derived is a C++ class that is
661/// derived from the type \p Base.
662bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
663 if (!getLangOptions().CPlusPlus)
664 return false;
John McCalle78aac42010-03-10 03:28:59 +0000665
666 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
667 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCalle78aac42010-03-10 03:28:59 +0000670 CXXRecordDecl *BaseRD = GetClassForType(Base);
671 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672 return false;
673
John McCall67da35c2010-02-04 22:26:26 +0000674 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
675 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000676}
677
678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
John McCalle78aac42010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000690 return false;
691
Douglas Gregor36d1b142009-10-06 17:59:45 +0000692 return DerivedRD->isDerivedFrom(BaseRD, Paths);
693}
694
Anders Carlssona70cff62010-04-24 19:06:50 +0000695void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000696 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000697 assert(BasePathArray.empty() && "Base path array must be empty!");
698 assert(Paths.isRecordingPaths() && "Must record paths!");
699
700 const CXXBasePath &Path = Paths.front();
701
702 // We first go backward and check if we have a virtual base.
703 // FIXME: It would be better if CXXBasePath had the base specifier for
704 // the nearest virtual base.
705 unsigned Start = 0;
706 for (unsigned I = Path.size(); I != 0; --I) {
707 if (Path[I - 1].Base->isVirtual()) {
708 Start = I - 1;
709 break;
710 }
711 }
712
713 // Now add all bases.
714 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000715 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000716}
717
Douglas Gregor88d292c2010-05-13 16:44:06 +0000718/// \brief Determine whether the given base path includes a virtual
719/// base class.
John McCallcf142162010-08-07 06:22:56 +0000720bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
721 for (CXXCastPath::const_iterator B = BasePath.begin(),
722 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000723 B != BEnd; ++B)
724 if ((*B)->isVirtual())
725 return true;
726
727 return false;
728}
729
Douglas Gregor36d1b142009-10-06 17:59:45 +0000730/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
731/// conversion (where Derived and Base are class types) is
732/// well-formed, meaning that the conversion is unambiguous (and
733/// that all of the base classes are accessible). Returns true
734/// and emits a diagnostic if the code is ill-formed, returns false
735/// otherwise. Loc is the location where this routine should point to
736/// if there is an error, and Range is the source range to highlight
737/// if there is an error.
738bool
739Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000740 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 unsigned AmbigiousBaseConvID,
742 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000743 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000744 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000745 // First, determine whether the path from Derived to Base is
746 // ambiguous. This is slightly more expensive than checking whether
747 // the Derived to Base conversion exists, because here we need to
748 // explore multiple paths to determine if there is an ambiguity.
749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
750 /*DetectVirtual=*/false);
751 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
752 assert(DerivationOkay &&
753 "Can only be used with a derived-to-base conversion");
754 (void)DerivationOkay;
755
756 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000757 if (InaccessibleBaseID) {
758 // Check that the base class can be accessed.
759 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
760 InaccessibleBaseID)) {
761 case AR_inaccessible:
762 return true;
763 case AR_accessible:
764 case AR_dependent:
765 case AR_delayed:
766 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000767 }
John McCall5b0829a2010-02-10 09:31:12 +0000768 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000769
770 // Build a base path if necessary.
771 if (BasePath)
772 BuildBasePathArray(Paths, *BasePath);
773 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000774 }
775
776 // We know that the derived-to-base conversion is ambiguous, and
777 // we're going to produce a diagnostic. Perform the derived-to-base
778 // search just one more time to compute all of the possible paths so
779 // that we can print them out. This is more expensive than any of
780 // the previous derived-to-base checks we've done, but at this point
781 // performance isn't as much of an issue.
782 Paths.clear();
783 Paths.setRecordingPaths(true);
784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
785 assert(StillOkay && "Can only be used with a derived-to-base conversion");
786 (void)StillOkay;
787
788 // Build up a textual representation of the ambiguous paths, e.g.,
789 // D -> B -> A, that will be used to illustrate the ambiguous
790 // conversions in the diagnostic. We only print one of the paths
791 // to each base class subobject.
792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
793
794 Diag(Loc, AmbigiousBaseConvID)
795 << Derived << Base << PathDisplayStr << Range << Name;
796 return true;
797}
798
799bool
800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000801 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000802 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000803 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000804 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000805 IgnoreAccess ? 0
806 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000807 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000808 Loc, Range, DeclarationName(),
809 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000810}
811
812
813/// @brief Builds a string representing ambiguous paths from a
814/// specific derived class to different subobjects of the same base
815/// class.
816///
817/// This function builds a string that can be used in error messages
818/// to show the different paths that one can take through the
819/// inheritance hierarchy to go from the derived class to different
820/// subobjects of a base class. The result looks something like this:
821/// @code
822/// struct D -> struct B -> struct A
823/// struct D -> struct C -> struct A
824/// @endcode
825std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
826 std::string PathDisplayStr;
827 std::set<unsigned> DisplayedPaths;
828 for (CXXBasePaths::paths_iterator Path = Paths.begin();
829 Path != Paths.end(); ++Path) {
830 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
831 // We haven't displayed a path to this particular base
832 // class subobject yet.
833 PathDisplayStr += "\n ";
834 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
835 for (CXXBasePath::const_iterator Element = Path->begin();
836 Element != Path->end(); ++Element)
837 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
838 }
839 }
840
841 return PathDisplayStr;
842}
843
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000844//===----------------------------------------------------------------------===//
845// C++ class member Handling
846//===----------------------------------------------------------------------===//
847
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000849Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
850 SourceLocation ASLoc,
851 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000852 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000853 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000854 ASLoc, ColonLoc);
855 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000856 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000857}
858
Anders Carlssonfd835532011-01-20 05:57:14 +0000859/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000860void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000861 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
862 if (!MD || !MD->isVirtual())
863 return;
864
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000865 if (MD->isDependentContext())
866 return;
867
Anders Carlssonfd835532011-01-20 05:57:14 +0000868 // C++0x [class.virtual]p3:
869 // If a virtual function is marked with the virt-specifier override and does
870 // not override a member function of a base class,
871 // the program is ill-formed.
872 bool HasOverriddenMethods =
873 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +0000874 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000875 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000876 diag::err_function_marked_override_not_overriding)
877 << MD->getDeclName();
878 return;
879 }
Anders Carlsson7d59a682011-01-22 22:23:37 +0000880
881 // C++0x [class.derived]p8:
882 // In a class definition marked with the class-virt-specifier explicit,
883 // if a virtual member function that is neither implicitly-declared nor a
884 // destructor overrides a member function of a base class and it is not
885 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000886 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
887 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlsson7d59a682011-01-22 22:23:37 +0000888 llvm::SmallVector<const CXXMethodDecl*, 4>
889 OverriddenMethods(MD->begin_overridden_methods(),
890 MD->end_overridden_methods());
891
892 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
893 << MD->getDeclName()
894 << (unsigned)OverriddenMethods.size();
895
896 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
897 Diag(OverriddenMethods[I]->getLocation(),
898 diag::note_overridden_virtual_function);
899 }
Anders Carlssonfd835532011-01-20 05:57:14 +0000900}
901
Anders Carlsson3f610c72011-01-20 16:25:36 +0000902/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
903/// function overrides a virtual member function marked 'final', according to
904/// C++0x [class.virtual]p3.
905bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
906 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +0000907 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +0000908 return false;
909
910 Diag(New->getLocation(), diag::err_final_function_overridden)
911 << New->getDeclName();
912 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
913 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +0000914}
915
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000916/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
917/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
918/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000919/// any.
John McCall48871652010-08-21 09:40:31 +0000920Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000921Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000922 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000923 ExprTy *BW, const VirtSpecifiers &VS,
924 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000925 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000926 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000927 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
928 DeclarationName Name = NameInfo.getName();
929 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000930
931 // For anonymous bitfields, the location should point to the type.
932 if (Loc.isInvalid())
933 Loc = D.getSourceRange().getBegin();
934
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935 Expr *BitWidth = static_cast<Expr*>(BW);
936 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937
John McCallb1cd7da2010-06-04 08:34:12 +0000938 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000939 assert(!DS.isFriendSpecified());
940
John McCallb1cd7da2010-06-04 08:34:12 +0000941 bool isFunc = false;
942 if (D.isFunctionDeclarator())
943 isFunc = true;
944 else if (D.getNumTypeObjects() == 0 &&
945 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000946 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000947 isFunc = TDType->isFunctionType();
948 }
949
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000950 // C++ 9.2p6: A member shall not be declared to have automatic storage
951 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000952 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
953 // data members and cannot be applied to names declared const or static,
954 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000955 switch (DS.getStorageClassSpec()) {
956 case DeclSpec::SCS_unspecified:
957 case DeclSpec::SCS_typedef:
958 case DeclSpec::SCS_static:
959 // FALL THROUGH.
960 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000961 case DeclSpec::SCS_mutable:
962 if (isFunc) {
963 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000964 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000965 else
Chris Lattner3b054132008-11-19 05:08:23 +0000966 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Sebastian Redl8071edb2008-11-17 23:24:37 +0000968 // FIXME: It would be nicer if the keyword was ignored only for this
969 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000970 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000971 }
972 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000973 default:
974 if (DS.getStorageClassSpecLoc().isValid())
975 Diag(DS.getStorageClassSpecLoc(),
976 diag::err_storageclass_invalid_for_member);
977 else
978 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
979 D.getMutableDeclSpec().ClearStorageClassSpecs();
980 }
981
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000982 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
983 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000984 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000985
986 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000987 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000988 CXXScopeSpec &SS = D.getCXXScopeSpec();
989
990
991 if (SS.isSet() && !SS.isInvalid()) {
992 // The user provided a superfluous scope specifier inside a class
993 // definition:
994 //
995 // class X {
996 // int X::member;
997 // };
998 DeclContext *DC = 0;
999 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1000 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1001 << Name << FixItHint::CreateRemoval(SS.getRange());
1002 else
1003 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1004 << Name << SS.getRange();
1005
1006 SS.clear();
1007 }
1008
Douglas Gregor3447e762009-08-20 22:52:58 +00001009 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001010 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001011 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1012 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001013 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001014 } else {
John McCall48871652010-08-21 09:40:31 +00001015 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001016 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001017 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001018 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001019
1020 // Non-instance-fields can't have a bitfield.
1021 if (BitWidth) {
1022 if (Member->isInvalidDecl()) {
1023 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001024 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001025 // C++ 9.6p3: A bit-field shall not be a static member.
1026 // "static member 'A' cannot be a bit-field"
1027 Diag(Loc, diag::err_static_not_bitfield)
1028 << Name << BitWidth->getSourceRange();
1029 } else if (isa<TypedefDecl>(Member)) {
1030 // "typedef member 'x' cannot be a bit-field"
1031 Diag(Loc, diag::err_typedef_not_bitfield)
1032 << Name << BitWidth->getSourceRange();
1033 } else {
1034 // A function typedef ("typedef int f(); f a;").
1035 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1036 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001037 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001038 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerd26760a2009-03-05 23:01:03 +00001041 BitWidth = 0;
1042 Member->setInvalidDecl();
1043 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001044
1045 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregor3447e762009-08-20 22:52:58 +00001047 // If we have declared a member function template, set the access of the
1048 // templated declaration as well.
1049 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1050 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001051 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001052
Anders Carlsson13a69102011-01-20 04:34:22 +00001053 if (VS.isOverrideSpecified()) {
1054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1055 if (!MD || !MD->isVirtual()) {
1056 Diag(Member->getLocStart(),
1057 diag::override_keyword_only_allowed_on_virtual_member_functions)
1058 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001059 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001060 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001061 }
1062 if (VS.isFinalSpecified()) {
1063 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1064 if (!MD || !MD->isVirtual()) {
1065 Diag(Member->getLocStart(),
1066 diag::override_keyword_only_allowed_on_virtual_member_functions)
1067 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001068 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001069 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001070 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001071
Anders Carlssonc87f8612011-01-20 06:29:02 +00001072 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001073
Douglas Gregor92751d42008-11-17 22:58:34 +00001074 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001075
Douglas Gregor0c880302009-03-11 23:00:04 +00001076 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001077 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001078 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001079 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001080
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001081 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001082 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001083 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001084 }
John McCall48871652010-08-21 09:40:31 +00001085 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001086}
1087
Douglas Gregor15e77a22009-12-31 09:10:24 +00001088/// \brief Find the direct and/or virtual base specifiers that
1089/// correspond to the given base type, for use in base initialization
1090/// within a constructor.
1091static bool FindBaseInitializer(Sema &SemaRef,
1092 CXXRecordDecl *ClassDecl,
1093 QualType BaseType,
1094 const CXXBaseSpecifier *&DirectBaseSpec,
1095 const CXXBaseSpecifier *&VirtualBaseSpec) {
1096 // First, check for a direct base class.
1097 DirectBaseSpec = 0;
1098 for (CXXRecordDecl::base_class_const_iterator Base
1099 = ClassDecl->bases_begin();
1100 Base != ClassDecl->bases_end(); ++Base) {
1101 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1102 // We found a direct base of this type. That's what we're
1103 // initializing.
1104 DirectBaseSpec = &*Base;
1105 break;
1106 }
1107 }
1108
1109 // Check for a virtual base class.
1110 // FIXME: We might be able to short-circuit this if we know in advance that
1111 // there are no virtual bases.
1112 VirtualBaseSpec = 0;
1113 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1114 // We haven't found a base yet; search the class hierarchy for a
1115 // virtual base class.
1116 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1117 /*DetectVirtual=*/false);
1118 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1119 BaseType, Paths)) {
1120 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1121 Path != Paths.end(); ++Path) {
1122 if (Path->back().Base->isVirtual()) {
1123 VirtualBaseSpec = Path->back().Base;
1124 break;
1125 }
1126 }
1127 }
1128 }
1129
1130 return DirectBaseSpec || VirtualBaseSpec;
1131}
1132
Douglas Gregore8381c02008-11-05 04:29:56 +00001133/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001134MemInitResult
John McCall48871652010-08-21 09:40:31 +00001135Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001136 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001137 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001138 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001139 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001140 SourceLocation IdLoc,
1141 SourceLocation LParenLoc,
1142 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001143 SourceLocation RParenLoc,
1144 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001145 if (!ConstructorD)
1146 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001147
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001148 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001149
1150 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001151 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001152 if (!Constructor) {
1153 // The user wrote a constructor initializer on a function that is
1154 // not a C++ constructor. Ignore the error for now, because we may
1155 // have more member initializers coming; we'll diagnose it just
1156 // once in ActOnMemInitializers.
1157 return true;
1158 }
1159
1160 CXXRecordDecl *ClassDecl = Constructor->getParent();
1161
1162 // C++ [class.base.init]p2:
1163 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001164 // constructor's class and, if not found in that scope, are looked
1165 // up in the scope containing the constructor's definition.
1166 // [Note: if the constructor's class contains a member with the
1167 // same name as a direct or virtual base class of the class, a
1168 // mem-initializer-id naming the member or base class and composed
1169 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001170 // mem-initializer-id for the hidden base class may be specified
1171 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001172 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001173 // Look for a member, first.
1174 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001175 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001176 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001177 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001178 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001179
Douglas Gregor44e7df62011-01-04 00:32:56 +00001180 if (Member) {
1181 if (EllipsisLoc.isValid())
1182 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1183 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1184
Francois Pichetd583da02010-12-04 09:14:42 +00001185 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001186 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001187 }
1188
Francois Pichetd583da02010-12-04 09:14:42 +00001189 // Handle anonymous union case.
1190 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001191 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1192 if (EllipsisLoc.isValid())
1193 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1194 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1195
Francois Pichetd583da02010-12-04 09:14:42 +00001196 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1197 NumArgs, IdLoc,
1198 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001199 }
Francois Pichetd583da02010-12-04 09:14:42 +00001200 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001201 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001202 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001203 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001204 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001205
1206 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001207 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001208 } else {
1209 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1210 LookupParsedName(R, S, &SS);
1211
1212 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1213 if (!TyD) {
1214 if (R.isAmbiguous()) return true;
1215
John McCallda6841b2010-04-09 19:01:14 +00001216 // We don't want access-control diagnostics here.
1217 R.suppressDiagnostics();
1218
Douglas Gregora3b624a2010-01-19 06:46:48 +00001219 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1220 bool NotUnknownSpecialization = false;
1221 DeclContext *DC = computeDeclContext(SS, false);
1222 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1223 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1224
1225 if (!NotUnknownSpecialization) {
1226 // When the scope specifier can refer to a member of an unknown
1227 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001228 BaseType = CheckTypenameType(ETK_None,
1229 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001230 *MemberOrBase, SourceLocation(),
1231 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001232 if (BaseType.isNull())
1233 return true;
1234
Douglas Gregora3b624a2010-01-19 06:46:48 +00001235 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001236 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001237 }
1238 }
1239
Douglas Gregor15e77a22009-12-31 09:10:24 +00001240 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001241 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001242 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1243 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001244 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001245 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001246 // We have found a non-static data member with a similar
1247 // name to what was typed; complain and initialize that
1248 // member.
1249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1250 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001251 << FixItHint::CreateReplacement(R.getNameLoc(),
1252 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001253 Diag(Member->getLocation(), diag::note_previous_decl)
1254 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001255
1256 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1257 LParenLoc, RParenLoc);
1258 }
1259 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1260 const CXXBaseSpecifier *DirectBaseSpec;
1261 const CXXBaseSpecifier *VirtualBaseSpec;
1262 if (FindBaseInitializer(*this, ClassDecl,
1263 Context.getTypeDeclType(Type),
1264 DirectBaseSpec, VirtualBaseSpec)) {
1265 // We have found a direct or virtual base class with a
1266 // similar name to what was typed; complain and initialize
1267 // that base class.
1268 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1269 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001270 << FixItHint::CreateReplacement(R.getNameLoc(),
1271 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001272
1273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1274 : VirtualBaseSpec;
1275 Diag(BaseSpec->getSourceRange().getBegin(),
1276 diag::note_base_class_specified_here)
1277 << BaseSpec->getType()
1278 << BaseSpec->getSourceRange();
1279
Douglas Gregor15e77a22009-12-31 09:10:24 +00001280 TyD = Type;
1281 }
1282 }
1283 }
1284
Douglas Gregora3b624a2010-01-19 06:46:48 +00001285 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001286 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1287 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1288 return true;
1289 }
John McCallb5a0d312009-12-21 10:41:20 +00001290 }
1291
Douglas Gregora3b624a2010-01-19 06:46:48 +00001292 if (BaseType.isNull()) {
1293 BaseType = Context.getTypeDeclType(TyD);
1294 if (SS.isSet()) {
1295 NestedNameSpecifier *Qualifier =
1296 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001297
Douglas Gregora3b624a2010-01-19 06:46:48 +00001298 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001299 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001300 }
John McCallb5a0d312009-12-21 10:41:20 +00001301 }
1302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
John McCallbcd03502009-12-07 02:54:59 +00001304 if (!TInfo)
1305 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001306
John McCallbcd03502009-12-07 02:54:59 +00001307 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001308 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001309}
1310
John McCalle22a04a2009-11-04 23:02:40 +00001311/// Checks an initializer expression for use of uninitialized fields, such as
1312/// containing the field that is being initialized. Returns true if there is an
1313/// uninitialized field was used an updates the SourceLocation parameter; false
1314/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001315static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001316 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001317 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001318 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1319
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001320 if (isa<CallExpr>(S)) {
1321 // Do not descend into function calls or constructors, as the use
1322 // of an uninitialized field may be valid. One would have to inspect
1323 // the contents of the function/ctor to determine if it is safe or not.
1324 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1325 // may be safe, depending on what the function/ctor does.
1326 return false;
1327 }
1328 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1329 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001330
1331 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1332 // The member expression points to a static data member.
1333 assert(VD->isStaticDataMember() &&
1334 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001335 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001336 return false;
1337 }
1338
1339 if (isa<EnumConstantDecl>(RhsField)) {
1340 // The member expression points to an enum.
1341 return false;
1342 }
1343
John McCalle22a04a2009-11-04 23:02:40 +00001344 if (RhsField == LhsField) {
1345 // Initializing a field with itself. Throw a warning.
1346 // But wait; there are exceptions!
1347 // Exception #1: The field may not belong to this record.
1348 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001349 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001350 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1351 // Even though the field matches, it does not belong to this record.
1352 return false;
1353 }
1354 // None of the exceptions triggered; return true to indicate an
1355 // uninitialized field was used.
1356 *L = ME->getMemberLoc();
1357 return true;
1358 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001359 } else if (isa<SizeOfAlignOfExpr>(S)) {
1360 // sizeof/alignof doesn't reference contents, do not warn.
1361 return false;
1362 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1363 // address-of doesn't reference contents (the pointer may be dereferenced
1364 // in the same expression but it would be rare; and weird).
1365 if (UOE->getOpcode() == UO_AddrOf)
1366 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001367 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001368 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1369 it != e; ++it) {
1370 if (!*it) {
1371 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001372 continue;
1373 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001374 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1375 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001376 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001377 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001378}
1379
John McCallfaf5fb42010-08-26 23:41:50 +00001380MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001381Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001382 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001383 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001384 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001385 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1386 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1387 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001388 "Member must be a FieldDecl or IndirectFieldDecl");
1389
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001390 if (Member->isInvalidDecl())
1391 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001392
John McCalle22a04a2009-11-04 23:02:40 +00001393 // Diagnose value-uses of fields to initialize themselves, e.g.
1394 // foo(foo)
1395 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001396 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001397 for (unsigned i = 0; i < NumArgs; ++i) {
1398 SourceLocation L;
1399 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1400 // FIXME: Return true in the case when other fields are used before being
1401 // uninitialized. For example, let this field be the i'th field. When
1402 // initializing the i'th field, throw a warning if any of the >= i'th
1403 // fields are used, as they are not yet initialized.
1404 // Right now we are only handling the case where the i'th field uses
1405 // itself in its initializer.
1406 Diag(L, diag::warn_field_is_uninit);
1407 }
1408 }
1409
Eli Friedman8e1433b2009-07-29 19:44:27 +00001410 bool HasDependentArg = false;
1411 for (unsigned i = 0; i < NumArgs; i++)
1412 HasDependentArg |= Args[i]->isTypeDependent();
1413
Chandler Carruthd44c3102010-12-06 09:23:57 +00001414 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001415 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001416 // Can't check initialization for a member of dependent type or when
1417 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001418 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1419 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001420
1421 // Erase any temporaries within this evaluation context; we're not
1422 // going to track them in the AST, since we'll be rebuilding the
1423 // ASTs during template instantiation.
1424 ExprTemporaries.erase(
1425 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1426 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001427 } else {
1428 // Initialize the member.
1429 InitializedEntity MemberEntity =
1430 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1431 : InitializedEntity::InitializeMember(IndirectMember, 0);
1432 InitializationKind Kind =
1433 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001434
Chandler Carruthd44c3102010-12-06 09:23:57 +00001435 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1436
1437 ExprResult MemberInit =
1438 InitSeq.Perform(*this, MemberEntity, Kind,
1439 MultiExprArg(*this, Args, NumArgs), 0);
1440 if (MemberInit.isInvalid())
1441 return true;
1442
1443 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1444
1445 // C++0x [class.base.init]p7:
1446 // The initialization of each base and member constitutes a
1447 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001448 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001449 if (MemberInit.isInvalid())
1450 return true;
1451
1452 // If we are in a dependent context, template instantiation will
1453 // perform this type-checking again. Just save the arguments that we
1454 // received in a ParenListExpr.
1455 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1456 // of the information that we have about the member
1457 // initializer. However, deconstructing the ASTs is a dicey process,
1458 // and this approach is far more likely to get the corner cases right.
1459 if (CurContext->isDependentContext())
1460 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1461 RParenLoc);
1462 else
1463 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001464 }
1465
Chandler Carruthd44c3102010-12-06 09:23:57 +00001466 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001467 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001468 IdLoc, LParenLoc, Init,
1469 RParenLoc);
1470 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001471 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001472 IdLoc, LParenLoc, Init,
1473 RParenLoc);
1474 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001475}
1476
John McCallfaf5fb42010-08-26 23:41:50 +00001477MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001478Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1479 Expr **Args, unsigned NumArgs,
1480 SourceLocation LParenLoc,
1481 SourceLocation RParenLoc,
1482 CXXRecordDecl *ClassDecl,
1483 SourceLocation EllipsisLoc) {
1484 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1485 if (!LangOpts.CPlusPlus0x)
1486 return Diag(Loc, diag::err_delegation_0x_only)
1487 << TInfo->getTypeLoc().getLocalSourceRange();
1488
1489 return Diag(Loc, diag::err_delegation_unimplemented)
1490 << TInfo->getTypeLoc().getLocalSourceRange();
1491}
1492
1493MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001494Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001495 Expr **Args, unsigned NumArgs,
1496 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001497 CXXRecordDecl *ClassDecl,
1498 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001499 bool HasDependentArg = false;
1500 for (unsigned i = 0; i < NumArgs; i++)
1501 HasDependentArg |= Args[i]->isTypeDependent();
1502
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001503 SourceLocation BaseLoc
1504 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1505
1506 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1507 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1508 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1509
1510 // C++ [class.base.init]p2:
1511 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001512 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001513 // of that class, the mem-initializer is ill-formed. A
1514 // mem-initializer-list can initialize a base class using any
1515 // name that denotes that base class type.
1516 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1517
Douglas Gregor44e7df62011-01-04 00:32:56 +00001518 if (EllipsisLoc.isValid()) {
1519 // This is a pack expansion.
1520 if (!BaseType->containsUnexpandedParameterPack()) {
1521 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1522 << SourceRange(BaseLoc, RParenLoc);
1523
1524 EllipsisLoc = SourceLocation();
1525 }
1526 } else {
1527 // Check for any unexpanded parameter packs.
1528 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1529 return true;
1530
1531 for (unsigned I = 0; I != NumArgs; ++I)
1532 if (DiagnoseUnexpandedParameterPack(Args[I]))
1533 return true;
1534 }
1535
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001536 // Check for direct and virtual base classes.
1537 const CXXBaseSpecifier *DirectBaseSpec = 0;
1538 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1539 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001540 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1541 BaseType))
1542 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1543 LParenLoc, RParenLoc, ClassDecl,
1544 EllipsisLoc);
1545
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001546 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1547 VirtualBaseSpec);
1548
1549 // C++ [base.class.init]p2:
1550 // Unless the mem-initializer-id names a nonstatic data member of the
1551 // constructor's class or a direct or virtual base of that class, the
1552 // mem-initializer is ill-formed.
1553 if (!DirectBaseSpec && !VirtualBaseSpec) {
1554 // If the class has any dependent bases, then it's possible that
1555 // one of those types will resolve to the same type as
1556 // BaseType. Therefore, just treat this as a dependent base
1557 // class initialization. FIXME: Should we try to check the
1558 // initialization anyway? It seems odd.
1559 if (ClassDecl->hasAnyDependentBases())
1560 Dependent = true;
1561 else
1562 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1563 << BaseType << Context.getTypeDeclType(ClassDecl)
1564 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1565 }
1566 }
1567
1568 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001569 // Can't check initialization for a base of dependent type or when
1570 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001571 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001572 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1573 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001574
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001575 // Erase any temporaries within this evaluation context; we're not
1576 // going to track them in the AST, since we'll be rebuilding the
1577 // ASTs during template instantiation.
1578 ExprTemporaries.erase(
1579 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1580 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001581
Alexis Hunt1d792652011-01-08 20:30:50 +00001582 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001583 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001584 LParenLoc,
1585 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001586 RParenLoc,
1587 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001588 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001589
1590 // C++ [base.class.init]p2:
1591 // If a mem-initializer-id is ambiguous because it designates both
1592 // a direct non-virtual base class and an inherited virtual base
1593 // class, the mem-initializer is ill-formed.
1594 if (DirectBaseSpec && VirtualBaseSpec)
1595 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001596 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001597
1598 CXXBaseSpecifier *BaseSpec
1599 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1600 if (!BaseSpec)
1601 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1602
1603 // Initialize the base.
1604 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001605 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001606 InitializationKind Kind =
1607 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1608
1609 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1610
John McCalldadc5752010-08-24 06:29:42 +00001611 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001612 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001613 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001614 if (BaseInit.isInvalid())
1615 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001616
1617 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001618
1619 // C++0x [class.base.init]p7:
1620 // The initialization of each base and member constitutes a
1621 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001622 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001623 if (BaseInit.isInvalid())
1624 return true;
1625
1626 // If we are in a dependent context, template instantiation will
1627 // perform this type-checking again. Just save the arguments that we
1628 // received in a ParenListExpr.
1629 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1630 // of the information that we have about the base
1631 // initializer. However, deconstructing the ASTs is a dicey process,
1632 // and this approach is far more likely to get the corner cases right.
1633 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001634 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001635 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1636 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001638 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001639 LParenLoc,
1640 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001641 RParenLoc,
1642 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001643 }
1644
Alexis Hunt1d792652011-01-08 20:30:50 +00001645 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001646 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001647 LParenLoc,
1648 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001649 RParenLoc,
1650 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001651}
1652
Anders Carlsson1b00e242010-04-23 03:10:23 +00001653/// ImplicitInitializerKind - How an implicit base or member initializer should
1654/// initialize its base or member.
1655enum ImplicitInitializerKind {
1656 IIK_Default,
1657 IIK_Copy,
1658 IIK_Move
1659};
1660
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001661static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001662BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001663 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001664 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001665 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001666 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001667 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001668 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1669 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001670
John McCalldadc5752010-08-24 06:29:42 +00001671 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001672
1673 switch (ImplicitInitKind) {
1674 case IIK_Default: {
1675 InitializationKind InitKind
1676 = InitializationKind::CreateDefault(Constructor->getLocation());
1677 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1678 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001679 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001680 break;
1681 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001682
Anders Carlsson1b00e242010-04-23 03:10:23 +00001683 case IIK_Copy: {
1684 ParmVarDecl *Param = Constructor->getParamDecl(0);
1685 QualType ParamType = Param->getType().getNonReferenceType();
1686
1687 Expr *CopyCtorArg =
1688 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001689 Constructor->getLocation(), ParamType,
1690 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001691
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001692 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001693 QualType ArgTy =
1694 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1695 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001696
1697 CXXCastPath BasePath;
1698 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001699 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001700 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001701 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001702
Anders Carlsson1b00e242010-04-23 03:10:23 +00001703 InitializationKind InitKind
1704 = InitializationKind::CreateDirect(Constructor->getLocation(),
1705 SourceLocation(), SourceLocation());
1706 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1707 &CopyCtorArg, 1);
1708 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001709 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001710 break;
1711 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001712
Anders Carlsson1b00e242010-04-23 03:10:23 +00001713 case IIK_Move:
1714 assert(false && "Unhandled initializer kind!");
1715 }
John McCallb268a282010-08-23 23:25:46 +00001716
Douglas Gregora40433a2010-12-07 00:41:46 +00001717 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001718 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001719 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001720
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001721 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001722 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001723 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1724 SourceLocation()),
1725 BaseSpec->isVirtual(),
1726 SourceLocation(),
1727 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001728 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001729 SourceLocation());
1730
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001731 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001732}
1733
Anders Carlsson3c1db572010-04-23 02:15:47 +00001734static bool
1735BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001736 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001737 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001738 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001739 if (Field->isInvalidDecl())
1740 return true;
1741
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001742 SourceLocation Loc = Constructor->getLocation();
1743
Anders Carlsson423f5d82010-04-23 16:04:08 +00001744 if (ImplicitInitKind == IIK_Copy) {
1745 ParmVarDecl *Param = Constructor->getParamDecl(0);
1746 QualType ParamType = Param->getType().getNonReferenceType();
1747
1748 Expr *MemberExprBase =
1749 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001750 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001751
1752 // Build a reference to this field within the parameter.
1753 CXXScopeSpec SS;
1754 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1755 Sema::LookupMemberName);
1756 MemberLookup.addDecl(Field, AS_public);
1757 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001758 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001760 ParamType, Loc,
1761 /*IsArrow=*/false,
1762 SS,
1763 /*FirstQualifierInScope=*/0,
1764 MemberLookup,
1765 /*TemplateArgs=*/0);
1766 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001767 return true;
1768
Douglas Gregor94f9a482010-05-05 05:51:00 +00001769 // When the field we are copying is an array, create index variables for
1770 // each dimension of the array. We use these index variables to subscript
1771 // the source array, and other clients (e.g., CodeGen) will perform the
1772 // necessary iteration with these index variables.
1773 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1774 QualType BaseType = Field->getType();
1775 QualType SizeType = SemaRef.Context.getSizeType();
1776 while (const ConstantArrayType *Array
1777 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1778 // Create the iteration variable for this array index.
1779 IdentifierInfo *IterationVarName = 0;
1780 {
1781 llvm::SmallString<8> Str;
1782 llvm::raw_svector_ostream OS(Str);
1783 OS << "__i" << IndexVariables.size();
1784 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1785 }
1786 VarDecl *IterationVar
1787 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1788 IterationVarName, SizeType,
1789 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001790 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001791 IndexVariables.push_back(IterationVar);
1792
1793 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001794 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001795 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001796 assert(!IterationVarRef.isInvalid() &&
1797 "Reference to invented variable cannot fail!");
1798
1799 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001800 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001801 Loc,
John McCallb268a282010-08-23 23:25:46 +00001802 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001803 Loc);
1804 if (CopyCtorArg.isInvalid())
1805 return true;
1806
1807 BaseType = Array->getElementType();
1808 }
1809
1810 // Construct the entity that we will be initializing. For an array, this
1811 // will be first element in the array, which may require several levels
1812 // of array-subscript entities.
1813 llvm::SmallVector<InitializedEntity, 4> Entities;
1814 Entities.reserve(1 + IndexVariables.size());
1815 Entities.push_back(InitializedEntity::InitializeMember(Field));
1816 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1817 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1818 0,
1819 Entities.back()));
1820
1821 // Direct-initialize to use the copy constructor.
1822 InitializationKind InitKind =
1823 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1824
1825 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1826 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1827 &CopyCtorArgE, 1);
1828
John McCalldadc5752010-08-24 06:29:42 +00001829 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001830 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001831 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001832 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001833 if (MemberInit.isInvalid())
1834 return true;
1835
1836 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001837 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001838 MemberInit.takeAs<Expr>(), Loc,
1839 IndexVariables.data(),
1840 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001841 return false;
1842 }
1843
Anders Carlsson423f5d82010-04-23 16:04:08 +00001844 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1845
Anders Carlsson3c1db572010-04-23 02:15:47 +00001846 QualType FieldBaseElementType =
1847 SemaRef.Context.getBaseElementType(Field->getType());
1848
Anders Carlsson3c1db572010-04-23 02:15:47 +00001849 if (FieldBaseElementType->isRecordType()) {
1850 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001851 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001852 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001853
1854 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001855 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001856 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001857
Douglas Gregora40433a2010-12-07 00:41:46 +00001858 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001859 if (MemberInit.isInvalid())
1860 return true;
1861
1862 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001863 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001864 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001865 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001866 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001867 return false;
1868 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001869
1870 if (FieldBaseElementType->isReferenceType()) {
1871 SemaRef.Diag(Constructor->getLocation(),
1872 diag::err_uninitialized_member_in_ctor)
1873 << (int)Constructor->isImplicit()
1874 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1875 << 0 << Field->getDeclName();
1876 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1877 return true;
1878 }
1879
1880 if (FieldBaseElementType.isConstQualified()) {
1881 SemaRef.Diag(Constructor->getLocation(),
1882 diag::err_uninitialized_member_in_ctor)
1883 << (int)Constructor->isImplicit()
1884 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1885 << 1 << Field->getDeclName();
1886 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1887 return true;
1888 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001889
1890 // Nothing to initialize.
1891 CXXMemberInit = 0;
1892 return false;
1893}
John McCallbc83b3f2010-05-20 23:23:51 +00001894
1895namespace {
1896struct BaseAndFieldInfo {
1897 Sema &S;
1898 CXXConstructorDecl *Ctor;
1899 bool AnyErrorsInInits;
1900 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001901 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1902 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001903
1904 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1905 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1906 // FIXME: Handle implicit move constructors.
1907 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1908 IIK = IIK_Copy;
1909 else
1910 IIK = IIK_Default;
1911 }
1912};
1913}
1914
1915static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1916 FieldDecl *Top, FieldDecl *Field) {
1917
Chandler Carruth139e9622010-06-30 02:59:29 +00001918 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001919 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001920 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001921 return false;
1922 }
1923
1924 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1925 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1926 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001927 CXXRecordDecl *FieldClassDecl
1928 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001929
1930 // Even though union members never have non-trivial default
1931 // constructions in C++03, we still build member initializers for aggregate
1932 // record types which can be union members, and C++0x allows non-trivial
1933 // default constructors for union members, so we ensure that only one
1934 // member is initialized for these.
1935 if (FieldClassDecl->isUnion()) {
1936 // First check for an explicit initializer for one field.
1937 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1938 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001939 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001940 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001941
1942 // Once we've initialized a field of an anonymous union, the union
1943 // field in the class is also initialized, so exit immediately.
1944 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001945 } else if ((*FA)->isAnonymousStructOrUnion()) {
1946 if (CollectFieldInitializer(Info, Top, *FA))
1947 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001948 }
1949 }
1950
1951 // Fallthrough and construct a default initializer for the union as
1952 // a whole, which can call its default constructor if such a thing exists
1953 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1954 // behavior going forward with C++0x, when anonymous unions there are
1955 // finalized, we should revisit this.
1956 } else {
1957 // For structs, we simply descend through to initialize all members where
1958 // necessary.
1959 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1960 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1961 if (CollectFieldInitializer(Info, Top, *FA))
1962 return true;
1963 }
1964 }
John McCallbc83b3f2010-05-20 23:23:51 +00001965 }
1966
1967 // Don't try to build an implicit initializer if there were semantic
1968 // errors in any of the initializers (and therefore we might be
1969 // missing some that the user actually wrote).
1970 if (Info.AnyErrorsInInits)
1971 return false;
1972
Alexis Hunt1d792652011-01-08 20:30:50 +00001973 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001974 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1975 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001976
Francois Pichetd583da02010-12-04 09:14:42 +00001977 if (Init)
1978 Info.AllToInit.push_back(Init);
1979
John McCallbc83b3f2010-05-20 23:23:51 +00001980 return false;
1981}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001982
Eli Friedman9cf6b592009-11-09 19:20:36 +00001983bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001984Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1985 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001986 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001987 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001988 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001989 // Just store the initializers as written, they will be checked during
1990 // instantiation.
1991 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001992 Constructor->setNumCtorInitializers(NumInitializers);
1993 CXXCtorInitializer **baseOrMemberInitializers =
1994 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001995 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001996 NumInitializers * sizeof(CXXCtorInitializer*));
1997 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001998 }
1999
2000 return false;
2001 }
2002
John McCallbc83b3f2010-05-20 23:23:51 +00002003 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002004
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002005 // We need to build the initializer AST according to order of construction
2006 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002007 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002008 if (!ClassDecl)
2009 return true;
2010
Eli Friedman9cf6b592009-11-09 19:20:36 +00002011 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002012
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002013 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002014 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002015
2016 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002017 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002018 else
Francois Pichetd583da02010-12-04 09:14:42 +00002019 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002020 }
2021
Anders Carlsson43c64af2010-04-21 19:52:01 +00002022 // Keep track of the direct virtual bases.
2023 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2024 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2025 E = ClassDecl->bases_end(); I != E; ++I) {
2026 if (I->isVirtual())
2027 DirectVBases.insert(I);
2028 }
2029
Anders Carlssondb0a9652010-04-02 06:26:44 +00002030 // Push virtual bases before others.
2031 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2032 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2033
Alexis Hunt1d792652011-01-08 20:30:50 +00002034 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002035 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2036 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002037 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002038 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002039 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002040 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002041 VBase, IsInheritedVirtualBase,
2042 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002043 HadError = true;
2044 continue;
2045 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002046
John McCallbc83b3f2010-05-20 23:23:51 +00002047 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002048 }
2049 }
Mike Stump11289f42009-09-09 15:08:12 +00002050
John McCallbc83b3f2010-05-20 23:23:51 +00002051 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2053 E = ClassDecl->bases_end(); Base != E; ++Base) {
2054 // Virtuals are in the virtual base list and already constructed.
2055 if (Base->isVirtual())
2056 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002057
Alexis Hunt1d792652011-01-08 20:30:50 +00002058 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002059 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2060 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002061 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002062 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002063 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002064 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002065 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002066 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002067 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002068 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002069
John McCallbc83b3f2010-05-20 23:23:51 +00002070 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002071 }
2072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
John McCallbc83b3f2010-05-20 23:23:51 +00002074 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002075 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002076 E = ClassDecl->field_end(); Field != E; ++Field) {
2077 if ((*Field)->getType()->isIncompleteArrayType()) {
2078 assert(ClassDecl->hasFlexibleArrayMember() &&
2079 "Incomplete array type is not valid");
2080 continue;
2081 }
John McCallbc83b3f2010-05-20 23:23:51 +00002082 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002083 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
John McCallbc83b3f2010-05-20 23:23:51 +00002086 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002087 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002088 Constructor->setNumCtorInitializers(NumInitializers);
2089 CXXCtorInitializer **baseOrMemberInitializers =
2090 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002091 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002092 NumInitializers * sizeof(CXXCtorInitializer*));
2093 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002094
John McCalla6309952010-03-16 21:39:52 +00002095 // Constructors implicitly reference the base and member
2096 // destructors.
2097 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2098 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002099 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002100
2101 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002102}
2103
Eli Friedman952c15d2009-07-21 19:28:10 +00002104static void *GetKeyForTopLevelField(FieldDecl *Field) {
2105 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002106 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002107 if (RT->getDecl()->isAnonymousStructOrUnion())
2108 return static_cast<void *>(RT->getDecl());
2109 }
2110 return static_cast<void *>(Field);
2111}
2112
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002113static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002114 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002115}
2116
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002117static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002118 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002119 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002120 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002121
Eli Friedman952c15d2009-07-21 19:28:10 +00002122 // For fields injected into the class via declaration of an anonymous union,
2123 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002124 FieldDecl *Field = Member->getAnyMember();
2125
John McCall23eebd92010-04-10 09:28:51 +00002126 // If the field is a member of an anonymous struct or union, our key
2127 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002128 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002129 if (RD->isAnonymousStructOrUnion()) {
2130 while (true) {
2131 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2132 if (Parent->isAnonymousStructOrUnion())
2133 RD = Parent;
2134 else
2135 break;
2136 }
2137
Anders Carlsson83ac3122010-03-30 16:19:37 +00002138 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002139 }
Mike Stump11289f42009-09-09 15:08:12 +00002140
Anders Carlssona942dcd2010-03-30 15:39:27 +00002141 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002142}
2143
Anders Carlssone857b292010-04-02 03:37:03 +00002144static void
2145DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002146 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002147 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002148 unsigned NumInits) {
2149 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002150 return;
Mike Stump11289f42009-09-09 15:08:12 +00002151
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002152 // Don't check initializers order unless the warning is enabled at the
2153 // location of at least one initializer.
2154 bool ShouldCheckOrder = false;
2155 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002156 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002157 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2158 Init->getSourceLocation())
2159 != Diagnostic::Ignored) {
2160 ShouldCheckOrder = true;
2161 break;
2162 }
2163 }
2164 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002165 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002166
John McCallbb7b6582010-04-10 07:37:23 +00002167 // Build the list of bases and members in the order that they'll
2168 // actually be initialized. The explicit initializers should be in
2169 // this same order but may be missing things.
2170 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002171
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002172 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2173
John McCallbb7b6582010-04-10 07:37:23 +00002174 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002175 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002176 ClassDecl->vbases_begin(),
2177 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002178 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002179
John McCallbb7b6582010-04-10 07:37:23 +00002180 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002181 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002182 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002183 if (Base->isVirtual())
2184 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002185 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
John McCallbb7b6582010-04-10 07:37:23 +00002188 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002189 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2190 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002191 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002192
John McCallbb7b6582010-04-10 07:37:23 +00002193 unsigned NumIdealInits = IdealInitKeys.size();
2194 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002195
Alexis Hunt1d792652011-01-08 20:30:50 +00002196 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002197 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002198 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002199 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002200
2201 // Scan forward to try to find this initializer in the idealized
2202 // initializers list.
2203 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2204 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002205 break;
John McCallbb7b6582010-04-10 07:37:23 +00002206
2207 // If we didn't find this initializer, it must be because we
2208 // scanned past it on a previous iteration. That can only
2209 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002210 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002211 Sema::SemaDiagnosticBuilder D =
2212 SemaRef.Diag(PrevInit->getSourceLocation(),
2213 diag::warn_initializer_out_of_order);
2214
Francois Pichetd583da02010-12-04 09:14:42 +00002215 if (PrevInit->isAnyMemberInitializer())
2216 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002217 else
2218 D << 1 << PrevInit->getBaseClassInfo()->getType();
2219
Francois Pichetd583da02010-12-04 09:14:42 +00002220 if (Init->isAnyMemberInitializer())
2221 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002222 else
2223 D << 1 << Init->getBaseClassInfo()->getType();
2224
2225 // Move back to the initializer's location in the ideal list.
2226 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2227 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002228 break;
John McCallbb7b6582010-04-10 07:37:23 +00002229
2230 assert(IdealIndex != NumIdealInits &&
2231 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002232 }
John McCallbb7b6582010-04-10 07:37:23 +00002233
2234 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002235 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002236}
2237
John McCall23eebd92010-04-10 09:28:51 +00002238namespace {
2239bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002240 CXXCtorInitializer *Init,
2241 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002242 if (!PrevInit) {
2243 PrevInit = Init;
2244 return false;
2245 }
2246
2247 if (FieldDecl *Field = Init->getMember())
2248 S.Diag(Init->getSourceLocation(),
2249 diag::err_multiple_mem_initialization)
2250 << Field->getDeclName()
2251 << Init->getSourceRange();
2252 else {
John McCall424cec92011-01-19 06:33:43 +00002253 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002254 assert(BaseClass && "neither field nor base");
2255 S.Diag(Init->getSourceLocation(),
2256 diag::err_multiple_base_initialization)
2257 << QualType(BaseClass, 0)
2258 << Init->getSourceRange();
2259 }
2260 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2261 << 0 << PrevInit->getSourceRange();
2262
2263 return true;
2264}
2265
Alexis Hunt1d792652011-01-08 20:30:50 +00002266typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002267typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2268
2269bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002270 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002271 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002272 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002273 RecordDecl *Parent = Field->getParent();
2274 if (!Parent->isAnonymousStructOrUnion())
2275 return false;
2276
2277 NamedDecl *Child = Field;
2278 do {
2279 if (Parent->isUnion()) {
2280 UnionEntry &En = Unions[Parent];
2281 if (En.first && En.first != Child) {
2282 S.Diag(Init->getSourceLocation(),
2283 diag::err_multiple_mem_union_initialization)
2284 << Field->getDeclName()
2285 << Init->getSourceRange();
2286 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2287 << 0 << En.second->getSourceRange();
2288 return true;
2289 } else if (!En.first) {
2290 En.first = Child;
2291 En.second = Init;
2292 }
2293 }
2294
2295 Child = Parent;
2296 Parent = cast<RecordDecl>(Parent->getDeclContext());
2297 } while (Parent->isAnonymousStructOrUnion());
2298
2299 return false;
2300}
2301}
2302
Anders Carlssone857b292010-04-02 03:37:03 +00002303/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002304void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002305 SourceLocation ColonLoc,
2306 MemInitTy **meminits, unsigned NumMemInits,
2307 bool AnyErrors) {
2308 if (!ConstructorDecl)
2309 return;
2310
2311 AdjustDeclIfTemplate(ConstructorDecl);
2312
2313 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002314 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002315
2316 if (!Constructor) {
2317 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2318 return;
2319 }
2320
Alexis Hunt1d792652011-01-08 20:30:50 +00002321 CXXCtorInitializer **MemInits =
2322 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002323
2324 // Mapping for the duplicate initializers check.
2325 // For member initializers, this is keyed with a FieldDecl*.
2326 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002327 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002328
2329 // Mapping for the inconsistent anonymous-union initializers check.
2330 RedundantUnionMap MemberUnions;
2331
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002332 bool HadError = false;
2333 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002334 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002335
Abramo Bagnara341d7832010-05-26 18:09:23 +00002336 // Set the source order index.
2337 Init->setSourceOrder(i);
2338
Francois Pichetd583da02010-12-04 09:14:42 +00002339 if (Init->isAnyMemberInitializer()) {
2340 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002341 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2342 CheckRedundantUnionInit(*this, Init, MemberUnions))
2343 HadError = true;
2344 } else {
2345 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2346 if (CheckRedundantInit(*this, Init, Members[Key]))
2347 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002348 }
Anders Carlssone857b292010-04-02 03:37:03 +00002349 }
2350
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002351 if (HadError)
2352 return;
2353
Anders Carlssone857b292010-04-02 03:37:03 +00002354 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002355
Alexis Hunt1d792652011-01-08 20:30:50 +00002356 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002357}
2358
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002359void
John McCalla6309952010-03-16 21:39:52 +00002360Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2361 CXXRecordDecl *ClassDecl) {
2362 // Ignore dependent contexts.
2363 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002364 return;
John McCall1064d7e2010-03-16 05:22:47 +00002365
2366 // FIXME: all the access-control diagnostics are positioned on the
2367 // field/base declaration. That's probably good; that said, the
2368 // user might reasonably want to know why the destructor is being
2369 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002370
Anders Carlssondee9a302009-11-17 04:44:12 +00002371 // Non-static data members.
2372 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2373 E = ClassDecl->field_end(); I != E; ++I) {
2374 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002375 if (Field->isInvalidDecl())
2376 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002377 QualType FieldType = Context.getBaseElementType(Field->getType());
2378
2379 const RecordType* RT = FieldType->getAs<RecordType>();
2380 if (!RT)
2381 continue;
2382
2383 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2384 if (FieldClassDecl->hasTrivialDestructor())
2385 continue;
2386
Douglas Gregore71edda2010-07-01 22:47:18 +00002387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002388 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002389 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002390 << Field->getDeclName()
2391 << FieldType);
2392
John McCalla6309952010-03-16 21:39:52 +00002393 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002394 }
2395
John McCall1064d7e2010-03-16 05:22:47 +00002396 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2397
Anders Carlssondee9a302009-11-17 04:44:12 +00002398 // Bases.
2399 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2400 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002401 // Bases are always records in a well-formed non-dependent class.
2402 const RecordType *RT = Base->getType()->getAs<RecordType>();
2403
2404 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002405 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002406 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002407
2408 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002409 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002410 if (BaseClassDecl->hasTrivialDestructor())
2411 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002412
Douglas Gregore71edda2010-07-01 22:47:18 +00002413 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002414
2415 // FIXME: caret should be on the start of the class name
2416 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002417 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002418 << Base->getType()
2419 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002420
John McCalla6309952010-03-16 21:39:52 +00002421 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002422 }
2423
2424 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002425 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2426 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002427
2428 // Bases are always records in a well-formed non-dependent class.
2429 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2430
2431 // Ignore direct virtual bases.
2432 if (DirectVirtualBases.count(RT))
2433 continue;
2434
Anders Carlssondee9a302009-11-17 04:44:12 +00002435 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002436 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002437 if (BaseClassDecl->hasTrivialDestructor())
2438 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002439
Douglas Gregore71edda2010-07-01 22:47:18 +00002440 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002441 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002442 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002443 << VBase->getType());
2444
John McCalla6309952010-03-16 21:39:52 +00002445 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002446 }
2447}
2448
John McCall48871652010-08-21 09:40:31 +00002449void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002450 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002451 return;
Mike Stump11289f42009-09-09 15:08:12 +00002452
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002454 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002455 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002456}
2457
Mike Stump11289f42009-09-09 15:08:12 +00002458bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002459 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002460 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002461 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002462 else
John McCall02db245d2010-08-18 09:41:07 +00002463 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002464}
2465
Anders Carlssoneabf7702009-08-27 00:13:57 +00002466bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002467 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002468 if (!getLangOptions().CPlusPlus)
2469 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002470
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002471 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002472 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002473
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002474 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002475 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002476 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002477 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002478
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002479 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002480 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002481 }
Mike Stump11289f42009-09-09 15:08:12 +00002482
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002483 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002484 if (!RT)
2485 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002486
John McCall67da35c2010-02-04 22:26:26 +00002487 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002488
John McCall02db245d2010-08-18 09:41:07 +00002489 // We can't answer whether something is abstract until it has a
2490 // definition. If it's currently being defined, we'll walk back
2491 // over all the declarations when we have a full definition.
2492 const CXXRecordDecl *Def = RD->getDefinition();
2493 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002494 return false;
2495
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002496 if (!RD->isAbstract())
2497 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002498
Anders Carlssoneabf7702009-08-27 00:13:57 +00002499 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002500 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002501
John McCall02db245d2010-08-18 09:41:07 +00002502 return true;
2503}
2504
2505void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2506 // Check if we've already emitted the list of pure virtual functions
2507 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002508 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002509 return;
Mike Stump11289f42009-09-09 15:08:12 +00002510
Douglas Gregor4165bd62010-03-23 23:47:56 +00002511 CXXFinalOverriderMap FinalOverriders;
2512 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002513
Anders Carlssona2f74f32010-06-03 01:00:02 +00002514 // Keep a set of seen pure methods so we won't diagnose the same method
2515 // more than once.
2516 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2517
Douglas Gregor4165bd62010-03-23 23:47:56 +00002518 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2519 MEnd = FinalOverriders.end();
2520 M != MEnd;
2521 ++M) {
2522 for (OverridingMethods::iterator SO = M->second.begin(),
2523 SOEnd = M->second.end();
2524 SO != SOEnd; ++SO) {
2525 // C++ [class.abstract]p4:
2526 // A class is abstract if it contains or inherits at least one
2527 // pure virtual function for which the final overrider is pure
2528 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002529
Douglas Gregor4165bd62010-03-23 23:47:56 +00002530 //
2531 if (SO->second.size() != 1)
2532 continue;
2533
2534 if (!SO->second.front().Method->isPure())
2535 continue;
2536
Anders Carlssona2f74f32010-06-03 01:00:02 +00002537 if (!SeenPureMethods.insert(SO->second.front().Method))
2538 continue;
2539
Douglas Gregor4165bd62010-03-23 23:47:56 +00002540 Diag(SO->second.front().Method->getLocation(),
2541 diag::note_pure_virtual_function)
2542 << SO->second.front().Method->getDeclName();
2543 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002544 }
2545
2546 if (!PureVirtualClassDiagSet)
2547 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2548 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002549}
2550
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002551namespace {
John McCall02db245d2010-08-18 09:41:07 +00002552struct AbstractUsageInfo {
2553 Sema &S;
2554 CXXRecordDecl *Record;
2555 CanQualType AbstractType;
2556 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002557
John McCall02db245d2010-08-18 09:41:07 +00002558 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2559 : S(S), Record(Record),
2560 AbstractType(S.Context.getCanonicalType(
2561 S.Context.getTypeDeclType(Record))),
2562 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002563
John McCall02db245d2010-08-18 09:41:07 +00002564 void DiagnoseAbstractType() {
2565 if (Invalid) return;
2566 S.DiagnoseAbstractType(Record);
2567 Invalid = true;
2568 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002569
John McCall02db245d2010-08-18 09:41:07 +00002570 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2571};
2572
2573struct CheckAbstractUsage {
2574 AbstractUsageInfo &Info;
2575 const NamedDecl *Ctx;
2576
2577 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2578 : Info(Info), Ctx(Ctx) {}
2579
2580 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2581 switch (TL.getTypeLocClass()) {
2582#define ABSTRACT_TYPELOC(CLASS, PARENT)
2583#define TYPELOC(CLASS, PARENT) \
2584 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2585#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002586 }
John McCall02db245d2010-08-18 09:41:07 +00002587 }
Mike Stump11289f42009-09-09 15:08:12 +00002588
John McCall02db245d2010-08-18 09:41:07 +00002589 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2590 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2591 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2592 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2593 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002594 }
John McCall02db245d2010-08-18 09:41:07 +00002595 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002596
John McCall02db245d2010-08-18 09:41:07 +00002597 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2598 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
John McCall02db245d2010-08-18 09:41:07 +00002601 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2602 // Visit the type parameters from a permissive context.
2603 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2604 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2605 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2606 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2607 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2608 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002609 }
John McCall02db245d2010-08-18 09:41:07 +00002610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
John McCall02db245d2010-08-18 09:41:07 +00002612 // Visit pointee types from a permissive context.
2613#define CheckPolymorphic(Type) \
2614 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2615 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2616 }
2617 CheckPolymorphic(PointerTypeLoc)
2618 CheckPolymorphic(ReferenceTypeLoc)
2619 CheckPolymorphic(MemberPointerTypeLoc)
2620 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002621
John McCall02db245d2010-08-18 09:41:07 +00002622 /// Handle all the types we haven't given a more specific
2623 /// implementation for above.
2624 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2625 // Every other kind of type that we haven't called out already
2626 // that has an inner type is either (1) sugar or (2) contains that
2627 // inner type in some way as a subobject.
2628 if (TypeLoc Next = TL.getNextTypeLoc())
2629 return Visit(Next, Sel);
2630
2631 // If there's no inner type and we're in a permissive context,
2632 // don't diagnose.
2633 if (Sel == Sema::AbstractNone) return;
2634
2635 // Check whether the type matches the abstract type.
2636 QualType T = TL.getType();
2637 if (T->isArrayType()) {
2638 Sel = Sema::AbstractArrayType;
2639 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002640 }
John McCall02db245d2010-08-18 09:41:07 +00002641 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2642 if (CT != Info.AbstractType) return;
2643
2644 // It matched; do some magic.
2645 if (Sel == Sema::AbstractArrayType) {
2646 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2647 << T << TL.getSourceRange();
2648 } else {
2649 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2650 << Sel << T << TL.getSourceRange();
2651 }
2652 Info.DiagnoseAbstractType();
2653 }
2654};
2655
2656void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2657 Sema::AbstractDiagSelID Sel) {
2658 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2659}
2660
2661}
2662
2663/// Check for invalid uses of an abstract type in a method declaration.
2664static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2665 CXXMethodDecl *MD) {
2666 // No need to do the check on definitions, which require that
2667 // the return/param types be complete.
2668 if (MD->isThisDeclarationADefinition())
2669 return;
2670
2671 // For safety's sake, just ignore it if we don't have type source
2672 // information. This should never happen for non-implicit methods,
2673 // but...
2674 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2675 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2676}
2677
2678/// Check for invalid uses of an abstract type within a class definition.
2679static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2680 CXXRecordDecl *RD) {
2681 for (CXXRecordDecl::decl_iterator
2682 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2683 Decl *D = *I;
2684 if (D->isImplicit()) continue;
2685
2686 // Methods and method templates.
2687 if (isa<CXXMethodDecl>(D)) {
2688 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2689 } else if (isa<FunctionTemplateDecl>(D)) {
2690 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2691 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2692
2693 // Fields and static variables.
2694 } else if (isa<FieldDecl>(D)) {
2695 FieldDecl *FD = cast<FieldDecl>(D);
2696 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2697 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2698 } else if (isa<VarDecl>(D)) {
2699 VarDecl *VD = cast<VarDecl>(D);
2700 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2701 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2702
2703 // Nested classes and class templates.
2704 } else if (isa<CXXRecordDecl>(D)) {
2705 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2706 } else if (isa<ClassTemplateDecl>(D)) {
2707 CheckAbstractClassUsage(Info,
2708 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2709 }
2710 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002711}
2712
Douglas Gregorc99f1552009-12-03 18:33:45 +00002713/// \brief Perform semantic checks on a class definition that has been
2714/// completing, introducing implicitly-declared members, checking for
2715/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002716void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002717 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002718 return;
2719
John McCall02db245d2010-08-18 09:41:07 +00002720 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2721 AbstractUsageInfo Info(*this, Record);
2722 CheckAbstractClassUsage(Info, Record);
2723 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002724
2725 // If this is not an aggregate type and has no user-declared constructor,
2726 // complain about any non-static data members of reference or const scalar
2727 // type, since they will never get initializers.
2728 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2729 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2730 bool Complained = false;
2731 for (RecordDecl::field_iterator F = Record->field_begin(),
2732 FEnd = Record->field_end();
2733 F != FEnd; ++F) {
2734 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002735 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002736 if (!Complained) {
2737 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2738 << Record->getTagKind() << Record;
2739 Complained = true;
2740 }
2741
2742 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2743 << F->getType()->isReferenceType()
2744 << F->getDeclName();
2745 }
2746 }
2747 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002748
Anders Carlssone771e762011-01-25 18:08:22 +00002749 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002750 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002751
2752 if (Record->getIdentifier()) {
2753 // C++ [class.mem]p13:
2754 // If T is the name of a class, then each of the following shall have a
2755 // name different from T:
2756 // - every member of every anonymous union that is a member of class T.
2757 //
2758 // C++ [class.mem]p14:
2759 // In addition, if class T has a user-declared constructor (12.1), every
2760 // non-static data member of class T shall have a name different from T.
2761 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002762 R.first != R.second; ++R.first) {
2763 NamedDecl *D = *R.first;
2764 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2765 isa<IndirectFieldDecl>(D)) {
2766 Diag(D->getLocation(), diag::err_member_name_of_class)
2767 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002768 break;
2769 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002770 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002771 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002772
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002773 // Warn if the class has virtual methods but non-virtual public destructor.
Argyrios Kyrtzidis83b797f2011-02-02 18:47:41 +00002774 if (Record->isDynamicClass() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002775 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002776 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002777 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2778 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2779 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002780
2781 // See if a method overloads virtual methods in a base
2782 /// class without overriding any.
2783 if (!Record->isDependentType()) {
2784 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2785 MEnd = Record->method_end();
2786 M != MEnd; ++M) {
2787 DiagnoseHiddenVirtualMethods(Record, *M);
2788 }
2789 }
2790}
2791
2792/// \brief Data used with FindHiddenVirtualMethod
2793struct FindHiddenVirtualMethodData {
2794 Sema *S;
2795 CXXMethodDecl *Method;
2796 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2797 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2798};
2799
2800/// \brief Member lookup function that determines whether a given C++
2801/// method overloads virtual methods in a base class without overriding any,
2802/// to be used with CXXRecordDecl::lookupInBases().
2803static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2804 CXXBasePath &Path,
2805 void *UserData) {
2806 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2807
2808 FindHiddenVirtualMethodData &Data
2809 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2810
2811 DeclarationName Name = Data.Method->getDeclName();
2812 assert(Name.getNameKind() == DeclarationName::Identifier);
2813
2814 bool foundSameNameMethod = false;
2815 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2816 for (Path.Decls = BaseRecord->lookup(Name);
2817 Path.Decls.first != Path.Decls.second;
2818 ++Path.Decls.first) {
2819 NamedDecl *D = *Path.Decls.first;
2820 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
2821 foundSameNameMethod = true;
2822 // Interested only in hidden virtual methods.
2823 if (!MD->isVirtual())
2824 continue;
2825 // If the method we are checking overrides a method from its base
2826 // don't warn about the other overloaded methods.
2827 if (!Data.S->IsOverload(Data.Method, MD, false))
2828 return true;
2829 // Collect the overload only if its hidden.
2830 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2831 overloadedMethods.push_back(MD);
2832 }
2833 }
2834
2835 if (foundSameNameMethod)
2836 Data.OverloadedMethods.append(overloadedMethods.begin(),
2837 overloadedMethods.end());
2838 return foundSameNameMethod;
2839}
2840
2841/// \brief See if a method overloads virtual methods in a base class without
2842/// overriding any.
2843void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2844 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2845 MD->getLocation()) == Diagnostic::Ignored)
2846 return;
2847 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2848 return;
2849
2850 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2851 /*bool RecordPaths=*/false,
2852 /*bool DetectVirtual=*/false);
2853 FindHiddenVirtualMethodData Data;
2854 Data.Method = MD;
2855 Data.S = this;
2856
2857 // Keep the base methods that were overriden or introduced in the subclass
2858 // by 'using' in a set. A base method not in this set is hidden.
2859 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2860 res.first != res.second; ++res.first) {
2861 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2862 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2863 E = MD->end_overridden_methods();
2864 I != E; ++I)
2865 Data.OverridenAndUsingBaseMethods.insert(*I);
2866 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2867 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
2868 Data.OverridenAndUsingBaseMethods.insert(MD);
2869 }
2870
2871 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2872 !Data.OverloadedMethods.empty()) {
2873 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2874 << MD << (Data.OverloadedMethods.size() > 1);
2875
2876 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2877 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2878 Diag(overloadedMD->getLocation(),
2879 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2880 }
2881 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002882}
2883
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002884void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002885 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002886 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002887 SourceLocation RBrac,
2888 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002889 if (!TagDecl)
2890 return;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002892 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002893
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002894 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002895 // strict aliasing violation!
2896 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002897 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002898
Douglas Gregor0be31a22010-07-02 17:43:08 +00002899 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002900 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002901}
2902
Douglas Gregor95755162010-07-01 05:10:53 +00002903namespace {
2904 /// \brief Helper class that collects exception specifications for
2905 /// implicitly-declared special member functions.
2906 class ImplicitExceptionSpecification {
2907 ASTContext &Context;
2908 bool AllowsAllExceptions;
2909 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2910 llvm::SmallVector<QualType, 4> Exceptions;
2911
2912 public:
2913 explicit ImplicitExceptionSpecification(ASTContext &Context)
2914 : Context(Context), AllowsAllExceptions(false) { }
2915
2916 /// \brief Whether the special member function should have any
2917 /// exception specification at all.
2918 bool hasExceptionSpecification() const {
2919 return !AllowsAllExceptions;
2920 }
2921
2922 /// \brief Whether the special member function should have a
2923 /// throw(...) exception specification (a Microsoft extension).
2924 bool hasAnyExceptionSpecification() const {
2925 return false;
2926 }
2927
2928 /// \brief The number of exceptions in the exception specification.
2929 unsigned size() const { return Exceptions.size(); }
2930
2931 /// \brief The set of exceptions in the exception specification.
2932 const QualType *data() const { return Exceptions.data(); }
2933
2934 /// \brief Note that
2935 void CalledDecl(CXXMethodDecl *Method) {
2936 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002937 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002938 return;
2939
2940 const FunctionProtoType *Proto
2941 = Method->getType()->getAs<FunctionProtoType>();
2942
2943 // If this function can throw any exceptions, make a note of that.
2944 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2945 AllowsAllExceptions = true;
2946 ExceptionsSeen.clear();
2947 Exceptions.clear();
2948 return;
2949 }
2950
2951 // Record the exceptions in this function's exception specification.
2952 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2953 EEnd = Proto->exception_end();
2954 E != EEnd; ++E)
2955 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2956 Exceptions.push_back(*E);
2957 }
2958 };
2959}
2960
2961
Douglas Gregor05379422008-11-03 17:51:48 +00002962/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2963/// special functions, such as the default constructor, copy
2964/// constructor, or destructor, to the given C++ class (C++
2965/// [special]p1). This routine can only be executed just before the
2966/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002967void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002968 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002969 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002970
Douglas Gregor54be3392010-07-01 17:57:27 +00002971 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002972 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002973
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002974 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2975 ++ASTContext::NumImplicitCopyAssignmentOperators;
2976
2977 // If we have a dynamic class, then the copy assignment operator may be
2978 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2979 // it shows up in the right place in the vtable and that we diagnose
2980 // problems with the implicit exception specification.
2981 if (ClassDecl->isDynamicClass())
2982 DeclareImplicitCopyAssignment(ClassDecl);
2983 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002984
Douglas Gregor7454c562010-07-02 20:37:36 +00002985 if (!ClassDecl->hasUserDeclaredDestructor()) {
2986 ++ASTContext::NumImplicitDestructors;
2987
2988 // If we have a dynamic class, then the destructor may be virtual, so we
2989 // have to declare the destructor immediately. This ensures that, e.g., it
2990 // shows up in the right place in the vtable and that we diagnose problems
2991 // with the implicit exception specification.
2992 if (ClassDecl->isDynamicClass())
2993 DeclareImplicitDestructor(ClassDecl);
2994 }
Douglas Gregor05379422008-11-03 17:51:48 +00002995}
2996
John McCall48871652010-08-21 09:40:31 +00002997void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002998 if (!D)
2999 return;
3000
3001 TemplateParameterList *Params = 0;
3002 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3003 Params = Template->getTemplateParameters();
3004 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3005 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3006 Params = PartialSpec->getTemplateParameters();
3007 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003008 return;
3009
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003010 for (TemplateParameterList::iterator Param = Params->begin(),
3011 ParamEnd = Params->end();
3012 Param != ParamEnd; ++Param) {
3013 NamedDecl *Named = cast<NamedDecl>(*Param);
3014 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003015 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003016 IdResolver.AddDecl(Named);
3017 }
3018 }
3019}
3020
John McCall48871652010-08-21 09:40:31 +00003021void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003022 if (!RecordD) return;
3023 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003024 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003025 PushDeclContext(S, Record);
3026}
3027
John McCall48871652010-08-21 09:40:31 +00003028void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003029 if (!RecordD) return;
3030 PopDeclContext();
3031}
3032
Douglas Gregor4d87df52008-12-16 21:30:33 +00003033/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3034/// parsing a top-level (non-nested) C++ class, and we are now
3035/// parsing those parts of the given Method declaration that could
3036/// not be parsed earlier (C++ [class.mem]p2), such as default
3037/// arguments. This action should enter the scope of the given
3038/// Method declaration as if we had just parsed the qualified method
3039/// name. However, it should not bring the parameters into scope;
3040/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003041void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003042}
3043
3044/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3045/// C++ method declaration. We're (re-)introducing the given
3046/// function parameter into scope for use in parsing later parts of
3047/// the method declaration. For example, we could see an
3048/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003049void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003050 if (!ParamD)
3051 return;
Mike Stump11289f42009-09-09 15:08:12 +00003052
John McCall48871652010-08-21 09:40:31 +00003053 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003054
3055 // If this parameter has an unparsed default argument, clear it out
3056 // to make way for the parsed default argument.
3057 if (Param->hasUnparsedDefaultArg())
3058 Param->setDefaultArg(0);
3059
John McCall48871652010-08-21 09:40:31 +00003060 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003061 if (Param->getDeclName())
3062 IdResolver.AddDecl(Param);
3063}
3064
3065/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3066/// processing the delayed method declaration for Method. The method
3067/// declaration is now considered finished. There may be a separate
3068/// ActOnStartOfFunctionDef action later (not necessarily
3069/// immediately!) for this method, if it was also defined inside the
3070/// class body.
John McCall48871652010-08-21 09:40:31 +00003071void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003072 if (!MethodD)
3073 return;
Mike Stump11289f42009-09-09 15:08:12 +00003074
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003075 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003076
John McCall48871652010-08-21 09:40:31 +00003077 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003078
3079 // Now that we have our default arguments, check the constructor
3080 // again. It could produce additional diagnostics or affect whether
3081 // the class has implicitly-declared destructors, among other
3082 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003083 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3084 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003085
3086 // Check the default arguments, which we may have added.
3087 if (!Method->isInvalidDecl())
3088 CheckCXXDefaultArguments(Method);
3089}
3090
Douglas Gregor831c93f2008-11-05 20:51:48 +00003091/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003092/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003093/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003094/// emit diagnostics and set the invalid bit to true. In any case, the type
3095/// will be updated to reflect a well-formed type for the constructor and
3096/// returned.
3097QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003098 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003099 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003100
3101 // C++ [class.ctor]p3:
3102 // A constructor shall not be virtual (10.3) or static (9.4). A
3103 // constructor can be invoked for a const, volatile or const
3104 // volatile object. A constructor shall not be declared const,
3105 // volatile, or const volatile (9.3.2).
3106 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003107 if (!D.isInvalidType())
3108 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3109 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3110 << SourceRange(D.getIdentifierLoc());
3111 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003112 }
John McCall8e7d6562010-08-26 03:08:43 +00003113 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003114 if (!D.isInvalidType())
3115 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3116 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3117 << SourceRange(D.getIdentifierLoc());
3118 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003119 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003120 }
Mike Stump11289f42009-09-09 15:08:12 +00003121
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003122 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003123 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003124 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003125 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3126 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003127 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003128 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3129 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003130 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3132 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003133 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
Douglas Gregordb9d6642011-01-26 05:01:58 +00003136 // C++0x [class.ctor]p4:
3137 // A constructor shall not be declared with a ref-qualifier.
3138 if (FTI.hasRefQualifier()) {
3139 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3140 << FTI.RefQualifierIsLValueRef
3141 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3142 D.setInvalidType();
3143 }
3144
Douglas Gregor831c93f2008-11-05 20:51:48 +00003145 // Rebuild the function type "R" without any type qualifiers (in
3146 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003147 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003148 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003149 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3150 return R;
3151
3152 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3153 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003154 EPI.RefQualifier = RQ_None;
3155
Chris Lattner38378bf2009-04-25 08:28:21 +00003156 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003157 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003158}
3159
Douglas Gregor4d87df52008-12-16 21:30:33 +00003160/// CheckConstructor - Checks a fully-formed constructor for
3161/// well-formedness, issuing any diagnostics required. Returns true if
3162/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003163void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003164 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003165 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3166 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003167 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003168
3169 // C++ [class.copy]p3:
3170 // A declaration of a constructor for a class X is ill-formed if
3171 // its first parameter is of type (optionally cv-qualified) X and
3172 // either there are no other parameters or else all other
3173 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003174 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003175 ((Constructor->getNumParams() == 1) ||
3176 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003177 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3178 Constructor->getTemplateSpecializationKind()
3179 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003180 QualType ParamType = Constructor->getParamDecl(0)->getType();
3181 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3182 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003183 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003184 const char *ConstRef
3185 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3186 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003187 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003188 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003189
3190 // FIXME: Rather that making the constructor invalid, we should endeavor
3191 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003192 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003193 }
3194 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003195}
3196
John McCalldeb646e2010-08-04 01:04:25 +00003197/// CheckDestructor - Checks a fully-formed destructor definition for
3198/// well-formedness, issuing any diagnostics required. Returns true
3199/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003200bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003201 CXXRecordDecl *RD = Destructor->getParent();
3202
3203 if (Destructor->isVirtual()) {
3204 SourceLocation Loc;
3205
3206 if (!Destructor->isImplicit())
3207 Loc = Destructor->getLocation();
3208 else
3209 Loc = RD->getLocation();
3210
3211 // If we have a virtual destructor, look up the deallocation function
3212 FunctionDecl *OperatorDelete = 0;
3213 DeclarationName Name =
3214 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003215 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003216 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003217
3218 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003219
3220 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003221 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003222
3223 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003224}
3225
Mike Stump11289f42009-09-09 15:08:12 +00003226static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003227FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3228 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3229 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003230 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003231}
3232
Douglas Gregor831c93f2008-11-05 20:51:48 +00003233/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3234/// the well-formednes of the destructor declarator @p D with type @p
3235/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003236/// emit diagnostics and set the declarator to invalid. Even if this happens,
3237/// will be updated to reflect a well-formed type for the destructor and
3238/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003239QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003240 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003241 // C++ [class.dtor]p1:
3242 // [...] A typedef-name that names a class is a class-name
3243 // (7.1.3); however, a typedef-name that names a class shall not
3244 // be used as the identifier in the declarator for a destructor
3245 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003246 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003247 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003248 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003249 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003250
3251 // C++ [class.dtor]p2:
3252 // A destructor is used to destroy objects of its class type. A
3253 // destructor takes no parameters, and no return type can be
3254 // specified for it (not even void). The address of a destructor
3255 // shall not be taken. A destructor shall not be static. A
3256 // destructor can be invoked for a const, volatile or const
3257 // volatile object. A destructor shall not be declared const,
3258 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003259 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003260 if (!D.isInvalidType())
3261 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3262 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003263 << SourceRange(D.getIdentifierLoc())
3264 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3265
John McCall8e7d6562010-08-26 03:08:43 +00003266 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003267 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003268 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003269 // Destructors don't have return types, but the parser will
3270 // happily parse something like:
3271 //
3272 // class X {
3273 // float ~X();
3274 // };
3275 //
3276 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003277 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3278 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3279 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003280 }
Mike Stump11289f42009-09-09 15:08:12 +00003281
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003282 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003283 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003284 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003285 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3286 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003287 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003288 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3289 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003290 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003291 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3292 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003293 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003294 }
3295
Douglas Gregordb9d6642011-01-26 05:01:58 +00003296 // C++0x [class.dtor]p2:
3297 // A destructor shall not be declared with a ref-qualifier.
3298 if (FTI.hasRefQualifier()) {
3299 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3300 << FTI.RefQualifierIsLValueRef
3301 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3302 D.setInvalidType();
3303 }
3304
Douglas Gregor831c93f2008-11-05 20:51:48 +00003305 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003306 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003307 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3308
3309 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003310 FTI.freeArgs();
3311 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003312 }
3313
Mike Stump11289f42009-09-09 15:08:12 +00003314 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003315 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003316 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003317 D.setInvalidType();
3318 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003319
3320 // Rebuild the function type "R" without any type qualifiers or
3321 // parameters (in case any of the errors above fired) and with
3322 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003323 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003324 if (!D.isInvalidType())
3325 return R;
3326
Douglas Gregor95755162010-07-01 05:10:53 +00003327 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003328 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3329 EPI.Variadic = false;
3330 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003331 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003332 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003333}
3334
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003335/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3336/// well-formednes of the conversion function declarator @p D with
3337/// type @p R. If there are any errors in the declarator, this routine
3338/// will emit diagnostics and return true. Otherwise, it will return
3339/// false. Either way, the type @p R will be updated to reflect a
3340/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003341void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003342 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003343 // C++ [class.conv.fct]p1:
3344 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003345 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003346 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003347 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003348 if (!D.isInvalidType())
3349 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3350 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3351 << SourceRange(D.getIdentifierLoc());
3352 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003353 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003354 }
John McCall212fa2e2010-04-13 00:04:31 +00003355
3356 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3357
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003358 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003359 // Conversion functions don't have return types, but the parser will
3360 // happily parse something like:
3361 //
3362 // class X {
3363 // float operator bool();
3364 // };
3365 //
3366 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003367 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3368 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3369 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003370 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003371 }
3372
John McCall212fa2e2010-04-13 00:04:31 +00003373 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3374
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003375 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003376 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003377 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3378
3379 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003380 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003381 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003382 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003383 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003384 D.setInvalidType();
3385 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003386
John McCall212fa2e2010-04-13 00:04:31 +00003387 // Diagnose "&operator bool()" and other such nonsense. This
3388 // is actually a gcc extension which we don't support.
3389 if (Proto->getResultType() != ConvType) {
3390 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3391 << Proto->getResultType();
3392 D.setInvalidType();
3393 ConvType = Proto->getResultType();
3394 }
3395
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003396 // C++ [class.conv.fct]p4:
3397 // The conversion-type-id shall not represent a function type nor
3398 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003399 if (ConvType->isArrayType()) {
3400 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3401 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003402 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003403 } else if (ConvType->isFunctionType()) {
3404 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3405 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003406 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003407 }
3408
3409 // Rebuild the function type "R" without any parameters (in case any
3410 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003411 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003412 if (D.isInvalidType())
3413 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003414
Douglas Gregor5fb53972009-01-14 15:45:31 +00003415 // C++0x explicit conversion operators.
3416 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003417 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003418 diag::warn_explicit_conversion_functions)
3419 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003420}
3421
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003422/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3423/// the declaration of the given C++ conversion function. This routine
3424/// is responsible for recording the conversion function in the C++
3425/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003426Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003427 assert(Conversion && "Expected to receive a conversion function declaration");
3428
Douglas Gregor4287b372008-12-12 08:25:50 +00003429 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003430
3431 // Make sure we aren't redeclaring the conversion function.
3432 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003433
3434 // C++ [class.conv.fct]p1:
3435 // [...] A conversion function is never used to convert a
3436 // (possibly cv-qualified) object to the (possibly cv-qualified)
3437 // same object type (or a reference to it), to a (possibly
3438 // cv-qualified) base class of that type (or a reference to it),
3439 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003440 // FIXME: Suppress this warning if the conversion function ends up being a
3441 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003442 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003443 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003444 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003445 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003446 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3447 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003448 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003449 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003450 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3451 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003452 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003453 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003454 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003455 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003456 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003457 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003458 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003459 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003460 }
3461
Douglas Gregor457104e2010-09-29 04:25:11 +00003462 if (FunctionTemplateDecl *ConversionTemplate
3463 = Conversion->getDescribedFunctionTemplate())
3464 return ConversionTemplate;
3465
John McCall48871652010-08-21 09:40:31 +00003466 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003467}
3468
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003469//===----------------------------------------------------------------------===//
3470// Namespace Handling
3471//===----------------------------------------------------------------------===//
3472
John McCallb1be5232010-08-26 09:15:37 +00003473
3474
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003475/// ActOnStartNamespaceDef - This is called at the start of a namespace
3476/// definition.
John McCall48871652010-08-21 09:40:31 +00003477Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003478 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003479 SourceLocation IdentLoc,
3480 IdentifierInfo *II,
3481 SourceLocation LBrace,
3482 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003483 // anonymous namespace starts at its left brace
3484 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3485 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003486 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003487 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003488
3489 Scope *DeclRegionScope = NamespcScope->getParent();
3490
Anders Carlssona7bcade2010-02-07 01:09:23 +00003491 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3492
John McCall2faf32c2010-12-10 02:59:44 +00003493 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3494 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003495
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003496 if (II) {
3497 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003498 // The identifier in an original-namespace-definition shall not
3499 // have been previously defined in the declarative region in
3500 // which the original-namespace-definition appears. The
3501 // identifier in an original-namespace-definition is the name of
3502 // the namespace. Subsequently in that declarative region, it is
3503 // treated as an original-namespace-name.
3504 //
3505 // Since namespace names are unique in their scope, and we don't
3506 // look through using directives, just
3507 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3508 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003509
Douglas Gregor91f84212008-12-11 16:49:14 +00003510 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3511 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003512 if (Namespc->isInline() != OrigNS->isInline()) {
3513 // inline-ness must match
3514 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3515 << Namespc->isInline();
3516 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3517 Namespc->setInvalidDecl();
3518 // Recover by ignoring the new namespace's inline status.
3519 Namespc->setInline(OrigNS->isInline());
3520 }
3521
Douglas Gregor91f84212008-12-11 16:49:14 +00003522 // Attach this namespace decl to the chain of extended namespace
3523 // definitions.
3524 OrigNS->setNextNamespace(Namespc);
3525 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003526
Mike Stump11289f42009-09-09 15:08:12 +00003527 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003528 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003529 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003530 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003531 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003532 } else if (PrevDecl) {
3533 // This is an invalid name redefinition.
3534 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3535 << Namespc->getDeclName();
3536 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3537 Namespc->setInvalidDecl();
3538 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003539 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003540 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003541 // This is the first "real" definition of the namespace "std", so update
3542 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003543 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003544 // We had already defined a dummy namespace "std". Link this new
3545 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003546 StdNS->setNextNamespace(Namespc);
3547 StdNS->setLocation(IdentLoc);
3548 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003549 }
3550
3551 // Make our StdNamespace cache point at the first real definition of the
3552 // "std" namespace.
3553 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003554 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003555
3556 PushOnScopeChains(Namespc, DeclRegionScope);
3557 } else {
John McCall4fa53422009-10-01 00:25:31 +00003558 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003559 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003560
3561 // Link the anonymous namespace into its parent.
3562 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003563 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003564 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3565 PrevDecl = TU->getAnonymousNamespace();
3566 TU->setAnonymousNamespace(Namespc);
3567 } else {
3568 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3569 PrevDecl = ND->getAnonymousNamespace();
3570 ND->setAnonymousNamespace(Namespc);
3571 }
3572
3573 // Link the anonymous namespace with its previous declaration.
3574 if (PrevDecl) {
3575 assert(PrevDecl->isAnonymousNamespace());
3576 assert(!PrevDecl->getNextNamespace());
3577 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3578 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003579
3580 if (Namespc->isInline() != PrevDecl->isInline()) {
3581 // inline-ness must match
3582 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3583 << Namespc->isInline();
3584 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3585 Namespc->setInvalidDecl();
3586 // Recover by ignoring the new namespace's inline status.
3587 Namespc->setInline(PrevDecl->isInline());
3588 }
John McCall0db42252009-12-16 02:06:49 +00003589 }
John McCall4fa53422009-10-01 00:25:31 +00003590
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003591 CurContext->addDecl(Namespc);
3592
John McCall4fa53422009-10-01 00:25:31 +00003593 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3594 // behaves as if it were replaced by
3595 // namespace unique { /* empty body */ }
3596 // using namespace unique;
3597 // namespace unique { namespace-body }
3598 // where all occurrences of 'unique' in a translation unit are
3599 // replaced by the same identifier and this identifier differs
3600 // from all other identifiers in the entire program.
3601
3602 // We just create the namespace with an empty name and then add an
3603 // implicit using declaration, just like the standard suggests.
3604 //
3605 // CodeGen enforces the "universally unique" aspect by giving all
3606 // declarations semantically contained within an anonymous
3607 // namespace internal linkage.
3608
John McCall0db42252009-12-16 02:06:49 +00003609 if (!PrevDecl) {
3610 UsingDirectiveDecl* UD
3611 = UsingDirectiveDecl::Create(Context, CurContext,
3612 /* 'using' */ LBrace,
3613 /* 'namespace' */ SourceLocation(),
3614 /* qualifier */ SourceRange(),
3615 /* NNS */ NULL,
3616 /* identifier */ SourceLocation(),
3617 Namespc,
3618 /* Ancestor */ CurContext);
3619 UD->setImplicit();
3620 CurContext->addDecl(UD);
3621 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003622 }
3623
3624 // Although we could have an invalid decl (i.e. the namespace name is a
3625 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003626 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3627 // for the namespace has the declarations that showed up in that particular
3628 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003629 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003630 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003631}
3632
Sebastian Redla6602e92009-11-23 15:34:23 +00003633/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3634/// is a namespace alias, returns the namespace it points to.
3635static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3636 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3637 return AD->getNamespace();
3638 return dyn_cast_or_null<NamespaceDecl>(D);
3639}
3640
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003641/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3642/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003643void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003644 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3645 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3646 Namespc->setRBracLoc(RBrace);
3647 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003648 if (Namespc->hasAttr<VisibilityAttr>())
3649 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003650}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003651
John McCall28a0cf72010-08-25 07:42:41 +00003652CXXRecordDecl *Sema::getStdBadAlloc() const {
3653 return cast_or_null<CXXRecordDecl>(
3654 StdBadAlloc.get(Context.getExternalSource()));
3655}
3656
3657NamespaceDecl *Sema::getStdNamespace() const {
3658 return cast_or_null<NamespaceDecl>(
3659 StdNamespace.get(Context.getExternalSource()));
3660}
3661
Douglas Gregorcdf87022010-06-29 17:53:46 +00003662/// \brief Retrieve the special "std" namespace, which may require us to
3663/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003664NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003665 if (!StdNamespace) {
3666 // The "std" namespace has not yet been defined, so build one implicitly.
3667 StdNamespace = NamespaceDecl::Create(Context,
3668 Context.getTranslationUnitDecl(),
3669 SourceLocation(),
3670 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003671 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003672 }
3673
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003674 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003675}
3676
John McCall48871652010-08-21 09:40:31 +00003677Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003678 SourceLocation UsingLoc,
3679 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003680 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003681 SourceLocation IdentLoc,
3682 IdentifierInfo *NamespcName,
3683 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003684 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3685 assert(NamespcName && "Invalid NamespcName.");
3686 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003687
3688 // This can only happen along a recovery path.
3689 while (S->getFlags() & Scope::TemplateParamScope)
3690 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003691 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003692
Douglas Gregor889ceb72009-02-03 19:21:40 +00003693 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003694 NestedNameSpecifier *Qualifier = 0;
3695 if (SS.isSet())
3696 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3697
Douglas Gregor34074322009-01-14 22:20:51 +00003698 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003699 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3700 LookupParsedName(R, S, &SS);
3701 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003702 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003703
Douglas Gregorcdf87022010-06-29 17:53:46 +00003704 if (R.empty()) {
3705 // Allow "using namespace std;" or "using namespace ::std;" even if
3706 // "std" hasn't been defined yet, for GCC compatibility.
3707 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3708 NamespcName->isStr("std")) {
3709 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003710 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003711 R.resolveKind();
3712 }
3713 // Otherwise, attempt typo correction.
3714 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3715 CTC_NoKeywords, 0)) {
3716 if (R.getAsSingle<NamespaceDecl>() ||
3717 R.getAsSingle<NamespaceAliasDecl>()) {
3718 if (DeclContext *DC = computeDeclContext(SS, false))
3719 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3720 << NamespcName << DC << Corrected << SS.getRange()
3721 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3722 else
3723 Diag(IdentLoc, diag::err_using_directive_suggest)
3724 << NamespcName << Corrected
3725 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3726 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3727 << Corrected;
3728
3729 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003730 } else {
3731 R.clear();
3732 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003733 }
3734 }
3735 }
3736
John McCall9f3059a2009-10-09 21:13:30 +00003737 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003738 NamedDecl *Named = R.getFoundDecl();
3739 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3740 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003741 // C++ [namespace.udir]p1:
3742 // A using-directive specifies that the names in the nominated
3743 // namespace can be used in the scope in which the
3744 // using-directive appears after the using-directive. During
3745 // unqualified name lookup (3.4.1), the names appear as if they
3746 // were declared in the nearest enclosing namespace which
3747 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003748 // namespace. [Note: in this context, "contains" means "contains
3749 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003750
3751 // Find enclosing context containing both using-directive and
3752 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003753 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003754 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3755 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3756 CommonAncestor = CommonAncestor->getParent();
3757
Sebastian Redla6602e92009-11-23 15:34:23 +00003758 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003759 SS.getRange(),
3760 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003761 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003762 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003763 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003764 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003765 }
3766
Douglas Gregor889ceb72009-02-03 19:21:40 +00003767 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003768 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003769}
3770
3771void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3772 // If scope has associated entity, then using directive is at namespace
3773 // or translation unit scope. We add UsingDirectiveDecls, into
3774 // it's lookup structure.
3775 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003776 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003777 else
3778 // Otherwise it is block-sope. using-directives will affect lookup
3779 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003780 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003781}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003782
Douglas Gregorfec52632009-06-20 00:51:54 +00003783
John McCall48871652010-08-21 09:40:31 +00003784Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003785 AccessSpecifier AS,
3786 bool HasUsingKeyword,
3787 SourceLocation UsingLoc,
3788 CXXScopeSpec &SS,
3789 UnqualifiedId &Name,
3790 AttributeList *AttrList,
3791 bool IsTypeName,
3792 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003793 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003794
Douglas Gregor220f4272009-11-04 16:30:06 +00003795 switch (Name.getKind()) {
3796 case UnqualifiedId::IK_Identifier:
3797 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003798 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003799 case UnqualifiedId::IK_ConversionFunctionId:
3800 break;
3801
3802 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003803 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003804 // C++0x inherited constructors.
3805 if (getLangOptions().CPlusPlus0x) break;
3806
Douglas Gregor220f4272009-11-04 16:30:06 +00003807 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3808 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003809 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003810
3811 case UnqualifiedId::IK_DestructorName:
3812 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3813 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003814 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003815
3816 case UnqualifiedId::IK_TemplateId:
3817 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3818 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003819 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003820 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003821
3822 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3823 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003824 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003825 return 0;
John McCall3969e302009-12-08 07:46:18 +00003826
John McCalla0097262009-12-11 02:10:03 +00003827 // Warn about using declarations.
3828 // TODO: store that the declaration was written without 'using' and
3829 // talk about access decls instead of using decls in the
3830 // diagnostics.
3831 if (!HasUsingKeyword) {
3832 UsingLoc = Name.getSourceRange().getBegin();
3833
3834 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003835 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003836 }
3837
Douglas Gregorc4356532010-12-16 00:46:58 +00003838 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3839 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3840 return 0;
3841
John McCall3f746822009-11-17 05:59:44 +00003842 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003843 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003844 /* IsInstantiation */ false,
3845 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003846 if (UD)
3847 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003848
John McCall48871652010-08-21 09:40:31 +00003849 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003850}
3851
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003852/// \brief Determine whether a using declaration considers the given
3853/// declarations as "equivalent", e.g., if they are redeclarations of
3854/// the same entity or are both typedefs of the same type.
3855static bool
3856IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3857 bool &SuppressRedeclaration) {
3858 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3859 SuppressRedeclaration = false;
3860 return true;
3861 }
3862
3863 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3864 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3865 SuppressRedeclaration = true;
3866 return Context.hasSameType(TD1->getUnderlyingType(),
3867 TD2->getUnderlyingType());
3868 }
3869
3870 return false;
3871}
3872
3873
John McCall84d87672009-12-10 09:41:52 +00003874/// Determines whether to create a using shadow decl for a particular
3875/// decl, given the set of decls existing prior to this using lookup.
3876bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3877 const LookupResult &Previous) {
3878 // Diagnose finding a decl which is not from a base class of the
3879 // current class. We do this now because there are cases where this
3880 // function will silently decide not to build a shadow decl, which
3881 // will pre-empt further diagnostics.
3882 //
3883 // We don't need to do this in C++0x because we do the check once on
3884 // the qualifier.
3885 //
3886 // FIXME: diagnose the following if we care enough:
3887 // struct A { int foo; };
3888 // struct B : A { using A::foo; };
3889 // template <class T> struct C : A {};
3890 // template <class T> struct D : C<T> { using B::foo; } // <---
3891 // This is invalid (during instantiation) in C++03 because B::foo
3892 // resolves to the using decl in B, which is not a base class of D<T>.
3893 // We can't diagnose it immediately because C<T> is an unknown
3894 // specialization. The UsingShadowDecl in D<T> then points directly
3895 // to A::foo, which will look well-formed when we instantiate.
3896 // The right solution is to not collapse the shadow-decl chain.
3897 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3898 DeclContext *OrigDC = Orig->getDeclContext();
3899
3900 // Handle enums and anonymous structs.
3901 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3902 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3903 while (OrigRec->isAnonymousStructOrUnion())
3904 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3905
3906 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3907 if (OrigDC == CurContext) {
3908 Diag(Using->getLocation(),
3909 diag::err_using_decl_nested_name_specifier_is_current_class)
3910 << Using->getNestedNameRange();
3911 Diag(Orig->getLocation(), diag::note_using_decl_target);
3912 return true;
3913 }
3914
3915 Diag(Using->getNestedNameRange().getBegin(),
3916 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3917 << Using->getTargetNestedNameDecl()
3918 << cast<CXXRecordDecl>(CurContext)
3919 << Using->getNestedNameRange();
3920 Diag(Orig->getLocation(), diag::note_using_decl_target);
3921 return true;
3922 }
3923 }
3924
3925 if (Previous.empty()) return false;
3926
3927 NamedDecl *Target = Orig;
3928 if (isa<UsingShadowDecl>(Target))
3929 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3930
John McCalla17e83e2009-12-11 02:33:26 +00003931 // If the target happens to be one of the previous declarations, we
3932 // don't have a conflict.
3933 //
3934 // FIXME: but we might be increasing its access, in which case we
3935 // should redeclare it.
3936 NamedDecl *NonTag = 0, *Tag = 0;
3937 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3938 I != E; ++I) {
3939 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003940 bool Result;
3941 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3942 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003943
3944 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3945 }
3946
John McCall84d87672009-12-10 09:41:52 +00003947 if (Target->isFunctionOrFunctionTemplate()) {
3948 FunctionDecl *FD;
3949 if (isa<FunctionTemplateDecl>(Target))
3950 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3951 else
3952 FD = cast<FunctionDecl>(Target);
3953
3954 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003955 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003956 case Ovl_Overload:
3957 return false;
3958
3959 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003960 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003961 break;
3962
3963 // We found a decl with the exact signature.
3964 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003965 // If we're in a record, we want to hide the target, so we
3966 // return true (without a diagnostic) to tell the caller not to
3967 // build a shadow decl.
3968 if (CurContext->isRecord())
3969 return true;
3970
3971 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003972 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003973 break;
3974 }
3975
3976 Diag(Target->getLocation(), diag::note_using_decl_target);
3977 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3978 return true;
3979 }
3980
3981 // Target is not a function.
3982
John McCall84d87672009-12-10 09:41:52 +00003983 if (isa<TagDecl>(Target)) {
3984 // No conflict between a tag and a non-tag.
3985 if (!Tag) return false;
3986
John McCalle29c5cd2009-12-10 19:51:03 +00003987 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003988 Diag(Target->getLocation(), diag::note_using_decl_target);
3989 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3990 return true;
3991 }
3992
3993 // No conflict between a tag and a non-tag.
3994 if (!NonTag) return false;
3995
John McCalle29c5cd2009-12-10 19:51:03 +00003996 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003997 Diag(Target->getLocation(), diag::note_using_decl_target);
3998 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3999 return true;
4000}
4001
John McCall3f746822009-11-17 05:59:44 +00004002/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004003UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004004 UsingDecl *UD,
4005 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004006
4007 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004008 NamedDecl *Target = Orig;
4009 if (isa<UsingShadowDecl>(Target)) {
4010 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4011 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004012 }
4013
4014 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004015 = UsingShadowDecl::Create(Context, CurContext,
4016 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004017 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004018
4019 Shadow->setAccess(UD->getAccess());
4020 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4021 Shadow->setInvalidDecl();
4022
John McCall3f746822009-11-17 05:59:44 +00004023 if (S)
John McCall3969e302009-12-08 07:46:18 +00004024 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004025 else
John McCall3969e302009-12-08 07:46:18 +00004026 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004027
John McCall3969e302009-12-08 07:46:18 +00004028
John McCall84d87672009-12-10 09:41:52 +00004029 return Shadow;
4030}
John McCall3969e302009-12-08 07:46:18 +00004031
John McCall84d87672009-12-10 09:41:52 +00004032/// Hides a using shadow declaration. This is required by the current
4033/// using-decl implementation when a resolvable using declaration in a
4034/// class is followed by a declaration which would hide or override
4035/// one or more of the using decl's targets; for example:
4036///
4037/// struct Base { void foo(int); };
4038/// struct Derived : Base {
4039/// using Base::foo;
4040/// void foo(int);
4041/// };
4042///
4043/// The governing language is C++03 [namespace.udecl]p12:
4044///
4045/// When a using-declaration brings names from a base class into a
4046/// derived class scope, member functions in the derived class
4047/// override and/or hide member functions with the same name and
4048/// parameter types in a base class (rather than conflicting).
4049///
4050/// There are two ways to implement this:
4051/// (1) optimistically create shadow decls when they're not hidden
4052/// by existing declarations, or
4053/// (2) don't create any shadow decls (or at least don't make them
4054/// visible) until we've fully parsed/instantiated the class.
4055/// The problem with (1) is that we might have to retroactively remove
4056/// a shadow decl, which requires several O(n) operations because the
4057/// decl structures are (very reasonably) not designed for removal.
4058/// (2) avoids this but is very fiddly and phase-dependent.
4059void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004060 if (Shadow->getDeclName().getNameKind() ==
4061 DeclarationName::CXXConversionFunctionName)
4062 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4063
John McCall84d87672009-12-10 09:41:52 +00004064 // Remove it from the DeclContext...
4065 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004066
John McCall84d87672009-12-10 09:41:52 +00004067 // ...and the scope, if applicable...
4068 if (S) {
John McCall48871652010-08-21 09:40:31 +00004069 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004070 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004071 }
4072
John McCall84d87672009-12-10 09:41:52 +00004073 // ...and the using decl.
4074 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4075
4076 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004077 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004078}
4079
John McCalle61f2ba2009-11-18 02:36:19 +00004080/// Builds a using declaration.
4081///
4082/// \param IsInstantiation - Whether this call arises from an
4083/// instantiation of an unresolved using declaration. We treat
4084/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004085NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4086 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004087 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004088 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004089 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004090 bool IsInstantiation,
4091 bool IsTypeName,
4092 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004093 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004094 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004095 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004096
Anders Carlssonf038fc22009-08-28 05:49:21 +00004097 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004098
Anders Carlsson59140b32009-08-28 03:16:11 +00004099 if (SS.isEmpty()) {
4100 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004101 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004102 }
Mike Stump11289f42009-09-09 15:08:12 +00004103
John McCall84d87672009-12-10 09:41:52 +00004104 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004105 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004106 ForRedeclaration);
4107 Previous.setHideTags(false);
4108 if (S) {
4109 LookupName(Previous, S);
4110
4111 // It is really dumb that we have to do this.
4112 LookupResult::Filter F = Previous.makeFilter();
4113 while (F.hasNext()) {
4114 NamedDecl *D = F.next();
4115 if (!isDeclInScope(D, CurContext, S))
4116 F.erase();
4117 }
4118 F.done();
4119 } else {
4120 assert(IsInstantiation && "no scope in non-instantiation");
4121 assert(CurContext->isRecord() && "scope not record in instantiation");
4122 LookupQualifiedName(Previous, CurContext);
4123 }
4124
Mike Stump11289f42009-09-09 15:08:12 +00004125 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00004126 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4127
John McCall84d87672009-12-10 09:41:52 +00004128 // Check for invalid redeclarations.
4129 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4130 return 0;
4131
4132 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004133 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4134 return 0;
4135
John McCall84c16cf2009-11-12 03:15:40 +00004136 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004137 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00004138 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004139 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004140 // FIXME: not all declaration name kinds are legal here
4141 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4142 UsingLoc, TypenameLoc,
4143 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004144 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004145 } else {
4146 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004147 UsingLoc, SS.getRange(),
4148 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004149 }
John McCallb96ec562009-12-04 22:46:56 +00004150 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004151 D = UsingDecl::Create(Context, CurContext,
4152 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00004153 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004154 }
John McCallb96ec562009-12-04 22:46:56 +00004155 D->setAccess(AS);
4156 CurContext->addDecl(D);
4157
4158 if (!LookupContext) return D;
4159 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004160
John McCall0b66eb32010-05-01 00:40:08 +00004161 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004162 UD->setInvalidDecl();
4163 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004164 }
4165
John McCall3969e302009-12-08 07:46:18 +00004166 // Look up the target name.
4167
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004168 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004169
John McCall3969e302009-12-08 07:46:18 +00004170 // Unlike most lookups, we don't always want to hide tag
4171 // declarations: tag names are visible through the using declaration
4172 // even if hidden by ordinary names, *except* in a dependent context
4173 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004174 if (!IsInstantiation)
4175 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004176
John McCall27b18f82009-11-17 02:14:36 +00004177 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004178
John McCall9f3059a2009-10-09 21:13:30 +00004179 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004180 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004181 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004182 UD->setInvalidDecl();
4183 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004184 }
4185
John McCallb96ec562009-12-04 22:46:56 +00004186 if (R.isAmbiguous()) {
4187 UD->setInvalidDecl();
4188 return UD;
4189 }
Mike Stump11289f42009-09-09 15:08:12 +00004190
John McCalle61f2ba2009-11-18 02:36:19 +00004191 if (IsTypeName) {
4192 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004193 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004194 Diag(IdentLoc, diag::err_using_typename_non_type);
4195 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4196 Diag((*I)->getUnderlyingDecl()->getLocation(),
4197 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004198 UD->setInvalidDecl();
4199 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004200 }
4201 } else {
4202 // If we asked for a non-typename and we got a type, error out,
4203 // but only if this is an instantiation of an unresolved using
4204 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004205 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004206 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4207 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004208 UD->setInvalidDecl();
4209 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004210 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004211 }
4212
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004213 // C++0x N2914 [namespace.udecl]p6:
4214 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004215 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004216 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4217 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004218 UD->setInvalidDecl();
4219 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004220 }
Mike Stump11289f42009-09-09 15:08:12 +00004221
John McCall84d87672009-12-10 09:41:52 +00004222 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4223 if (!CheckUsingShadowDecl(UD, *I, Previous))
4224 BuildUsingShadowDecl(S, UD, *I);
4225 }
John McCall3f746822009-11-17 05:59:44 +00004226
4227 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004228}
4229
John McCall84d87672009-12-10 09:41:52 +00004230/// Checks that the given using declaration is not an invalid
4231/// redeclaration. Note that this is checking only for the using decl
4232/// itself, not for any ill-formedness among the UsingShadowDecls.
4233bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4234 bool isTypeName,
4235 const CXXScopeSpec &SS,
4236 SourceLocation NameLoc,
4237 const LookupResult &Prev) {
4238 // C++03 [namespace.udecl]p8:
4239 // C++0x [namespace.udecl]p10:
4240 // A using-declaration is a declaration and can therefore be used
4241 // repeatedly where (and only where) multiple declarations are
4242 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004243 //
John McCall032092f2010-11-29 18:01:58 +00004244 // That's in non-member contexts.
4245 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004246 return false;
4247
4248 NestedNameSpecifier *Qual
4249 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4250
4251 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4252 NamedDecl *D = *I;
4253
4254 bool DTypename;
4255 NestedNameSpecifier *DQual;
4256 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4257 DTypename = UD->isTypeName();
4258 DQual = UD->getTargetNestedNameDecl();
4259 } else if (UnresolvedUsingValueDecl *UD
4260 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4261 DTypename = false;
4262 DQual = UD->getTargetNestedNameSpecifier();
4263 } else if (UnresolvedUsingTypenameDecl *UD
4264 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4265 DTypename = true;
4266 DQual = UD->getTargetNestedNameSpecifier();
4267 } else continue;
4268
4269 // using decls differ if one says 'typename' and the other doesn't.
4270 // FIXME: non-dependent using decls?
4271 if (isTypeName != DTypename) continue;
4272
4273 // using decls differ if they name different scopes (but note that
4274 // template instantiation can cause this check to trigger when it
4275 // didn't before instantiation).
4276 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4277 Context.getCanonicalNestedNameSpecifier(DQual))
4278 continue;
4279
4280 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004281 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004282 return true;
4283 }
4284
4285 return false;
4286}
4287
John McCall3969e302009-12-08 07:46:18 +00004288
John McCallb96ec562009-12-04 22:46:56 +00004289/// Checks that the given nested-name qualifier used in a using decl
4290/// in the current context is appropriately related to the current
4291/// scope. If an error is found, diagnoses it and returns true.
4292bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4293 const CXXScopeSpec &SS,
4294 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004295 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004296
John McCall3969e302009-12-08 07:46:18 +00004297 if (!CurContext->isRecord()) {
4298 // C++03 [namespace.udecl]p3:
4299 // C++0x [namespace.udecl]p8:
4300 // A using-declaration for a class member shall be a member-declaration.
4301
4302 // If we weren't able to compute a valid scope, it must be a
4303 // dependent class scope.
4304 if (!NamedContext || NamedContext->isRecord()) {
4305 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4306 << SS.getRange();
4307 return true;
4308 }
4309
4310 // Otherwise, everything is known to be fine.
4311 return false;
4312 }
4313
4314 // The current scope is a record.
4315
4316 // If the named context is dependent, we can't decide much.
4317 if (!NamedContext) {
4318 // FIXME: in C++0x, we can diagnose if we can prove that the
4319 // nested-name-specifier does not refer to a base class, which is
4320 // still possible in some cases.
4321
4322 // Otherwise we have to conservatively report that things might be
4323 // okay.
4324 return false;
4325 }
4326
4327 if (!NamedContext->isRecord()) {
4328 // Ideally this would point at the last name in the specifier,
4329 // but we don't have that level of source info.
4330 Diag(SS.getRange().getBegin(),
4331 diag::err_using_decl_nested_name_specifier_is_not_class)
4332 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4333 return true;
4334 }
4335
Douglas Gregor7c842292010-12-21 07:41:49 +00004336 if (!NamedContext->isDependentContext() &&
4337 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4338 return true;
4339
John McCall3969e302009-12-08 07:46:18 +00004340 if (getLangOptions().CPlusPlus0x) {
4341 // C++0x [namespace.udecl]p3:
4342 // In a using-declaration used as a member-declaration, the
4343 // nested-name-specifier shall name a base class of the class
4344 // being defined.
4345
4346 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4347 cast<CXXRecordDecl>(NamedContext))) {
4348 if (CurContext == NamedContext) {
4349 Diag(NameLoc,
4350 diag::err_using_decl_nested_name_specifier_is_current_class)
4351 << SS.getRange();
4352 return true;
4353 }
4354
4355 Diag(SS.getRange().getBegin(),
4356 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4357 << (NestedNameSpecifier*) SS.getScopeRep()
4358 << cast<CXXRecordDecl>(CurContext)
4359 << SS.getRange();
4360 return true;
4361 }
4362
4363 return false;
4364 }
4365
4366 // C++03 [namespace.udecl]p4:
4367 // A using-declaration used as a member-declaration shall refer
4368 // to a member of a base class of the class being defined [etc.].
4369
4370 // Salient point: SS doesn't have to name a base class as long as
4371 // lookup only finds members from base classes. Therefore we can
4372 // diagnose here only if we can prove that that can't happen,
4373 // i.e. if the class hierarchies provably don't intersect.
4374
4375 // TODO: it would be nice if "definitely valid" results were cached
4376 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4377 // need to be repeated.
4378
4379 struct UserData {
4380 llvm::DenseSet<const CXXRecordDecl*> Bases;
4381
4382 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4383 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4384 Data->Bases.insert(Base);
4385 return true;
4386 }
4387
4388 bool hasDependentBases(const CXXRecordDecl *Class) {
4389 return !Class->forallBases(collect, this);
4390 }
4391
4392 /// Returns true if the base is dependent or is one of the
4393 /// accumulated base classes.
4394 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4395 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4396 return !Data->Bases.count(Base);
4397 }
4398
4399 bool mightShareBases(const CXXRecordDecl *Class) {
4400 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4401 }
4402 };
4403
4404 UserData Data;
4405
4406 // Returns false if we find a dependent base.
4407 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4408 return false;
4409
4410 // Returns false if the class has a dependent base or if it or one
4411 // of its bases is present in the base set of the current context.
4412 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4413 return false;
4414
4415 Diag(SS.getRange().getBegin(),
4416 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4417 << (NestedNameSpecifier*) SS.getScopeRep()
4418 << cast<CXXRecordDecl>(CurContext)
4419 << SS.getRange();
4420
4421 return true;
John McCallb96ec562009-12-04 22:46:56 +00004422}
4423
John McCall48871652010-08-21 09:40:31 +00004424Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004425 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004426 SourceLocation AliasLoc,
4427 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004428 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004429 SourceLocation IdentLoc,
4430 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004431
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004432 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004433 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4434 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004435
Anders Carlssondca83c42009-03-28 06:23:46 +00004436 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004437 NamedDecl *PrevDecl
4438 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4439 ForRedeclaration);
4440 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4441 PrevDecl = 0;
4442
4443 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004444 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004445 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004446 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004447 // FIXME: At some point, we'll want to create the (redundant)
4448 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004449 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004450 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004451 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004452 }
Mike Stump11289f42009-09-09 15:08:12 +00004453
Anders Carlssondca83c42009-03-28 06:23:46 +00004454 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4455 diag::err_redefinition_different_kind;
4456 Diag(AliasLoc, DiagID) << Alias;
4457 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004458 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004459 }
4460
John McCall27b18f82009-11-17 02:14:36 +00004461 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004462 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004463
John McCall9f3059a2009-10-09 21:13:30 +00004464 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004465 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4466 CTC_NoKeywords, 0)) {
4467 if (R.getAsSingle<NamespaceDecl>() ||
4468 R.getAsSingle<NamespaceAliasDecl>()) {
4469 if (DeclContext *DC = computeDeclContext(SS, false))
4470 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4471 << Ident << DC << Corrected << SS.getRange()
4472 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4473 else
4474 Diag(IdentLoc, diag::err_using_directive_suggest)
4475 << Ident << Corrected
4476 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4477
4478 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4479 << Corrected;
4480
4481 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004482 } else {
4483 R.clear();
4484 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004485 }
4486 }
4487
4488 if (R.empty()) {
4489 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004490 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004491 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004492 }
Mike Stump11289f42009-09-09 15:08:12 +00004493
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004494 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004495 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4496 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004497 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004498 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004499
John McCalld8d0d432010-02-16 06:53:13 +00004500 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004501 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004502}
4503
Douglas Gregora57478e2010-05-01 15:04:51 +00004504namespace {
4505 /// \brief Scoped object used to handle the state changes required in Sema
4506 /// to implicitly define the body of a C++ member function;
4507 class ImplicitlyDefinedFunctionScope {
4508 Sema &S;
4509 DeclContext *PreviousContext;
4510
4511 public:
4512 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4513 : S(S), PreviousContext(S.CurContext)
4514 {
4515 S.CurContext = Method;
4516 S.PushFunctionScope();
4517 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4518 }
4519
4520 ~ImplicitlyDefinedFunctionScope() {
4521 S.PopExpressionEvaluationContext();
4522 S.PopFunctionOrBlockScope();
4523 S.CurContext = PreviousContext;
4524 }
4525 };
4526}
4527
Sebastian Redlc15c3262010-09-13 22:02:47 +00004528static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4529 CXXRecordDecl *D) {
4530 ASTContext &Context = Self.Context;
4531 QualType ClassType = Context.getTypeDeclType(D);
4532 DeclarationName ConstructorName
4533 = Context.DeclarationNames.getCXXConstructorName(
4534 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4535
4536 DeclContext::lookup_const_iterator Con, ConEnd;
4537 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4538 Con != ConEnd; ++Con) {
4539 // FIXME: In C++0x, a constructor template can be a default constructor.
4540 if (isa<FunctionTemplateDecl>(*Con))
4541 continue;
4542
4543 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4544 if (Constructor->isDefaultConstructor())
4545 return Constructor;
4546 }
4547 return 0;
4548}
4549
Douglas Gregor0be31a22010-07-02 17:43:08 +00004550CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4551 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004552 // C++ [class.ctor]p5:
4553 // A default constructor for a class X is a constructor of class X
4554 // that can be called without an argument. If there is no
4555 // user-declared constructor for class X, a default constructor is
4556 // implicitly declared. An implicitly-declared default constructor
4557 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004558 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4559 "Should not build implicit default constructor!");
4560
Douglas Gregor6d880b12010-07-01 22:31:05 +00004561 // C++ [except.spec]p14:
4562 // An implicitly declared special member function (Clause 12) shall have an
4563 // exception-specification. [...]
4564 ImplicitExceptionSpecification ExceptSpec(Context);
4565
4566 // Direct base-class destructors.
4567 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4568 BEnd = ClassDecl->bases_end();
4569 B != BEnd; ++B) {
4570 if (B->isVirtual()) // Handled below.
4571 continue;
4572
Douglas Gregor9672f922010-07-03 00:47:00 +00004573 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4574 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4575 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4576 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004577 else if (CXXConstructorDecl *Constructor
4578 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004579 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004580 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004581 }
4582
4583 // Virtual base-class destructors.
4584 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4585 BEnd = ClassDecl->vbases_end();
4586 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004587 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4588 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4589 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4590 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4591 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004592 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004593 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004594 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004595 }
4596
4597 // Field destructors.
4598 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4599 FEnd = ClassDecl->field_end();
4600 F != FEnd; ++F) {
4601 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004602 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4603 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4604 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4605 ExceptSpec.CalledDecl(
4606 DeclareImplicitDefaultConstructor(FieldClassDecl));
4607 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004608 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004609 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004610 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004611 }
John McCalldb40c7f2010-12-14 08:05:40 +00004612
4613 FunctionProtoType::ExtProtoInfo EPI;
4614 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4615 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4616 EPI.NumExceptions = ExceptSpec.size();
4617 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004618
4619 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004620 CanQualType ClassType
4621 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4622 DeclarationName Name
4623 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004624 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004625 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004626 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004627 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004628 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004629 /*TInfo=*/0,
4630 /*isExplicit=*/false,
4631 /*isInline=*/true,
4632 /*isImplicitlyDeclared=*/true);
4633 DefaultCon->setAccess(AS_public);
4634 DefaultCon->setImplicit();
4635 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004636
4637 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004638 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4639
Douglas Gregor0be31a22010-07-02 17:43:08 +00004640 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004641 PushOnScopeChains(DefaultCon, S, false);
4642 ClassDecl->addDecl(DefaultCon);
4643
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004644 return DefaultCon;
4645}
4646
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004647void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4648 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004649 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004650 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004651 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004652
Anders Carlsson423f5d82010-04-23 16:04:08 +00004653 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004654 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004655
Douglas Gregora57478e2010-05-01 15:04:51 +00004656 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004657 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004658 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004659 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004660 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004661 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004662 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004663 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004664 }
Douglas Gregor73193272010-09-20 16:48:21 +00004665
4666 SourceLocation Loc = Constructor->getLocation();
4667 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4668
4669 Constructor->setUsed();
4670 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004671}
4672
Douglas Gregor0be31a22010-07-02 17:43:08 +00004673CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004674 // C++ [class.dtor]p2:
4675 // If a class has no user-declared destructor, a destructor is
4676 // declared implicitly. An implicitly-declared destructor is an
4677 // inline public member of its class.
4678
4679 // C++ [except.spec]p14:
4680 // An implicitly declared special member function (Clause 12) shall have
4681 // an exception-specification.
4682 ImplicitExceptionSpecification ExceptSpec(Context);
4683
4684 // Direct base-class destructors.
4685 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4686 BEnd = ClassDecl->bases_end();
4687 B != BEnd; ++B) {
4688 if (B->isVirtual()) // Handled below.
4689 continue;
4690
4691 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4692 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004693 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004694 }
4695
4696 // Virtual base-class destructors.
4697 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4698 BEnd = ClassDecl->vbases_end();
4699 B != BEnd; ++B) {
4700 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4701 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004702 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004703 }
4704
4705 // Field destructors.
4706 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4707 FEnd = ClassDecl->field_end();
4708 F != FEnd; ++F) {
4709 if (const RecordType *RecordTy
4710 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4711 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004712 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004713 }
4714
Douglas Gregor7454c562010-07-02 20:37:36 +00004715 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004716 FunctionProtoType::ExtProtoInfo EPI;
4717 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4718 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4719 EPI.NumExceptions = ExceptSpec.size();
4720 EPI.Exceptions = ExceptSpec.data();
4721 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004722
4723 CanQualType ClassType
4724 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4725 DeclarationName Name
4726 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004727 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004728 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004729 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004730 /*isInline=*/true,
4731 /*isImplicitlyDeclared=*/true);
4732 Destructor->setAccess(AS_public);
4733 Destructor->setImplicit();
4734 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004735
4736 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004737 ++ASTContext::NumImplicitDestructorsDeclared;
4738
4739 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004740 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004741 PushOnScopeChains(Destructor, S, false);
4742 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004743
4744 // This could be uniqued if it ever proves significant.
4745 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4746
4747 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004748
Douglas Gregorf1203042010-07-01 19:09:28 +00004749 return Destructor;
4750}
4751
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004752void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004753 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004754 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004755 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004756 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004757 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004758
Douglas Gregor54818f02010-05-12 16:39:35 +00004759 if (Destructor->isInvalidDecl())
4760 return;
4761
Douglas Gregora57478e2010-05-01 15:04:51 +00004762 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004763
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004764 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004765 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4766 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004767
Douglas Gregor54818f02010-05-12 16:39:35 +00004768 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004769 Diag(CurrentLocation, diag::note_member_synthesized_at)
4770 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4771
4772 Destructor->setInvalidDecl();
4773 return;
4774 }
4775
Douglas Gregor73193272010-09-20 16:48:21 +00004776 SourceLocation Loc = Destructor->getLocation();
4777 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4778
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004779 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004780 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004781}
4782
Douglas Gregorb139cd52010-05-01 20:49:11 +00004783/// \brief Builds a statement that copies the given entity from \p From to
4784/// \c To.
4785///
4786/// This routine is used to copy the members of a class with an
4787/// implicitly-declared copy assignment operator. When the entities being
4788/// copied are arrays, this routine builds for loops to copy them.
4789///
4790/// \param S The Sema object used for type-checking.
4791///
4792/// \param Loc The location where the implicit copy is being generated.
4793///
4794/// \param T The type of the expressions being copied. Both expressions must
4795/// have this type.
4796///
4797/// \param To The expression we are copying to.
4798///
4799/// \param From The expression we are copying from.
4800///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004801/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4802/// Otherwise, it's a non-static member subobject.
4803///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004804/// \param Depth Internal parameter recording the depth of the recursion.
4805///
4806/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004807static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004808BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004809 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004810 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004811 // C++0x [class.copy]p30:
4812 // Each subobject is assigned in the manner appropriate to its type:
4813 //
4814 // - if the subobject is of class type, the copy assignment operator
4815 // for the class is used (as if by explicit qualification; that is,
4816 // ignoring any possible virtual overriding functions in more derived
4817 // classes);
4818 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4819 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4820
4821 // Look for operator=.
4822 DeclarationName Name
4823 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4824 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4825 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4826
4827 // Filter out any result that isn't a copy-assignment operator.
4828 LookupResult::Filter F = OpLookup.makeFilter();
4829 while (F.hasNext()) {
4830 NamedDecl *D = F.next();
4831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4832 if (Method->isCopyAssignmentOperator())
4833 continue;
4834
4835 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004836 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004837 F.done();
4838
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004839 // Suppress the protected check (C++ [class.protected]) for each of the
4840 // assignment operators we found. This strange dance is required when
4841 // we're assigning via a base classes's copy-assignment operator. To
4842 // ensure that we're getting the right base class subobject (without
4843 // ambiguities), we need to cast "this" to that subobject type; to
4844 // ensure that we don't go through the virtual call mechanism, we need
4845 // to qualify the operator= name with the base class (see below). However,
4846 // this means that if the base class has a protected copy assignment
4847 // operator, the protected member access check will fail. So, we
4848 // rewrite "protected" access to "public" access in this case, since we
4849 // know by construction that we're calling from a derived class.
4850 if (CopyingBaseSubobject) {
4851 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4852 L != LEnd; ++L) {
4853 if (L.getAccess() == AS_protected)
4854 L.setAccess(AS_public);
4855 }
4856 }
4857
Douglas Gregorb139cd52010-05-01 20:49:11 +00004858 // Create the nested-name-specifier that will be used to qualify the
4859 // reference to operator=; this is required to suppress the virtual
4860 // call mechanism.
4861 CXXScopeSpec SS;
4862 SS.setRange(Loc);
4863 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4864 T.getTypePtr()));
4865
4866 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004867 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004868 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004869 /*FirstQualifierInScope=*/0, OpLookup,
4870 /*TemplateArgs=*/0,
4871 /*SuppressQualifierCheck=*/true);
4872 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004873 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004874
4875 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004876
John McCalldadc5752010-08-24 06:29:42 +00004877 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004878 OpEqualRef.takeAs<Expr>(),
4879 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004880 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004881 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004882
4883 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004884 }
John McCallab8c2732010-03-16 06:11:48 +00004885
Douglas Gregorb139cd52010-05-01 20:49:11 +00004886 // - if the subobject is of scalar type, the built-in assignment
4887 // operator is used.
4888 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4889 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004890 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004891 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004892 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004893
4894 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004895 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004896
4897 // - if the subobject is an array, each element is assigned, in the
4898 // manner appropriate to the element type;
4899
4900 // Construct a loop over the array bounds, e.g.,
4901 //
4902 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4903 //
4904 // that will copy each of the array elements.
4905 QualType SizeType = S.Context.getSizeType();
4906
4907 // Create the iteration variable.
4908 IdentifierInfo *IterationVarName = 0;
4909 {
4910 llvm::SmallString<8> Str;
4911 llvm::raw_svector_ostream OS(Str);
4912 OS << "__i" << Depth;
4913 IterationVarName = &S.Context.Idents.get(OS.str());
4914 }
4915 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4916 IterationVarName, SizeType,
4917 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004918 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004919
4920 // Initialize the iteration variable to zero.
4921 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004922 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004923
4924 // Create a reference to the iteration variable; we'll use this several
4925 // times throughout.
4926 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004927 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004928 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4929
4930 // Create the DeclStmt that holds the iteration variable.
4931 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4932
4933 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004934 llvm::APInt Upper
4935 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004936 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004937 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004938 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4939 BO_NE, S.Context.BoolTy,
4940 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004941
4942 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004943 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004944 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4945 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004946
4947 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004948 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4949 IterationVarRef, Loc));
4950 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4951 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004952
4953 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004954 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4955 To, From, CopyingBaseSubobject,
4956 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004957 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004958 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004959
4960 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004961 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004962 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004963 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004964 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004965}
4966
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004967/// \brief Determine whether the given class has a copy assignment operator
4968/// that accepts a const-qualified argument.
4969static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4970 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4971
4972 if (!Class->hasDeclaredCopyAssignment())
4973 S.DeclareImplicitCopyAssignment(Class);
4974
4975 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4976 DeclarationName OpName
4977 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4978
4979 DeclContext::lookup_const_iterator Op, OpEnd;
4980 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4981 // C++ [class.copy]p9:
4982 // A user-declared copy assignment operator is a non-static non-template
4983 // member function of class X with exactly one parameter of type X, X&,
4984 // const X&, volatile X& or const volatile X&.
4985 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4986 if (!Method)
4987 continue;
4988
4989 if (Method->isStatic())
4990 continue;
4991 if (Method->getPrimaryTemplate())
4992 continue;
4993 const FunctionProtoType *FnType =
4994 Method->getType()->getAs<FunctionProtoType>();
4995 assert(FnType && "Overloaded operator has no prototype.");
4996 // Don't assert on this; an invalid decl might have been left in the AST.
4997 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4998 continue;
4999 bool AcceptsConst = true;
5000 QualType ArgType = FnType->getArgType(0);
5001 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5002 ArgType = Ref->getPointeeType();
5003 // Is it a non-const lvalue reference?
5004 if (!ArgType.isConstQualified())
5005 AcceptsConst = false;
5006 }
5007 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5008 continue;
5009
5010 // We have a single argument of type cv X or cv X&, i.e. we've found the
5011 // copy assignment operator. Return whether it accepts const arguments.
5012 return AcceptsConst;
5013 }
5014 assert(Class->isInvalidDecl() &&
5015 "No copy assignment operator declared in valid code.");
5016 return false;
5017}
5018
Douglas Gregor0be31a22010-07-02 17:43:08 +00005019CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005020 // Note: The following rules are largely analoguous to the copy
5021 // constructor rules. Note that virtual bases are not taken into account
5022 // for determining the argument type of the operator. Note also that
5023 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005024
5025
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005026 // C++ [class.copy]p10:
5027 // If the class definition does not explicitly declare a copy
5028 // assignment operator, one is declared implicitly.
5029 // The implicitly-defined copy assignment operator for a class X
5030 // will have the form
5031 //
5032 // X& X::operator=(const X&)
5033 //
5034 // if
5035 bool HasConstCopyAssignment = true;
5036
5037 // -- each direct base class B of X has a copy assignment operator
5038 // whose parameter is of type const B&, const volatile B& or B,
5039 // and
5040 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5041 BaseEnd = ClassDecl->bases_end();
5042 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5043 assert(!Base->getType()->isDependentType() &&
5044 "Cannot generate implicit members for class with dependent bases.");
5045 const CXXRecordDecl *BaseClassDecl
5046 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005047 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005048 }
5049
5050 // -- for all the nonstatic data members of X that are of a class
5051 // type M (or array thereof), each such class type has a copy
5052 // assignment operator whose parameter is of type const M&,
5053 // const volatile M& or M.
5054 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5055 FieldEnd = ClassDecl->field_end();
5056 HasConstCopyAssignment && Field != FieldEnd;
5057 ++Field) {
5058 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5059 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5060 const CXXRecordDecl *FieldClassDecl
5061 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005062 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005063 }
5064 }
5065
5066 // Otherwise, the implicitly declared copy assignment operator will
5067 // have the form
5068 //
5069 // X& X::operator=(X&)
5070 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5071 QualType RetType = Context.getLValueReferenceType(ArgType);
5072 if (HasConstCopyAssignment)
5073 ArgType = ArgType.withConst();
5074 ArgType = Context.getLValueReferenceType(ArgType);
5075
Douglas Gregor68e11362010-07-01 17:48:08 +00005076 // C++ [except.spec]p14:
5077 // An implicitly declared special member function (Clause 12) shall have an
5078 // exception-specification. [...]
5079 ImplicitExceptionSpecification ExceptSpec(Context);
5080 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5081 BaseEnd = ClassDecl->bases_end();
5082 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005083 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005084 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005085
5086 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5087 DeclareImplicitCopyAssignment(BaseClassDecl);
5088
Douglas Gregor68e11362010-07-01 17:48:08 +00005089 if (CXXMethodDecl *CopyAssign
5090 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5091 ExceptSpec.CalledDecl(CopyAssign);
5092 }
5093 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5094 FieldEnd = ClassDecl->field_end();
5095 Field != FieldEnd;
5096 ++Field) {
5097 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5098 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005099 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005100 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005101
5102 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5103 DeclareImplicitCopyAssignment(FieldClassDecl);
5104
Douglas Gregor68e11362010-07-01 17:48:08 +00005105 if (CXXMethodDecl *CopyAssign
5106 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5107 ExceptSpec.CalledDecl(CopyAssign);
5108 }
5109 }
5110
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005111 // An implicitly-declared copy assignment operator is an inline public
5112 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005113 FunctionProtoType::ExtProtoInfo EPI;
5114 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5115 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5116 EPI.NumExceptions = ExceptSpec.size();
5117 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005118 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005119 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005120 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005121 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005122 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005123 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005124 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005125 /*isInline=*/true);
5126 CopyAssignment->setAccess(AS_public);
5127 CopyAssignment->setImplicit();
5128 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005129
5130 // Add the parameter to the operator.
5131 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5132 ClassDecl->getLocation(),
5133 /*Id=*/0,
5134 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005135 SC_None,
5136 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005137 CopyAssignment->setParams(&FromParam, 1);
5138
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005139 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005140 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5141
Douglas Gregor0be31a22010-07-02 17:43:08 +00005142 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005143 PushOnScopeChains(CopyAssignment, S, false);
5144 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005145
5146 AddOverriddenMethods(ClassDecl, CopyAssignment);
5147 return CopyAssignment;
5148}
5149
Douglas Gregorb139cd52010-05-01 20:49:11 +00005150void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5151 CXXMethodDecl *CopyAssignOperator) {
5152 assert((CopyAssignOperator->isImplicit() &&
5153 CopyAssignOperator->isOverloadedOperator() &&
5154 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005155 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005156 "DefineImplicitCopyAssignment called for wrong function");
5157
5158 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5159
5160 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5161 CopyAssignOperator->setInvalidDecl();
5162 return;
5163 }
5164
5165 CopyAssignOperator->setUsed();
5166
5167 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005168 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005169
5170 // C++0x [class.copy]p30:
5171 // The implicitly-defined or explicitly-defaulted copy assignment operator
5172 // for a non-union class X performs memberwise copy assignment of its
5173 // subobjects. The direct base classes of X are assigned first, in the
5174 // order of their declaration in the base-specifier-list, and then the
5175 // immediate non-static data members of X are assigned, in the order in
5176 // which they were declared in the class definition.
5177
5178 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005179 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005180
5181 // The parameter for the "other" object, which we are copying from.
5182 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5183 Qualifiers OtherQuals = Other->getType().getQualifiers();
5184 QualType OtherRefType = Other->getType();
5185 if (const LValueReferenceType *OtherRef
5186 = OtherRefType->getAs<LValueReferenceType>()) {
5187 OtherRefType = OtherRef->getPointeeType();
5188 OtherQuals = OtherRefType.getQualifiers();
5189 }
5190
5191 // Our location for everything implicitly-generated.
5192 SourceLocation Loc = CopyAssignOperator->getLocation();
5193
5194 // Construct a reference to the "other" object. We'll be using this
5195 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005196 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005197 assert(OtherRef && "Reference to parameter cannot fail!");
5198
5199 // Construct the "this" pointer. We'll be using this throughout the generated
5200 // ASTs.
5201 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5202 assert(This && "Reference to this cannot fail!");
5203
5204 // Assign base classes.
5205 bool Invalid = false;
5206 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5207 E = ClassDecl->bases_end(); Base != E; ++Base) {
5208 // Form the assignment:
5209 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5210 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005211 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005212 Invalid = true;
5213 continue;
5214 }
5215
John McCallcf142162010-08-07 06:22:56 +00005216 CXXCastPath BasePath;
5217 BasePath.push_back(Base);
5218
Douglas Gregorb139cd52010-05-01 20:49:11 +00005219 // Construct the "from" expression, which is an implicit cast to the
5220 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005221 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005222 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005223 CK_UncheckedDerivedToBase,
5224 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005225
5226 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005227 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005228
5229 // Implicitly cast "this" to the appropriately-qualified base type.
5230 Expr *ToE = To.takeAs<Expr>();
5231 ImpCastExprToType(ToE,
5232 Context.getCVRQualifiedType(BaseType,
5233 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005234 CK_UncheckedDerivedToBase,
5235 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005236 To = Owned(ToE);
5237
5238 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005239 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005240 To.get(), From,
5241 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005242 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005243 Diag(CurrentLocation, diag::note_member_synthesized_at)
5244 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5245 CopyAssignOperator->setInvalidDecl();
5246 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005247 }
5248
5249 // Success! Record the copy.
5250 Statements.push_back(Copy.takeAs<Expr>());
5251 }
5252
5253 // \brief Reference to the __builtin_memcpy function.
5254 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005255 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005256 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005257
5258 // Assign non-static members.
5259 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5260 FieldEnd = ClassDecl->field_end();
5261 Field != FieldEnd; ++Field) {
5262 // Check for members of reference type; we can't copy those.
5263 if (Field->getType()->isReferenceType()) {
5264 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5265 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5266 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005267 Diag(CurrentLocation, diag::note_member_synthesized_at)
5268 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005269 Invalid = true;
5270 continue;
5271 }
5272
5273 // Check for members of const-qualified, non-class type.
5274 QualType BaseType = Context.getBaseElementType(Field->getType());
5275 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5276 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5277 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5278 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005279 Diag(CurrentLocation, diag::note_member_synthesized_at)
5280 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005281 Invalid = true;
5282 continue;
5283 }
5284
5285 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005286 if (FieldType->isIncompleteArrayType()) {
5287 assert(ClassDecl->hasFlexibleArrayMember() &&
5288 "Incomplete array type is not valid");
5289 continue;
5290 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005291
5292 // Build references to the field in the object we're copying from and to.
5293 CXXScopeSpec SS; // Intentionally empty
5294 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5295 LookupMemberName);
5296 MemberLookup.addDecl(*Field);
5297 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005298 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005299 Loc, /*IsArrow=*/false,
5300 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005301 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005302 Loc, /*IsArrow=*/true,
5303 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005304 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5305 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5306
5307 // If the field should be copied with __builtin_memcpy rather than via
5308 // explicit assignments, do so. This optimization only applies for arrays
5309 // of scalars and arrays of class type with trivial copy-assignment
5310 // operators.
5311 if (FieldType->isArrayType() &&
5312 (!BaseType->isRecordType() ||
5313 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5314 ->hasTrivialCopyAssignment())) {
5315 // Compute the size of the memory buffer to be copied.
5316 QualType SizeType = Context.getSizeType();
5317 llvm::APInt Size(Context.getTypeSize(SizeType),
5318 Context.getTypeSizeInChars(BaseType).getQuantity());
5319 for (const ConstantArrayType *Array
5320 = Context.getAsConstantArrayType(FieldType);
5321 Array;
5322 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005323 llvm::APInt ArraySize
5324 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005325 Size *= ArraySize;
5326 }
5327
5328 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005329 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5330 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005331
5332 bool NeedsCollectableMemCpy =
5333 (BaseType->isRecordType() &&
5334 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5335
5336 if (NeedsCollectableMemCpy) {
5337 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005338 // Create a reference to the __builtin_objc_memmove_collectable function.
5339 LookupResult R(*this,
5340 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005341 Loc, LookupOrdinaryName);
5342 LookupName(R, TUScope, true);
5343
5344 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5345 if (!CollectableMemCpy) {
5346 // Something went horribly wrong earlier, and we will have
5347 // complained about it.
5348 Invalid = true;
5349 continue;
5350 }
5351
5352 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5353 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005354 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005355 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5356 }
5357 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005358 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005359 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005360 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5361 LookupOrdinaryName);
5362 LookupName(R, TUScope, true);
5363
5364 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5365 if (!BuiltinMemCpy) {
5366 // Something went horribly wrong earlier, and we will have complained
5367 // about it.
5368 Invalid = true;
5369 continue;
5370 }
5371
5372 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5373 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005374 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005375 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5376 }
5377
John McCall37ad5512010-08-23 06:44:23 +00005378 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005379 CallArgs.push_back(To.takeAs<Expr>());
5380 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005381 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005382 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005383 if (NeedsCollectableMemCpy)
5384 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005385 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005386 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005387 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005388 else
5389 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005390 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005391 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005392 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005393
Douglas Gregorb139cd52010-05-01 20:49:11 +00005394 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5395 Statements.push_back(Call.takeAs<Expr>());
5396 continue;
5397 }
5398
5399 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005400 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005401 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005402 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005403 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005404 Diag(CurrentLocation, diag::note_member_synthesized_at)
5405 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5406 CopyAssignOperator->setInvalidDecl();
5407 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005408 }
5409
5410 // Success! Record the copy.
5411 Statements.push_back(Copy.takeAs<Stmt>());
5412 }
5413
5414 if (!Invalid) {
5415 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005416 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005417
John McCalldadc5752010-08-24 06:29:42 +00005418 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005419 if (Return.isInvalid())
5420 Invalid = true;
5421 else {
5422 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005423
5424 if (Trap.hasErrorOccurred()) {
5425 Diag(CurrentLocation, diag::note_member_synthesized_at)
5426 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5427 Invalid = true;
5428 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005429 }
5430 }
5431
5432 if (Invalid) {
5433 CopyAssignOperator->setInvalidDecl();
5434 return;
5435 }
5436
John McCalldadc5752010-08-24 06:29:42 +00005437 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005438 /*isStmtExpr=*/false);
5439 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5440 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005441}
5442
Douglas Gregor0be31a22010-07-02 17:43:08 +00005443CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5444 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005445 // C++ [class.copy]p4:
5446 // If the class definition does not explicitly declare a copy
5447 // constructor, one is declared implicitly.
5448
Douglas Gregor54be3392010-07-01 17:57:27 +00005449 // C++ [class.copy]p5:
5450 // The implicitly-declared copy constructor for a class X will
5451 // have the form
5452 //
5453 // X::X(const X&)
5454 //
5455 // if
5456 bool HasConstCopyConstructor = true;
5457
5458 // -- each direct or virtual base class B of X has a copy
5459 // constructor whose first parameter is of type const B& or
5460 // const volatile B&, and
5461 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5462 BaseEnd = ClassDecl->bases_end();
5463 HasConstCopyConstructor && Base != BaseEnd;
5464 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005465 // Virtual bases are handled below.
5466 if (Base->isVirtual())
5467 continue;
5468
Douglas Gregora6d69502010-07-02 23:41:54 +00005469 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005470 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005471 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5472 DeclareImplicitCopyConstructor(BaseClassDecl);
5473
Douglas Gregorcfe68222010-07-01 18:27:03 +00005474 HasConstCopyConstructor
5475 = BaseClassDecl->hasConstCopyConstructor(Context);
5476 }
5477
5478 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5479 BaseEnd = ClassDecl->vbases_end();
5480 HasConstCopyConstructor && Base != BaseEnd;
5481 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005482 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005483 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005484 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5485 DeclareImplicitCopyConstructor(BaseClassDecl);
5486
Douglas Gregor54be3392010-07-01 17:57:27 +00005487 HasConstCopyConstructor
5488 = BaseClassDecl->hasConstCopyConstructor(Context);
5489 }
5490
5491 // -- for all the nonstatic data members of X that are of a
5492 // class type M (or array thereof), each such class type
5493 // has a copy constructor whose first parameter is of type
5494 // const M& or const volatile M&.
5495 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5496 FieldEnd = ClassDecl->field_end();
5497 HasConstCopyConstructor && Field != FieldEnd;
5498 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005499 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005500 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005501 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005502 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005503 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5504 DeclareImplicitCopyConstructor(FieldClassDecl);
5505
Douglas Gregor54be3392010-07-01 17:57:27 +00005506 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005507 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005508 }
5509 }
5510
5511 // Otherwise, the implicitly declared copy constructor will have
5512 // the form
5513 //
5514 // X::X(X&)
5515 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5516 QualType ArgType = ClassType;
5517 if (HasConstCopyConstructor)
5518 ArgType = ArgType.withConst();
5519 ArgType = Context.getLValueReferenceType(ArgType);
5520
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005521 // C++ [except.spec]p14:
5522 // An implicitly declared special member function (Clause 12) shall have an
5523 // exception-specification. [...]
5524 ImplicitExceptionSpecification ExceptSpec(Context);
5525 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5526 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5527 BaseEnd = ClassDecl->bases_end();
5528 Base != BaseEnd;
5529 ++Base) {
5530 // Virtual bases are handled below.
5531 if (Base->isVirtual())
5532 continue;
5533
Douglas Gregora6d69502010-07-02 23:41:54 +00005534 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005535 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005536 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5537 DeclareImplicitCopyConstructor(BaseClassDecl);
5538
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005539 if (CXXConstructorDecl *CopyConstructor
5540 = BaseClassDecl->getCopyConstructor(Context, Quals))
5541 ExceptSpec.CalledDecl(CopyConstructor);
5542 }
5543 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5544 BaseEnd = ClassDecl->vbases_end();
5545 Base != BaseEnd;
5546 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005547 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005548 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005549 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5550 DeclareImplicitCopyConstructor(BaseClassDecl);
5551
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005552 if (CXXConstructorDecl *CopyConstructor
5553 = BaseClassDecl->getCopyConstructor(Context, Quals))
5554 ExceptSpec.CalledDecl(CopyConstructor);
5555 }
5556 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5557 FieldEnd = ClassDecl->field_end();
5558 Field != FieldEnd;
5559 ++Field) {
5560 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5561 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005562 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005563 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005564 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5565 DeclareImplicitCopyConstructor(FieldClassDecl);
5566
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005567 if (CXXConstructorDecl *CopyConstructor
5568 = FieldClassDecl->getCopyConstructor(Context, Quals))
5569 ExceptSpec.CalledDecl(CopyConstructor);
5570 }
5571 }
5572
Douglas Gregor54be3392010-07-01 17:57:27 +00005573 // An implicitly-declared copy constructor is an inline public
5574 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005575 FunctionProtoType::ExtProtoInfo EPI;
5576 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5577 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5578 EPI.NumExceptions = ExceptSpec.size();
5579 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005580 DeclarationName Name
5581 = Context.DeclarationNames.getCXXConstructorName(
5582 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005583 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005584 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005585 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005586 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005587 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005588 /*TInfo=*/0,
5589 /*isExplicit=*/false,
5590 /*isInline=*/true,
5591 /*isImplicitlyDeclared=*/true);
5592 CopyConstructor->setAccess(AS_public);
5593 CopyConstructor->setImplicit();
5594 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5595
Douglas Gregora6d69502010-07-02 23:41:54 +00005596 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005597 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5598
Douglas Gregor54be3392010-07-01 17:57:27 +00005599 // Add the parameter to the constructor.
5600 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5601 ClassDecl->getLocation(),
5602 /*IdentifierInfo=*/0,
5603 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005604 SC_None,
5605 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005606 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005607 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005608 PushOnScopeChains(CopyConstructor, S, false);
5609 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005610
5611 return CopyConstructor;
5612}
5613
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005614void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5615 CXXConstructorDecl *CopyConstructor,
5616 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005617 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005618 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005619 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005620 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005621
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005622 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005623 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005624
Douglas Gregora57478e2010-05-01 15:04:51 +00005625 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005626 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005627
Alexis Hunt1d792652011-01-08 20:30:50 +00005628 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005629 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005630 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005631 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005632 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005633 } else {
5634 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5635 CopyConstructor->getLocation(),
5636 MultiStmtArg(*this, 0, 0),
5637 /*isStmtExpr=*/false)
5638 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005639 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005640
5641 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005642}
5643
John McCalldadc5752010-08-24 06:29:42 +00005644ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005645Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005646 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005647 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005648 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005649 unsigned ConstructKind,
5650 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005651 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005652
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005653 // C++0x [class.copy]p34:
5654 // When certain criteria are met, an implementation is allowed to
5655 // omit the copy/move construction of a class object, even if the
5656 // copy/move constructor and/or destructor for the object have
5657 // side effects. [...]
5658 // - when a temporary class object that has not been bound to a
5659 // reference (12.2) would be copied/moved to a class object
5660 // with the same cv-unqualified type, the copy/move operation
5661 // can be omitted by constructing the temporary object
5662 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005663 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00005664 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005665 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005666 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005667 }
Mike Stump11289f42009-09-09 15:08:12 +00005668
5669 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005670 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005671 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005672}
5673
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005674/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5675/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005676ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005677Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5678 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005679 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005680 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005681 unsigned ConstructKind,
5682 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005683 unsigned NumExprs = ExprArgs.size();
5684 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005685
Douglas Gregor27381f32009-11-23 12:27:39 +00005686 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005687 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005688 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005689 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005690 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5691 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005692}
5693
Mike Stump11289f42009-09-09 15:08:12 +00005694bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005695 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005696 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005697 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005698 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005699 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005700 move(Exprs), false, CXXConstructExpr::CK_Complete,
5701 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005702 if (TempResult.isInvalid())
5703 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005704
Anders Carlsson6eb55572009-08-25 05:12:04 +00005705 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005706 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005707 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005708 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005709 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005710
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005711 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005712}
5713
John McCall03c48482010-02-02 09:10:11 +00005714void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5715 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005716 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005717 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005718 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005719 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005720 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005721 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005722 << VD->getDeclName()
5723 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005724
John McCall386dfc72010-09-18 05:25:11 +00005725 // TODO: this should be re-enabled for static locals by !CXAAtExit
5726 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005727 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005728 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005729}
5730
Mike Stump11289f42009-09-09 15:08:12 +00005731/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005732/// ActOnDeclarator, when a C++ direct initializer is present.
5733/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005734void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005735 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005736 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005737 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005738 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005739
5740 // If there is no declaration, there was an error parsing it. Just ignore
5741 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005742 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005743 return;
Mike Stump11289f42009-09-09 15:08:12 +00005744
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005745 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5746 if (!VDecl) {
5747 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5748 RealDecl->setInvalidDecl();
5749 return;
5750 }
5751
Douglas Gregor402250f2009-08-26 21:14:46 +00005752 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005753 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005754 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5755 //
5756 // Clients that want to distinguish between the two forms, can check for
5757 // direct initializer using VarDecl::hasCXXDirectInitializer().
5758 // A major benefit is that clients that don't particularly care about which
5759 // exactly form was it (like the CodeGen) can handle both cases without
5760 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005761
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005762 // C++ 8.5p11:
5763 // The form of initialization (using parentheses or '=') is generally
5764 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005765 // class type.
5766
Douglas Gregor50dc2192010-02-11 22:55:30 +00005767 if (!VDecl->getType()->isDependentType() &&
5768 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005769 diag::err_typecheck_decl_incomplete_type)) {
5770 VDecl->setInvalidDecl();
5771 return;
5772 }
5773
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005774 // The variable can not have an abstract class type.
5775 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5776 diag::err_abstract_type_in_decl,
5777 AbstractVariableType))
5778 VDecl->setInvalidDecl();
5779
Sebastian Redl5ca79842010-02-01 20:16:42 +00005780 const VarDecl *Def;
5781 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005782 Diag(VDecl->getLocation(), diag::err_redefinition)
5783 << VDecl->getDeclName();
5784 Diag(Def->getLocation(), diag::note_previous_definition);
5785 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005786 return;
5787 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005788
Douglas Gregorf0f83692010-08-24 05:27:49 +00005789 // C++ [class.static.data]p4
5790 // If a static data member is of const integral or const
5791 // enumeration type, its declaration in the class definition can
5792 // specify a constant-initializer which shall be an integral
5793 // constant expression (5.19). In that case, the member can appear
5794 // in integral constant expressions. The member shall still be
5795 // defined in a namespace scope if it is used in the program and the
5796 // namespace scope definition shall not contain an initializer.
5797 //
5798 // We already performed a redefinition check above, but for static
5799 // data members we also need to check whether there was an in-class
5800 // declaration with an initializer.
5801 const VarDecl* PrevInit = 0;
5802 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5803 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5804 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5805 return;
5806 }
5807
Douglas Gregor71f39c92010-12-16 01:31:22 +00005808 bool IsDependent = false;
5809 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5810 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5811 VDecl->setInvalidDecl();
5812 return;
5813 }
5814
5815 if (Exprs.get()[I]->isTypeDependent())
5816 IsDependent = true;
5817 }
5818
Douglas Gregor50dc2192010-02-11 22:55:30 +00005819 // If either the declaration has a dependent type or if any of the
5820 // expressions is type-dependent, we represent the initialization
5821 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005822 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005823 // Let clients know that initialization was done with a direct initializer.
5824 VDecl->setCXXDirectInitializer(true);
5825
5826 // Store the initialization expressions as a ParenListExpr.
5827 unsigned NumExprs = Exprs.size();
5828 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5829 (Expr **)Exprs.release(),
5830 NumExprs, RParenLoc));
5831 return;
5832 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005833
5834 // Capture the variable that is being initialized and the style of
5835 // initialization.
5836 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5837
5838 // FIXME: Poor source location information.
5839 InitializationKind Kind
5840 = InitializationKind::CreateDirect(VDecl->getLocation(),
5841 LParenLoc, RParenLoc);
5842
5843 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005844 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005845 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005846 if (Result.isInvalid()) {
5847 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005848 return;
5849 }
John McCallacf0ee52010-10-08 02:01:28 +00005850
5851 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005852
Douglas Gregora40433a2010-12-07 00:41:46 +00005853 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005854 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005855 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005856
John McCall8b7fd8f12011-01-19 11:48:09 +00005857 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005858}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005859
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005860/// \brief Given a constructor and the set of arguments provided for the
5861/// constructor, convert the arguments and add any required default arguments
5862/// to form a proper call to this constructor.
5863///
5864/// \returns true if an error occurred, false otherwise.
5865bool
5866Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5867 MultiExprArg ArgsPtr,
5868 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005869 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005870 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5871 unsigned NumArgs = ArgsPtr.size();
5872 Expr **Args = (Expr **)ArgsPtr.get();
5873
5874 const FunctionProtoType *Proto
5875 = Constructor->getType()->getAs<FunctionProtoType>();
5876 assert(Proto && "Constructor without a prototype?");
5877 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005878
5879 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005880 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005881 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005882 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005883 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005884
5885 VariadicCallType CallType =
5886 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5887 llvm::SmallVector<Expr *, 8> AllArgs;
5888 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5889 Proto, 0, Args, NumArgs, AllArgs,
5890 CallType);
5891 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5892 ConvertedArgs.push_back(AllArgs[i]);
5893 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005894}
5895
Anders Carlssone363c8e2009-12-12 00:32:00 +00005896static inline bool
5897CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5898 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005899 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005900 if (isa<NamespaceDecl>(DC)) {
5901 return SemaRef.Diag(FnDecl->getLocation(),
5902 diag::err_operator_new_delete_declared_in_namespace)
5903 << FnDecl->getDeclName();
5904 }
5905
5906 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005907 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005908 return SemaRef.Diag(FnDecl->getLocation(),
5909 diag::err_operator_new_delete_declared_static)
5910 << FnDecl->getDeclName();
5911 }
5912
Anders Carlsson60659a82009-12-12 02:43:16 +00005913 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005914}
5915
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005916static inline bool
5917CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5918 CanQualType ExpectedResultType,
5919 CanQualType ExpectedFirstParamType,
5920 unsigned DependentParamTypeDiag,
5921 unsigned InvalidParamTypeDiag) {
5922 QualType ResultType =
5923 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5924
5925 // Check that the result type is not dependent.
5926 if (ResultType->isDependentType())
5927 return SemaRef.Diag(FnDecl->getLocation(),
5928 diag::err_operator_new_delete_dependent_result_type)
5929 << FnDecl->getDeclName() << ExpectedResultType;
5930
5931 // Check that the result type is what we expect.
5932 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5933 return SemaRef.Diag(FnDecl->getLocation(),
5934 diag::err_operator_new_delete_invalid_result_type)
5935 << FnDecl->getDeclName() << ExpectedResultType;
5936
5937 // A function template must have at least 2 parameters.
5938 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5939 return SemaRef.Diag(FnDecl->getLocation(),
5940 diag::err_operator_new_delete_template_too_few_parameters)
5941 << FnDecl->getDeclName();
5942
5943 // The function decl must have at least 1 parameter.
5944 if (FnDecl->getNumParams() == 0)
5945 return SemaRef.Diag(FnDecl->getLocation(),
5946 diag::err_operator_new_delete_too_few_parameters)
5947 << FnDecl->getDeclName();
5948
5949 // Check the the first parameter type is not dependent.
5950 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5951 if (FirstParamType->isDependentType())
5952 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5953 << FnDecl->getDeclName() << ExpectedFirstParamType;
5954
5955 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005956 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005957 ExpectedFirstParamType)
5958 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5959 << FnDecl->getDeclName() << ExpectedFirstParamType;
5960
5961 return false;
5962}
5963
Anders Carlsson12308f42009-12-11 23:23:22 +00005964static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005965CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005966 // C++ [basic.stc.dynamic.allocation]p1:
5967 // A program is ill-formed if an allocation function is declared in a
5968 // namespace scope other than global scope or declared static in global
5969 // scope.
5970 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5971 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005972
5973 CanQualType SizeTy =
5974 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5975
5976 // C++ [basic.stc.dynamic.allocation]p1:
5977 // The return type shall be void*. The first parameter shall have type
5978 // std::size_t.
5979 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5980 SizeTy,
5981 diag::err_operator_new_dependent_param_type,
5982 diag::err_operator_new_param_type))
5983 return true;
5984
5985 // C++ [basic.stc.dynamic.allocation]p1:
5986 // The first parameter shall not have an associated default argument.
5987 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005988 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005989 diag::err_operator_new_default_arg)
5990 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5991
5992 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005993}
5994
5995static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005996CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5997 // C++ [basic.stc.dynamic.deallocation]p1:
5998 // A program is ill-formed if deallocation functions are declared in a
5999 // namespace scope other than global scope or declared static in global
6000 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006001 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6002 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006003
6004 // C++ [basic.stc.dynamic.deallocation]p2:
6005 // Each deallocation function shall return void and its first parameter
6006 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006007 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6008 SemaRef.Context.VoidPtrTy,
6009 diag::err_operator_delete_dependent_param_type,
6010 diag::err_operator_delete_param_type))
6011 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006012
Anders Carlsson12308f42009-12-11 23:23:22 +00006013 return false;
6014}
6015
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006016/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6017/// of this overloaded operator is well-formed. If so, returns false;
6018/// otherwise, emits appropriate diagnostics and returns true.
6019bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006020 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006021 "Expected an overloaded operator declaration");
6022
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006023 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6024
Mike Stump11289f42009-09-09 15:08:12 +00006025 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006026 // The allocation and deallocation functions, operator new,
6027 // operator new[], operator delete and operator delete[], are
6028 // described completely in 3.7.3. The attributes and restrictions
6029 // found in the rest of this subclause do not apply to them unless
6030 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006031 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006032 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006033
Anders Carlsson22f443f2009-12-12 00:26:23 +00006034 if (Op == OO_New || Op == OO_Array_New)
6035 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006036
6037 // C++ [over.oper]p6:
6038 // An operator function shall either be a non-static member
6039 // function or be a non-member function and have at least one
6040 // parameter whose type is a class, a reference to a class, an
6041 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006042 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6043 if (MethodDecl->isStatic())
6044 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006045 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006046 } else {
6047 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006048 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6049 ParamEnd = FnDecl->param_end();
6050 Param != ParamEnd; ++Param) {
6051 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006052 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6053 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006054 ClassOrEnumParam = true;
6055 break;
6056 }
6057 }
6058
Douglas Gregord69246b2008-11-17 16:14:12 +00006059 if (!ClassOrEnumParam)
6060 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006061 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006062 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006063 }
6064
6065 // C++ [over.oper]p8:
6066 // An operator function cannot have default arguments (8.3.6),
6067 // except where explicitly stated below.
6068 //
Mike Stump11289f42009-09-09 15:08:12 +00006069 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006070 // (C++ [over.call]p1).
6071 if (Op != OO_Call) {
6072 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6073 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006074 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006075 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006076 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006077 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006078 }
6079 }
6080
Douglas Gregor6cf08062008-11-10 13:38:07 +00006081 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6082 { false, false, false }
6083#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6084 , { Unary, Binary, MemberOnly }
6085#include "clang/Basic/OperatorKinds.def"
6086 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006087
Douglas Gregor6cf08062008-11-10 13:38:07 +00006088 bool CanBeUnaryOperator = OperatorUses[Op][0];
6089 bool CanBeBinaryOperator = OperatorUses[Op][1];
6090 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006091
6092 // C++ [over.oper]p8:
6093 // [...] Operator functions cannot have more or fewer parameters
6094 // than the number required for the corresponding operator, as
6095 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006096 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006097 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006098 if (Op != OO_Call &&
6099 ((NumParams == 1 && !CanBeUnaryOperator) ||
6100 (NumParams == 2 && !CanBeBinaryOperator) ||
6101 (NumParams < 1) || (NumParams > 2))) {
6102 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006103 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006104 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006105 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006106 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006107 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006108 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006109 assert(CanBeBinaryOperator &&
6110 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006111 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006112 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006113
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006114 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006115 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006116 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006117
Douglas Gregord69246b2008-11-17 16:14:12 +00006118 // Overloaded operators other than operator() cannot be variadic.
6119 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006120 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006121 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006122 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006123 }
6124
6125 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006126 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6127 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006128 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006129 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006130 }
6131
6132 // C++ [over.inc]p1:
6133 // The user-defined function called operator++ implements the
6134 // prefix and postfix ++ operator. If this function is a member
6135 // function with no parameters, or a non-member function with one
6136 // parameter of class or enumeration type, it defines the prefix
6137 // increment operator ++ for objects of that type. If the function
6138 // is a member function with one parameter (which shall be of type
6139 // int) or a non-member function with two parameters (the second
6140 // of which shall be of type int), it defines the postfix
6141 // increment operator ++ for objects of that type.
6142 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6143 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6144 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006145 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006146 ParamIsInt = BT->getKind() == BuiltinType::Int;
6147
Chris Lattner2b786902008-11-21 07:50:02 +00006148 if (!ParamIsInt)
6149 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006150 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006151 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006152 }
6153
Douglas Gregord69246b2008-11-17 16:14:12 +00006154 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006155}
Chris Lattner3b024a32008-12-17 07:09:26 +00006156
Alexis Huntc88db062010-01-13 09:01:02 +00006157/// CheckLiteralOperatorDeclaration - Check whether the declaration
6158/// of this literal operator function is well-formed. If so, returns
6159/// false; otherwise, emits appropriate diagnostics and returns true.
6160bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6161 DeclContext *DC = FnDecl->getDeclContext();
6162 Decl::Kind Kind = DC->getDeclKind();
6163 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6164 Kind != Decl::LinkageSpec) {
6165 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6166 << FnDecl->getDeclName();
6167 return true;
6168 }
6169
6170 bool Valid = false;
6171
Alexis Hunt7dd26172010-04-07 23:11:06 +00006172 // template <char...> type operator "" name() is the only valid template
6173 // signature, and the only valid signature with no parameters.
6174 if (FnDecl->param_size() == 0) {
6175 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6176 // Must have only one template parameter
6177 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6178 if (Params->size() == 1) {
6179 NonTypeTemplateParmDecl *PmDecl =
6180 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006181
Alexis Hunt7dd26172010-04-07 23:11:06 +00006182 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006183 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6184 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6185 Valid = true;
6186 }
6187 }
6188 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006189 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006190 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6191
Alexis Huntc88db062010-01-13 09:01:02 +00006192 QualType T = (*Param)->getType();
6193
Alexis Hunt079a6f72010-04-07 22:57:35 +00006194 // unsigned long long int, long double, and any character type are allowed
6195 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006196 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6197 Context.hasSameType(T, Context.LongDoubleTy) ||
6198 Context.hasSameType(T, Context.CharTy) ||
6199 Context.hasSameType(T, Context.WCharTy) ||
6200 Context.hasSameType(T, Context.Char16Ty) ||
6201 Context.hasSameType(T, Context.Char32Ty)) {
6202 if (++Param == FnDecl->param_end())
6203 Valid = true;
6204 goto FinishedParams;
6205 }
6206
Alexis Hunt079a6f72010-04-07 22:57:35 +00006207 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006208 const PointerType *PT = T->getAs<PointerType>();
6209 if (!PT)
6210 goto FinishedParams;
6211 T = PT->getPointeeType();
6212 if (!T.isConstQualified())
6213 goto FinishedParams;
6214 T = T.getUnqualifiedType();
6215
6216 // Move on to the second parameter;
6217 ++Param;
6218
6219 // If there is no second parameter, the first must be a const char *
6220 if (Param == FnDecl->param_end()) {
6221 if (Context.hasSameType(T, Context.CharTy))
6222 Valid = true;
6223 goto FinishedParams;
6224 }
6225
6226 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6227 // are allowed as the first parameter to a two-parameter function
6228 if (!(Context.hasSameType(T, Context.CharTy) ||
6229 Context.hasSameType(T, Context.WCharTy) ||
6230 Context.hasSameType(T, Context.Char16Ty) ||
6231 Context.hasSameType(T, Context.Char32Ty)))
6232 goto FinishedParams;
6233
6234 // The second and final parameter must be an std::size_t
6235 T = (*Param)->getType().getUnqualifiedType();
6236 if (Context.hasSameType(T, Context.getSizeType()) &&
6237 ++Param == FnDecl->param_end())
6238 Valid = true;
6239 }
6240
6241 // FIXME: This diagnostic is absolutely terrible.
6242FinishedParams:
6243 if (!Valid) {
6244 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6245 << FnDecl->getDeclName();
6246 return true;
6247 }
6248
6249 return false;
6250}
6251
Douglas Gregor07665a62009-01-05 19:45:36 +00006252/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6253/// linkage specification, including the language and (if present)
6254/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6255/// the location of the language string literal, which is provided
6256/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6257/// the '{' brace. Otherwise, this linkage specification does not
6258/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006259Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6260 SourceLocation LangLoc,
6261 llvm::StringRef Lang,
6262 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006263 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006264 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006265 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006266 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006267 Language = LinkageSpecDecl::lang_cxx;
6268 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006269 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006270 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006271 }
Mike Stump11289f42009-09-09 15:08:12 +00006272
Chris Lattner438e5012008-12-17 07:13:27 +00006273 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006274
Douglas Gregor07665a62009-01-05 19:45:36 +00006275 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006276 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006277 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006278 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006279 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006280 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006281}
6282
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006283/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006284/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6285/// valid, it's the position of the closing '}' brace in a linkage
6286/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006287Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6288 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006289 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006290 if (LinkageSpec)
6291 PopDeclContext();
6292 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006293}
6294
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006295/// \brief Perform semantic analysis for the variable declaration that
6296/// occurs within a C++ catch clause, returning the newly-created
6297/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006298VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006299 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006300 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006301 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006302 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006303 QualType ExDeclType = TInfo->getType();
6304
Sebastian Redl54c04d42008-12-22 19:15:10 +00006305 // Arrays and functions decay.
6306 if (ExDeclType->isArrayType())
6307 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6308 else if (ExDeclType->isFunctionType())
6309 ExDeclType = Context.getPointerType(ExDeclType);
6310
6311 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6312 // The exception-declaration shall not denote a pointer or reference to an
6313 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006314 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006315 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006316 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006317 Invalid = true;
6318 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006319
Douglas Gregor104ee002010-03-08 01:47:36 +00006320 // GCC allows catching pointers and references to incomplete types
6321 // as an extension; so do we, but we warn by default.
6322
Sebastian Redl54c04d42008-12-22 19:15:10 +00006323 QualType BaseType = ExDeclType;
6324 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006325 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006326 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006327 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006328 BaseType = Ptr->getPointeeType();
6329 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006330 DK = diag::ext_catch_incomplete_ptr;
6331 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006332 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006333 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006334 BaseType = Ref->getPointeeType();
6335 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006336 DK = diag::ext_catch_incomplete_ref;
6337 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006338 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006339 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006340 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6341 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006342 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006343
Mike Stump11289f42009-09-09 15:08:12 +00006344 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006345 RequireNonAbstractType(Loc, ExDeclType,
6346 diag::err_abstract_type_in_decl,
6347 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006348 Invalid = true;
6349
John McCall2ca705e2010-07-24 00:37:23 +00006350 // Only the non-fragile NeXT runtime currently supports C++ catches
6351 // of ObjC types, and no runtime supports catching ObjC types by value.
6352 if (!Invalid && getLangOptions().ObjC1) {
6353 QualType T = ExDeclType;
6354 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6355 T = RT->getPointeeType();
6356
6357 if (T->isObjCObjectType()) {
6358 Diag(Loc, diag::err_objc_object_catch);
6359 Invalid = true;
6360 } else if (T->isObjCObjectPointerType()) {
6361 if (!getLangOptions().NeXTRuntime) {
6362 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6363 Invalid = true;
6364 } else if (!getLangOptions().ObjCNonFragileABI) {
6365 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6366 Invalid = true;
6367 }
6368 }
6369 }
6370
Mike Stump11289f42009-09-09 15:08:12 +00006371 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006372 Name, ExDeclType, TInfo, SC_None,
6373 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006374 ExDecl->setExceptionVariable(true);
6375
Douglas Gregor6de584c2010-03-05 23:38:39 +00006376 if (!Invalid) {
6377 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6378 // C++ [except.handle]p16:
6379 // The object declared in an exception-declaration or, if the
6380 // exception-declaration does not specify a name, a temporary (12.2) is
6381 // copy-initialized (8.5) from the exception object. [...]
6382 // The object is destroyed when the handler exits, after the destruction
6383 // of any automatic objects initialized within the handler.
6384 //
6385 // We just pretend to initialize the object with itself, then make sure
6386 // it can be destroyed later.
6387 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6388 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006389 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006390 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6391 SourceLocation());
6392 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006393 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006394 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006395 if (Result.isInvalid())
6396 Invalid = true;
6397 else
6398 FinalizeVarWithDestructor(ExDecl, RecordTy);
6399 }
6400 }
6401
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006402 if (Invalid)
6403 ExDecl->setInvalidDecl();
6404
6405 return ExDecl;
6406}
6407
6408/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6409/// handler.
John McCall48871652010-08-21 09:40:31 +00006410Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006411 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006412 bool Invalid = D.isInvalidType();
6413
6414 // Check for unexpanded parameter packs.
6415 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6416 UPPC_ExceptionType)) {
6417 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6418 D.getIdentifierLoc());
6419 Invalid = true;
6420 }
6421
Sebastian Redl54c04d42008-12-22 19:15:10 +00006422 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006423 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006424 LookupOrdinaryName,
6425 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006426 // The scope should be freshly made just for us. There is just no way
6427 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006428 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006429 if (PrevDecl->isTemplateParameter()) {
6430 // Maybe we will complain about the shadowed template parameter.
6431 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006432 }
6433 }
6434
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006435 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006436 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6437 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006438 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006439 }
6440
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006441 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006442 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006443 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006444
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006445 if (Invalid)
6446 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006447
Sebastian Redl54c04d42008-12-22 19:15:10 +00006448 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006449 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006450 PushOnScopeChains(ExDecl, S);
6451 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006452 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006453
Douglas Gregor758a8692009-06-17 21:51:59 +00006454 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006455 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006456}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006457
John McCall48871652010-08-21 09:40:31 +00006458Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006459 Expr *AssertExpr,
6460 Expr *AssertMessageExpr_) {
6461 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006462
Anders Carlsson54b26982009-03-14 00:33:21 +00006463 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6464 llvm::APSInt Value(32);
6465 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6466 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6467 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006468 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006469 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006470
Anders Carlsson54b26982009-03-14 00:33:21 +00006471 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006472 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006473 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006474 }
6475 }
Mike Stump11289f42009-09-09 15:08:12 +00006476
Douglas Gregoref68fee2010-12-15 23:55:21 +00006477 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6478 return 0;
6479
Mike Stump11289f42009-09-09 15:08:12 +00006480 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006481 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006482
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006483 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006484 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006485}
Sebastian Redlf769df52009-03-24 22:27:57 +00006486
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006487/// \brief Perform semantic analysis of the given friend type declaration.
6488///
6489/// \returns A friend declaration that.
6490FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6491 TypeSourceInfo *TSInfo) {
6492 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6493
6494 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006495 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006496
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006497 if (!getLangOptions().CPlusPlus0x) {
6498 // C++03 [class.friend]p2:
6499 // An elaborated-type-specifier shall be used in a friend declaration
6500 // for a class.*
6501 //
6502 // * The class-key of the elaborated-type-specifier is required.
6503 if (!ActiveTemplateInstantiations.empty()) {
6504 // Do not complain about the form of friend template types during
6505 // template instantiation; we will already have complained when the
6506 // template was declared.
6507 } else if (!T->isElaboratedTypeSpecifier()) {
6508 // If we evaluated the type to a record type, suggest putting
6509 // a tag in front.
6510 if (const RecordType *RT = T->getAs<RecordType>()) {
6511 RecordDecl *RD = RT->getDecl();
6512
6513 std::string InsertionText = std::string(" ") + RD->getKindName();
6514
6515 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6516 << (unsigned) RD->getTagKind()
6517 << T
6518 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6519 InsertionText);
6520 } else {
6521 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6522 << T
6523 << SourceRange(FriendLoc, TypeRange.getEnd());
6524 }
6525 } else if (T->getAs<EnumType>()) {
6526 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006527 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006528 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006529 }
6530 }
6531
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006532 // C++0x [class.friend]p3:
6533 // If the type specifier in a friend declaration designates a (possibly
6534 // cv-qualified) class type, that class is declared as a friend; otherwise,
6535 // the friend declaration is ignored.
6536
6537 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6538 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006539
6540 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6541}
6542
John McCallace48cd2010-10-19 01:40:49 +00006543/// Handle a friend tag declaration where the scope specifier was
6544/// templated.
6545Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6546 unsigned TagSpec, SourceLocation TagLoc,
6547 CXXScopeSpec &SS,
6548 IdentifierInfo *Name, SourceLocation NameLoc,
6549 AttributeList *Attr,
6550 MultiTemplateParamsArg TempParamLists) {
6551 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6552
6553 bool isExplicitSpecialization = false;
6554 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6555 bool Invalid = false;
6556
6557 if (TemplateParameterList *TemplateParams
6558 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6559 TempParamLists.get(),
6560 TempParamLists.size(),
6561 /*friend*/ true,
6562 isExplicitSpecialization,
6563 Invalid)) {
6564 --NumMatchedTemplateParamLists;
6565
6566 if (TemplateParams->size() > 0) {
6567 // This is a declaration of a class template.
6568 if (Invalid)
6569 return 0;
6570
6571 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6572 SS, Name, NameLoc, Attr,
6573 TemplateParams, AS_public).take();
6574 } else {
6575 // The "template<>" header is extraneous.
6576 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6577 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6578 isExplicitSpecialization = true;
6579 }
6580 }
6581
6582 if (Invalid) return 0;
6583
6584 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6585
6586 bool isAllExplicitSpecializations = true;
6587 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6588 if (TempParamLists.get()[I]->size()) {
6589 isAllExplicitSpecializations = false;
6590 break;
6591 }
6592 }
6593
6594 // FIXME: don't ignore attributes.
6595
6596 // If it's explicit specializations all the way down, just forget
6597 // about the template header and build an appropriate non-templated
6598 // friend. TODO: for source fidelity, remember the headers.
6599 if (isAllExplicitSpecializations) {
6600 ElaboratedTypeKeyword Keyword
6601 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6602 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6603 TagLoc, SS.getRange(), NameLoc);
6604 if (T.isNull())
6605 return 0;
6606
6607 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6608 if (isa<DependentNameType>(T)) {
6609 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6610 TL.setKeywordLoc(TagLoc);
6611 TL.setQualifierRange(SS.getRange());
6612 TL.setNameLoc(NameLoc);
6613 } else {
6614 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6615 TL.setKeywordLoc(TagLoc);
6616 TL.setQualifierRange(SS.getRange());
6617 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6618 }
6619
6620 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6621 TSI, FriendLoc);
6622 Friend->setAccess(AS_public);
6623 CurContext->addDecl(Friend);
6624 return Friend;
6625 }
6626
6627 // Handle the case of a templated-scope friend class. e.g.
6628 // template <class T> class A<T>::B;
6629 // FIXME: we don't support these right now.
6630 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6631 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6632 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6633 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6634 TL.setKeywordLoc(TagLoc);
6635 TL.setQualifierRange(SS.getRange());
6636 TL.setNameLoc(NameLoc);
6637
6638 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6639 TSI, FriendLoc);
6640 Friend->setAccess(AS_public);
6641 Friend->setUnsupportedFriend(true);
6642 CurContext->addDecl(Friend);
6643 return Friend;
6644}
6645
6646
John McCall11083da2009-09-16 22:47:08 +00006647/// Handle a friend type declaration. This works in tandem with
6648/// ActOnTag.
6649///
6650/// Notes on friend class templates:
6651///
6652/// We generally treat friend class declarations as if they were
6653/// declaring a class. So, for example, the elaborated type specifier
6654/// in a friend declaration is required to obey the restrictions of a
6655/// class-head (i.e. no typedefs in the scope chain), template
6656/// parameters are required to match up with simple template-ids, &c.
6657/// However, unlike when declaring a template specialization, it's
6658/// okay to refer to a template specialization without an empty
6659/// template parameter declaration, e.g.
6660/// friend class A<T>::B<unsigned>;
6661/// We permit this as a special case; if there are any template
6662/// parameters present at all, require proper matching, i.e.
6663/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006664Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006665 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006666 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006667
6668 assert(DS.isFriendSpecified());
6669 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6670
John McCall11083da2009-09-16 22:47:08 +00006671 // Try to convert the decl specifier to a type. This works for
6672 // friend templates because ActOnTag never produces a ClassTemplateDecl
6673 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006674 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006675 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6676 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006677 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006678 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006679
Douglas Gregor6c110f32010-12-16 01:14:37 +00006680 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6681 return 0;
6682
John McCall11083da2009-09-16 22:47:08 +00006683 // This is definitely an error in C++98. It's probably meant to
6684 // be forbidden in C++0x, too, but the specification is just
6685 // poorly written.
6686 //
6687 // The problem is with declarations like the following:
6688 // template <T> friend A<T>::foo;
6689 // where deciding whether a class C is a friend or not now hinges
6690 // on whether there exists an instantiation of A that causes
6691 // 'foo' to equal C. There are restrictions on class-heads
6692 // (which we declare (by fiat) elaborated friend declarations to
6693 // be) that makes this tractable.
6694 //
6695 // FIXME: handle "template <> friend class A<T>;", which
6696 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006697 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006698 Diag(Loc, diag::err_tagless_friend_type_template)
6699 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006700 return 0;
John McCall11083da2009-09-16 22:47:08 +00006701 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006702
John McCallaa74a0c2009-08-28 07:59:38 +00006703 // C++98 [class.friend]p1: A friend of a class is a function
6704 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006705 // This is fixed in DR77, which just barely didn't make the C++03
6706 // deadline. It's also a very silly restriction that seriously
6707 // affects inner classes and which nobody else seems to implement;
6708 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006709 //
6710 // But note that we could warn about it: it's always useless to
6711 // friend one of your own members (it's not, however, worthless to
6712 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006713
John McCall11083da2009-09-16 22:47:08 +00006714 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006715 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006716 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006717 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006718 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006719 TSI,
John McCall11083da2009-09-16 22:47:08 +00006720 DS.getFriendSpecLoc());
6721 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006722 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6723
6724 if (!D)
John McCall48871652010-08-21 09:40:31 +00006725 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006726
John McCall11083da2009-09-16 22:47:08 +00006727 D->setAccess(AS_public);
6728 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006729
John McCall48871652010-08-21 09:40:31 +00006730 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006731}
6732
John McCallde3fd222010-10-12 23:13:28 +00006733Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6734 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006735 const DeclSpec &DS = D.getDeclSpec();
6736
6737 assert(DS.isFriendSpecified());
6738 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6739
6740 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006741 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6742 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006743
6744 // C++ [class.friend]p1
6745 // A friend of a class is a function or class....
6746 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006747 // It *doesn't* see through dependent types, which is correct
6748 // according to [temp.arg.type]p3:
6749 // If a declaration acquires a function type through a
6750 // type dependent on a template-parameter and this causes
6751 // a declaration that does not use the syntactic form of a
6752 // function declarator to have a function type, the program
6753 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006754 if (!T->isFunctionType()) {
6755 Diag(Loc, diag::err_unexpected_friend);
6756
6757 // It might be worthwhile to try to recover by creating an
6758 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006759 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006760 }
6761
6762 // C++ [namespace.memdef]p3
6763 // - If a friend declaration in a non-local class first declares a
6764 // class or function, the friend class or function is a member
6765 // of the innermost enclosing namespace.
6766 // - The name of the friend is not found by simple name lookup
6767 // until a matching declaration is provided in that namespace
6768 // scope (either before or after the class declaration granting
6769 // friendship).
6770 // - If a friend function is called, its name may be found by the
6771 // name lookup that considers functions from namespaces and
6772 // classes associated with the types of the function arguments.
6773 // - When looking for a prior declaration of a class or a function
6774 // declared as a friend, scopes outside the innermost enclosing
6775 // namespace scope are not considered.
6776
John McCallde3fd222010-10-12 23:13:28 +00006777 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006778 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6779 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006780 assert(Name);
6781
Douglas Gregor6c110f32010-12-16 01:14:37 +00006782 // Check for unexpanded parameter packs.
6783 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6784 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6785 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6786 return 0;
6787
John McCall07e91c02009-08-06 02:15:43 +00006788 // The context we found the declaration in, or in which we should
6789 // create the declaration.
6790 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006791 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006792 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006793 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006794
John McCallde3fd222010-10-12 23:13:28 +00006795 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006796
John McCallde3fd222010-10-12 23:13:28 +00006797 // There are four cases here.
6798 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006799 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006800 // there as appropriate.
6801 // Recover from invalid scope qualifiers as if they just weren't there.
6802 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006803 // C++0x [namespace.memdef]p3:
6804 // If the name in a friend declaration is neither qualified nor
6805 // a template-id and the declaration is a function or an
6806 // elaborated-type-specifier, the lookup to determine whether
6807 // the entity has been previously declared shall not consider
6808 // any scopes outside the innermost enclosing namespace.
6809 // C++0x [class.friend]p11:
6810 // If a friend declaration appears in a local class and the name
6811 // specified is an unqualified name, a prior declaration is
6812 // looked up without considering scopes that are outside the
6813 // innermost enclosing non-class scope. For a friend function
6814 // declaration, if there is no prior declaration, the program is
6815 // ill-formed.
6816 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006817 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006818
John McCallf7cfb222010-10-13 05:45:15 +00006819 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006820 DC = CurContext;
6821 while (true) {
6822 // Skip class contexts. If someone can cite chapter and verse
6823 // for this behavior, that would be nice --- it's what GCC and
6824 // EDG do, and it seems like a reasonable intent, but the spec
6825 // really only says that checks for unqualified existing
6826 // declarations should stop at the nearest enclosing namespace,
6827 // not that they should only consider the nearest enclosing
6828 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006829 while (DC->isRecord())
6830 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006831
John McCall1f82f242009-11-18 22:49:29 +00006832 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006833
6834 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006835 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006836 break;
John McCallf7cfb222010-10-13 05:45:15 +00006837
John McCallf4776592010-10-14 22:22:28 +00006838 if (isTemplateId) {
6839 if (isa<TranslationUnitDecl>(DC)) break;
6840 } else {
6841 if (DC->isFileContext()) break;
6842 }
John McCall07e91c02009-08-06 02:15:43 +00006843 DC = DC->getParent();
6844 }
6845
6846 // C++ [class.friend]p1: A friend of a class is a function or
6847 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006848 // C++0x changes this for both friend types and functions.
6849 // Most C++ 98 compilers do seem to give an error here, so
6850 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006851 if (!Previous.empty() && DC->Equals(CurContext)
6852 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006853 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006854
John McCallccbc0322010-10-13 06:22:15 +00006855 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006856
John McCallde3fd222010-10-12 23:13:28 +00006857 // - There's a non-dependent scope specifier, in which case we
6858 // compute it and do a previous lookup there for a function
6859 // or function template.
6860 } else if (!SS.getScopeRep()->isDependent()) {
6861 DC = computeDeclContext(SS);
6862 if (!DC) return 0;
6863
6864 if (RequireCompleteDeclContext(SS, DC)) return 0;
6865
6866 LookupQualifiedName(Previous, DC);
6867
6868 // Ignore things found implicitly in the wrong scope.
6869 // TODO: better diagnostics for this case. Suggesting the right
6870 // qualified scope would be nice...
6871 LookupResult::Filter F = Previous.makeFilter();
6872 while (F.hasNext()) {
6873 NamedDecl *D = F.next();
6874 if (!DC->InEnclosingNamespaceSetOf(
6875 D->getDeclContext()->getRedeclContext()))
6876 F.erase();
6877 }
6878 F.done();
6879
6880 if (Previous.empty()) {
6881 D.setInvalidType();
6882 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6883 return 0;
6884 }
6885
6886 // C++ [class.friend]p1: A friend of a class is a function or
6887 // class that is not a member of the class . . .
6888 if (DC->Equals(CurContext))
6889 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6890
6891 // - There's a scope specifier that does not match any template
6892 // parameter lists, in which case we use some arbitrary context,
6893 // create a method or method template, and wait for instantiation.
6894 // - There's a scope specifier that does match some template
6895 // parameter lists, which we don't handle right now.
6896 } else {
6897 DC = CurContext;
6898 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006899 }
6900
John McCallf7cfb222010-10-13 05:45:15 +00006901 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006902 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006903 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6904 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6905 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006906 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006907 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6908 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006909 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006910 }
John McCall07e91c02009-08-06 02:15:43 +00006911 }
6912
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006913 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006914 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006915 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006916 IsDefinition,
6917 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006918 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006919
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006920 assert(ND->getDeclContext() == DC);
6921 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006922
John McCall759e32b2009-08-31 22:39:49 +00006923 // Add the function declaration to the appropriate lookup tables,
6924 // adjusting the redeclarations list as necessary. We don't
6925 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006926 //
John McCall759e32b2009-08-31 22:39:49 +00006927 // Also update the scope-based lookup if the target context's
6928 // lookup context is in lexical scope.
6929 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006930 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006931 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006932 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006933 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006934 }
John McCallaa74a0c2009-08-28 07:59:38 +00006935
6936 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006937 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006938 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006939 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006940 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006941
John McCallde3fd222010-10-12 23:13:28 +00006942 if (ND->isInvalidDecl())
6943 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006944 else {
6945 FunctionDecl *FD;
6946 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6947 FD = FTD->getTemplatedDecl();
6948 else
6949 FD = cast<FunctionDecl>(ND);
6950
6951 // Mark templated-scope function declarations as unsupported.
6952 if (FD->getNumTemplateParameterLists())
6953 FrD->setUnsupportedFriend(true);
6954 }
John McCallde3fd222010-10-12 23:13:28 +00006955
John McCall48871652010-08-21 09:40:31 +00006956 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006957}
6958
John McCall48871652010-08-21 09:40:31 +00006959void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6960 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006961
Sebastian Redlf769df52009-03-24 22:27:57 +00006962 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6963 if (!Fn) {
6964 Diag(DelLoc, diag::err_deleted_non_function);
6965 return;
6966 }
6967 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6968 Diag(DelLoc, diag::err_deleted_decl_not_first);
6969 Diag(Prev->getLocation(), diag::note_previous_declaration);
6970 // If the declaration wasn't the first, we delete the function anyway for
6971 // recovery.
6972 }
6973 Fn->setDeleted();
6974}
Sebastian Redl4c018662009-04-27 21:33:24 +00006975
6976static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6977 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6978 ++CI) {
6979 Stmt *SubStmt = *CI;
6980 if (!SubStmt)
6981 continue;
6982 if (isa<ReturnStmt>(SubStmt))
6983 Self.Diag(SubStmt->getSourceRange().getBegin(),
6984 diag::err_return_in_constructor_handler);
6985 if (!isa<Expr>(SubStmt))
6986 SearchForReturnInStmt(Self, SubStmt);
6987 }
6988}
6989
6990void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6991 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6992 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6993 SearchForReturnInStmt(*this, Handler);
6994 }
6995}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006996
Mike Stump11289f42009-09-09 15:08:12 +00006997bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006998 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006999 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7000 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007001
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007002 if (Context.hasSameType(NewTy, OldTy) ||
7003 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007004 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007005
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007006 // Check if the return types are covariant
7007 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007008
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007009 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007010 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7011 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007012 NewClassTy = NewPT->getPointeeType();
7013 OldClassTy = OldPT->getPointeeType();
7014 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007015 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7016 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7017 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7018 NewClassTy = NewRT->getPointeeType();
7019 OldClassTy = OldRT->getPointeeType();
7020 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007021 }
7022 }
Mike Stump11289f42009-09-09 15:08:12 +00007023
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007024 // The return types aren't either both pointers or references to a class type.
7025 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007026 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007027 diag::err_different_return_type_for_overriding_virtual_function)
7028 << New->getDeclName() << NewTy << OldTy;
7029 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007030
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007031 return true;
7032 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007033
Anders Carlssone60365b2009-12-31 18:34:24 +00007034 // C++ [class.virtual]p6:
7035 // If the return type of D::f differs from the return type of B::f, the
7036 // class type in the return type of D::f shall be complete at the point of
7037 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007038 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7039 if (!RT->isBeingDefined() &&
7040 RequireCompleteType(New->getLocation(), NewClassTy,
7041 PDiag(diag::err_covariant_return_incomplete)
7042 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007043 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007044 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007045
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007046 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007047 // Check if the new class derives from the old class.
7048 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7049 Diag(New->getLocation(),
7050 diag::err_covariant_return_not_derived)
7051 << New->getDeclName() << NewTy << OldTy;
7052 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7053 return true;
7054 }
Mike Stump11289f42009-09-09 15:08:12 +00007055
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007056 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007057 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007058 diag::err_covariant_return_inaccessible_base,
7059 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7060 // FIXME: Should this point to the return type?
7061 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007062 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7063 return true;
7064 }
7065 }
Mike Stump11289f42009-09-09 15:08:12 +00007066
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007067 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007068 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007069 Diag(New->getLocation(),
7070 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007071 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007072 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7073 return true;
7074 };
Mike Stump11289f42009-09-09 15:08:12 +00007075
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007076
7077 // The new class type must have the same or less qualifiers as the old type.
7078 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7079 Diag(New->getLocation(),
7080 diag::err_covariant_return_type_class_type_more_qualified)
7081 << New->getDeclName() << NewTy << OldTy;
7082 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7083 return true;
7084 };
Mike Stump11289f42009-09-09 15:08:12 +00007085
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007086 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007087}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007088
Douglas Gregor21920e372009-12-01 17:24:26 +00007089/// \brief Mark the given method pure.
7090///
7091/// \param Method the method to be marked pure.
7092///
7093/// \param InitRange the source range that covers the "0" initializer.
7094bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7095 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7096 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007097 return false;
7098 }
7099
7100 if (!Method->isInvalidDecl())
7101 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7102 << Method->getDeclName() << InitRange;
7103 return true;
7104}
7105
John McCall1f4ee7b2009-12-19 09:28:58 +00007106/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7107/// an initializer for the out-of-line declaration 'Dcl'. The scope
7108/// is a fresh scope pushed for just this purpose.
7109///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007110/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7111/// static data member of class X, names should be looked up in the scope of
7112/// class X.
John McCall48871652010-08-21 09:40:31 +00007113void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007114 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007115 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007116
John McCall1f4ee7b2009-12-19 09:28:58 +00007117 // We should only get called for declarations with scope specifiers, like:
7118 // int foo::bar;
7119 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007120 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007121}
7122
7123/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007124/// initializer for the out-of-line declaration 'D'.
7125void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007126 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007127 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007128
John McCall1f4ee7b2009-12-19 09:28:58 +00007129 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007130 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007131}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007132
7133/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7134/// C++ if/switch/while/for statement.
7135/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007136DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007137 // C++ 6.4p2:
7138 // The declarator shall not specify a function or an array.
7139 // The type-specifier-seq shall not contain typedef and shall not declare a
7140 // new class or enumeration.
7141 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7142 "Parser allowed 'typedef' as storage class of condition decl.");
7143
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007144 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007145 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7146 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007147
7148 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7149 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7150 // would be created and CXXConditionDeclExpr wants a VarDecl.
7151 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7152 << D.getSourceRange();
7153 return DeclResult();
7154 } else if (OwnedTag && OwnedTag->isDefinition()) {
7155 // The type-specifier-seq shall not declare a new class or enumeration.
7156 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7157 }
7158
John McCall48871652010-08-21 09:40:31 +00007159 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007160 if (!Dcl)
7161 return DeclResult();
7162
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007163 return Dcl;
7164}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007165
Douglas Gregor88d292c2010-05-13 16:44:06 +00007166void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7167 bool DefinitionRequired) {
7168 // Ignore any vtable uses in unevaluated operands or for classes that do
7169 // not have a vtable.
7170 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7171 CurContext->isDependentContext() ||
7172 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007173 return;
7174
Douglas Gregor88d292c2010-05-13 16:44:06 +00007175 // Try to insert this class into the map.
7176 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7177 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7178 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7179 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007180 // If we already had an entry, check to see if we are promoting this vtable
7181 // to required a definition. If so, we need to reappend to the VTableUses
7182 // list, since we may have already processed the first entry.
7183 if (DefinitionRequired && !Pos.first->second) {
7184 Pos.first->second = true;
7185 } else {
7186 // Otherwise, we can early exit.
7187 return;
7188 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007189 }
7190
7191 // Local classes need to have their virtual members marked
7192 // immediately. For all other classes, we mark their virtual members
7193 // at the end of the translation unit.
7194 if (Class->isLocalClass())
7195 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007196 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007197 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007198}
7199
Douglas Gregor88d292c2010-05-13 16:44:06 +00007200bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007201 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007202 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007203
Douglas Gregor88d292c2010-05-13 16:44:06 +00007204 // Note: The VTableUses vector could grow as a result of marking
7205 // the members of a class as "used", so we check the size each
7206 // time through the loop and prefer indices (with are stable) to
7207 // iterators (which are not).
7208 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007209 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007210 if (!Class)
7211 continue;
7212
7213 SourceLocation Loc = VTableUses[I].second;
7214
7215 // If this class has a key function, but that key function is
7216 // defined in another translation unit, we don't need to emit the
7217 // vtable even though we're using it.
7218 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007219 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007220 switch (KeyFunction->getTemplateSpecializationKind()) {
7221 case TSK_Undeclared:
7222 case TSK_ExplicitSpecialization:
7223 case TSK_ExplicitInstantiationDeclaration:
7224 // The key function is in another translation unit.
7225 continue;
7226
7227 case TSK_ExplicitInstantiationDefinition:
7228 case TSK_ImplicitInstantiation:
7229 // We will be instantiating the key function.
7230 break;
7231 }
7232 } else if (!KeyFunction) {
7233 // If we have a class with no key function that is the subject
7234 // of an explicit instantiation declaration, suppress the
7235 // vtable; it will live with the explicit instantiation
7236 // definition.
7237 bool IsExplicitInstantiationDeclaration
7238 = Class->getTemplateSpecializationKind()
7239 == TSK_ExplicitInstantiationDeclaration;
7240 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7241 REnd = Class->redecls_end();
7242 R != REnd; ++R) {
7243 TemplateSpecializationKind TSK
7244 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7245 if (TSK == TSK_ExplicitInstantiationDeclaration)
7246 IsExplicitInstantiationDeclaration = true;
7247 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7248 IsExplicitInstantiationDeclaration = false;
7249 break;
7250 }
7251 }
7252
7253 if (IsExplicitInstantiationDeclaration)
7254 continue;
7255 }
7256
7257 // Mark all of the virtual members of this class as referenced, so
7258 // that we can build a vtable. Then, tell the AST consumer that a
7259 // vtable for this class is required.
7260 MarkVirtualMembersReferenced(Loc, Class);
7261 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7262 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7263
7264 // Optionally warn if we're emitting a weak vtable.
7265 if (Class->getLinkage() == ExternalLinkage &&
7266 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007267 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007268 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7269 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007270 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007271 VTableUses.clear();
7272
Anders Carlsson82fccd02009-12-07 08:24:59 +00007273 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007274}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007275
Rafael Espindola5b334082010-03-26 00:36:59 +00007276void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7277 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007278 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7279 e = RD->method_end(); i != e; ++i) {
7280 CXXMethodDecl *MD = *i;
7281
7282 // C++ [basic.def.odr]p2:
7283 // [...] A virtual member function is used if it is not pure. [...]
7284 if (MD->isVirtual() && !MD->isPure())
7285 MarkDeclarationReferenced(Loc, MD);
7286 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007287
7288 // Only classes that have virtual bases need a VTT.
7289 if (RD->getNumVBases() == 0)
7290 return;
7291
7292 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7293 e = RD->bases_end(); i != e; ++i) {
7294 const CXXRecordDecl *Base =
7295 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007296 if (Base->getNumVBases() == 0)
7297 continue;
7298 MarkVirtualMembersReferenced(Loc, Base);
7299 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007300}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007301
7302/// SetIvarInitializers - This routine builds initialization ASTs for the
7303/// Objective-C implementation whose ivars need be initialized.
7304void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7305 if (!getLangOptions().CPlusPlus)
7306 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007307 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007308 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7309 CollectIvarsToConstructOrDestruct(OID, ivars);
7310 if (ivars.empty())
7311 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007312 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007313 for (unsigned i = 0; i < ivars.size(); i++) {
7314 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007315 if (Field->isInvalidDecl())
7316 continue;
7317
Alexis Hunt1d792652011-01-08 20:30:50 +00007318 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007319 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7320 InitializationKind InitKind =
7321 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7322
7323 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007324 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007325 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007326 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007327 // Note, MemberInit could actually come back empty if no initialization
7328 // is required (e.g., because it would call a trivial default constructor)
7329 if (!MemberInit.get() || MemberInit.isInvalid())
7330 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007331
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007332 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007333 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7334 SourceLocation(),
7335 MemberInit.takeAs<Expr>(),
7336 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007337 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007338
7339 // Be sure that the destructor is accessible and is marked as referenced.
7340 if (const RecordType *RecordTy
7341 = Context.getBaseElementType(Field->getType())
7342 ->getAs<RecordType>()) {
7343 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007344 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007345 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7346 CheckDestructorAccess(Field->getLocation(), Destructor,
7347 PDiag(diag::err_access_dtor_ivar)
7348 << Context.getBaseElementType(Field->getType()));
7349 }
7350 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007351 }
7352 ObjCImplementation->setIvarInitializers(Context,
7353 AllToInit.data(), AllToInit.size());
7354 }
7355}