blob: 9def74d954328d00b4fc23162672fbd718ad6046 [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.
528 if (CXXBaseDecl->isMarkedFinal()) {
529 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
536 // FIXME: Get rid of this.
Alexis Hunt96d5c762009-11-21 08:43:09 +0000537 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
538 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
539 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000540 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
541 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000542 return 0;
543 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000544
John McCall3696dcb2010-08-17 07:23:57 +0000545 if (BaseDecl->isInvalidDecl())
546 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000547
548 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000549 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000550 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000551 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000552}
553
Douglas Gregor556877c2008-04-13 21:30:24 +0000554/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
555/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000556/// example:
557/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000558/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000559BaseResult
John McCall48871652010-08-21 09:40:31 +0000560Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000561 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 ParsedType basetype, SourceLocation BaseLoc,
563 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000564 if (!classdecl)
565 return true;
566
Douglas Gregorc40290e2009-03-09 23:48:35 +0000567 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000568 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000569 if (!Class)
570 return true;
571
Nick Lewycky19b9f952010-07-26 16:56:01 +0000572 TypeSourceInfo *TInfo = 0;
573 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000574
Douglas Gregor752a5952011-01-03 22:36:02 +0000575 if (EllipsisLoc.isInvalid() &&
576 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000577 UPPC_BaseType))
578 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000579
Douglas Gregor463421d2009-03-03 04:44:36 +0000580 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000581 Virtual, Access, TInfo,
582 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000583 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000584
Douglas Gregor463421d2009-03-03 04:44:36 +0000585 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000586}
Douglas Gregor556877c2008-04-13 21:30:24 +0000587
Douglas Gregor463421d2009-03-03 04:44:36 +0000588/// \brief Performs the actual work of attaching the given base class
589/// specifiers to a C++ class.
590bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
591 unsigned NumBases) {
592 if (NumBases == 0)
593 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000594
595 // Used to keep track of which base types we have already seen, so
596 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000597 // that the key is always the unqualified canonical type of the base
598 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000599 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
600
601 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000602 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000604 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000605 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000607 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000608 if (!Class->hasObjectMember()) {
609 if (const RecordType *FDTTy =
610 NewBaseType.getTypePtr()->getAs<RecordType>())
611 if (FDTTy->getDecl()->hasObjectMember())
612 Class->setHasObjectMember(true);
613 }
614
Douglas Gregor29a92472008-10-22 17:49:05 +0000615 if (KnownBaseTypes[NewBaseType]) {
616 // C++ [class.mi]p3:
617 // A class shall not be specified as a direct base class of a
618 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000619 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000620 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000621 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000623
624 // Delete the duplicate base class specifier; we're going to
625 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000626 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000627
628 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000629 } else {
630 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 KnownBaseTypes[NewBaseType] = Bases[idx];
632 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000633 }
634 }
635
636 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000637 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000638
639 // Delete the remaining (good) base class specifiers, since their
640 // data has been copied into the CXXRecordDecl.
641 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000642 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000643
644 return Invalid;
645}
646
647/// ActOnBaseSpecifiers - Attach the given base specifiers to the
648/// class, after checking whether there are any duplicate base
649/// classes.
John McCall48871652010-08-21 09:40:31 +0000650void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000651 unsigned NumBases) {
652 if (!ClassDecl || !Bases || !NumBases)
653 return;
654
655 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000656 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000658}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000659
John McCalle78aac42010-03-10 03:28:59 +0000660static CXXRecordDecl *GetClassForType(QualType T) {
661 if (const RecordType *RT = T->getAs<RecordType>())
662 return cast<CXXRecordDecl>(RT->getDecl());
663 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
664 return ICT->getDecl();
665 else
666 return 0;
667}
668
Douglas Gregor36d1b142009-10-06 17:59:45 +0000669/// \brief Determine whether the type \p Derived is a C++ class that is
670/// derived from the type \p Base.
671bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
672 if (!getLangOptions().CPlusPlus)
673 return false;
John McCalle78aac42010-03-10 03:28:59 +0000674
675 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
676 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000677 return false;
678
John McCalle78aac42010-03-10 03:28:59 +0000679 CXXRecordDecl *BaseRD = GetClassForType(Base);
680 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000681 return false;
682
John McCall67da35c2010-02-04 22:26:26 +0000683 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
684 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000685}
686
687/// \brief Determine whether the type \p Derived is a C++ class that is
688/// derived from the type \p Base.
689bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
690 if (!getLangOptions().CPlusPlus)
691 return false;
692
John McCalle78aac42010-03-10 03:28:59 +0000693 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
694 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000695 return false;
696
John McCalle78aac42010-03-10 03:28:59 +0000697 CXXRecordDecl *BaseRD = GetClassForType(Base);
698 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000699 return false;
700
Douglas Gregor36d1b142009-10-06 17:59:45 +0000701 return DerivedRD->isDerivedFrom(BaseRD, Paths);
702}
703
Anders Carlssona70cff62010-04-24 19:06:50 +0000704void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000705 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000706 assert(BasePathArray.empty() && "Base path array must be empty!");
707 assert(Paths.isRecordingPaths() && "Must record paths!");
708
709 const CXXBasePath &Path = Paths.front();
710
711 // We first go backward and check if we have a virtual base.
712 // FIXME: It would be better if CXXBasePath had the base specifier for
713 // the nearest virtual base.
714 unsigned Start = 0;
715 for (unsigned I = Path.size(); I != 0; --I) {
716 if (Path[I - 1].Base->isVirtual()) {
717 Start = I - 1;
718 break;
719 }
720 }
721
722 // Now add all bases.
723 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000724 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000725}
726
Douglas Gregor88d292c2010-05-13 16:44:06 +0000727/// \brief Determine whether the given base path includes a virtual
728/// base class.
John McCallcf142162010-08-07 06:22:56 +0000729bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
730 for (CXXCastPath::const_iterator B = BasePath.begin(),
731 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000732 B != BEnd; ++B)
733 if ((*B)->isVirtual())
734 return true;
735
736 return false;
737}
738
Douglas Gregor36d1b142009-10-06 17:59:45 +0000739/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
740/// conversion (where Derived and Base are class types) is
741/// well-formed, meaning that the conversion is unambiguous (and
742/// that all of the base classes are accessible). Returns true
743/// and emits a diagnostic if the code is ill-formed, returns false
744/// otherwise. Loc is the location where this routine should point to
745/// if there is an error, and Range is the source range to highlight
746/// if there is an error.
747bool
748Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000749 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000750 unsigned AmbigiousBaseConvID,
751 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000752 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000753 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000754 // First, determine whether the path from Derived to Base is
755 // ambiguous. This is slightly more expensive than checking whether
756 // the Derived to Base conversion exists, because here we need to
757 // explore multiple paths to determine if there is an ambiguity.
758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
759 /*DetectVirtual=*/false);
760 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
761 assert(DerivationOkay &&
762 "Can only be used with a derived-to-base conversion");
763 (void)DerivationOkay;
764
765 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000766 if (InaccessibleBaseID) {
767 // Check that the base class can be accessed.
768 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
769 InaccessibleBaseID)) {
770 case AR_inaccessible:
771 return true;
772 case AR_accessible:
773 case AR_dependent:
774 case AR_delayed:
775 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000776 }
John McCall5b0829a2010-02-10 09:31:12 +0000777 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000778
779 // Build a base path if necessary.
780 if (BasePath)
781 BuildBasePathArray(Paths, *BasePath);
782 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000783 }
784
785 // We know that the derived-to-base conversion is ambiguous, and
786 // we're going to produce a diagnostic. Perform the derived-to-base
787 // search just one more time to compute all of the possible paths so
788 // that we can print them out. This is more expensive than any of
789 // the previous derived-to-base checks we've done, but at this point
790 // performance isn't as much of an issue.
791 Paths.clear();
792 Paths.setRecordingPaths(true);
793 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
794 assert(StillOkay && "Can only be used with a derived-to-base conversion");
795 (void)StillOkay;
796
797 // Build up a textual representation of the ambiguous paths, e.g.,
798 // D -> B -> A, that will be used to illustrate the ambiguous
799 // conversions in the diagnostic. We only print one of the paths
800 // to each base class subobject.
801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
802
803 Diag(Loc, AmbigiousBaseConvID)
804 << Derived << Base << PathDisplayStr << Range << Name;
805 return true;
806}
807
808bool
809Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000810 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000811 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000812 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000813 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000814 IgnoreAccess ? 0
815 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000816 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000817 Loc, Range, DeclarationName(),
818 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000819}
820
821
822/// @brief Builds a string representing ambiguous paths from a
823/// specific derived class to different subobjects of the same base
824/// class.
825///
826/// This function builds a string that can be used in error messages
827/// to show the different paths that one can take through the
828/// inheritance hierarchy to go from the derived class to different
829/// subobjects of a base class. The result looks something like this:
830/// @code
831/// struct D -> struct B -> struct A
832/// struct D -> struct C -> struct A
833/// @endcode
834std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
835 std::string PathDisplayStr;
836 std::set<unsigned> DisplayedPaths;
837 for (CXXBasePaths::paths_iterator Path = Paths.begin();
838 Path != Paths.end(); ++Path) {
839 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
840 // We haven't displayed a path to this particular base
841 // class subobject yet.
842 PathDisplayStr += "\n ";
843 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
844 for (CXXBasePath::const_iterator Element = Path->begin();
845 Element != Path->end(); ++Element)
846 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
847 }
848 }
849
850 return PathDisplayStr;
851}
852
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853//===----------------------------------------------------------------------===//
854// C++ class member Handling
855//===----------------------------------------------------------------------===//
856
Abramo Bagnarad7340582010-06-05 05:09:32 +0000857/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000858Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
859 SourceLocation ASLoc,
860 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000861 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000862 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000863 ASLoc, ColonLoc);
864 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000865 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000866}
867
Anders Carlssonfd835532011-01-20 05:57:14 +0000868/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000869void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000870 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
871 if (!MD || !MD->isVirtual())
872 return;
873
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000874 if (MD->isDependentContext())
875 return;
876
Anders Carlssonfd835532011-01-20 05:57:14 +0000877 // C++0x [class.virtual]p3:
878 // If a virtual function is marked with the virt-specifier override and does
879 // not override a member function of a base class,
880 // the program is ill-formed.
881 bool HasOverriddenMethods =
882 MD->begin_overridden_methods() != MD->end_overridden_methods();
883 if (MD->isMarkedOverride() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000884 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000885 diag::err_function_marked_override_not_overriding)
886 << MD->getDeclName();
887 return;
888 }
Anders Carlsson7d59a682011-01-22 22:23:37 +0000889
890 // C++0x [class.derived]p8:
891 // In a class definition marked with the class-virt-specifier explicit,
892 // if a virtual member function that is neither implicitly-declared nor a
893 // destructor overrides a member function of a base class and it is not
894 // marked with the virt-specifier override, the program is ill-formed.
895 if (MD->getParent()->isMarkedExplicit() && !isa<CXXDestructorDecl>(MD) &&
896 HasOverriddenMethods && !MD->isMarkedOverride()) {
897 llvm::SmallVector<const CXXMethodDecl*, 4>
898 OverriddenMethods(MD->begin_overridden_methods(),
899 MD->end_overridden_methods());
900
901 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
902 << MD->getDeclName()
903 << (unsigned)OverriddenMethods.size();
904
905 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
906 Diag(OverriddenMethods[I]->getLocation(),
907 diag::note_overridden_virtual_function);
908 }
Anders Carlssonfd835532011-01-20 05:57:14 +0000909}
910
Anders Carlsson3f610c72011-01-20 16:25:36 +0000911/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
912/// function overrides a virtual member function marked 'final', according to
913/// C++0x [class.virtual]p3.
914bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
915 const CXXMethodDecl *Old) {
916 // FIXME: Get rid of FinalAttr here.
917 if (Old->hasAttr<FinalAttr>() || Old->isMarkedFinal()) {
918 Diag(New->getLocation(), diag::err_final_function_overridden)
919 << New->getDeclName();
920 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
921 return true;
922 }
923
924 return false;
925}
926
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000927/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
928/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
929/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000930/// any.
John McCall48871652010-08-21 09:40:31 +0000931Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000932Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000933 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000934 ExprTy *BW, const VirtSpecifiers &VS,
935 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000936 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
939 DeclarationName Name = NameInfo.getName();
940 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000941
942 // For anonymous bitfields, the location should point to the type.
943 if (Loc.isInvalid())
944 Loc = D.getSourceRange().getBegin();
945
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946 Expr *BitWidth = static_cast<Expr*>(BW);
947 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000948
John McCallb1cd7da2010-06-04 08:34:12 +0000949 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000950 assert(!DS.isFriendSpecified());
951
John McCallb1cd7da2010-06-04 08:34:12 +0000952 bool isFunc = false;
953 if (D.isFunctionDeclarator())
954 isFunc = true;
955 else if (D.getNumTypeObjects() == 0 &&
956 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000957 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000958 isFunc = TDType->isFunctionType();
959 }
960
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000961 // C++ 9.2p6: A member shall not be declared to have automatic storage
962 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000963 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
964 // data members and cannot be applied to names declared const or static,
965 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000966 switch (DS.getStorageClassSpec()) {
967 case DeclSpec::SCS_unspecified:
968 case DeclSpec::SCS_typedef:
969 case DeclSpec::SCS_static:
970 // FALL THROUGH.
971 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000972 case DeclSpec::SCS_mutable:
973 if (isFunc) {
974 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000975 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000976 else
Chris Lattner3b054132008-11-19 05:08:23 +0000977 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000978
Sebastian Redl8071edb2008-11-17 23:24:37 +0000979 // FIXME: It would be nicer if the keyword was ignored only for this
980 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000981 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000982 }
983 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000984 default:
985 if (DS.getStorageClassSpecLoc().isValid())
986 Diag(DS.getStorageClassSpecLoc(),
987 diag::err_storageclass_invalid_for_member);
988 else
989 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
990 D.getMutableDeclSpec().ClearStorageClassSpecs();
991 }
992
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000993 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
994 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000995 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000996
997 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000998 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000999 CXXScopeSpec &SS = D.getCXXScopeSpec();
1000
1001
1002 if (SS.isSet() && !SS.isInvalid()) {
1003 // The user provided a superfluous scope specifier inside a class
1004 // definition:
1005 //
1006 // class X {
1007 // int X::member;
1008 // };
1009 DeclContext *DC = 0;
1010 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1011 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1012 << Name << FixItHint::CreateRemoval(SS.getRange());
1013 else
1014 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1015 << Name << SS.getRange();
1016
1017 SS.clear();
1018 }
1019
Douglas Gregor3447e762009-08-20 22:52:58 +00001020 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001021 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001022 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1023 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001024 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001025 } else {
John McCall48871652010-08-21 09:40:31 +00001026 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001027 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001028 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001029 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001030
1031 // Non-instance-fields can't have a bitfield.
1032 if (BitWidth) {
1033 if (Member->isInvalidDecl()) {
1034 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001035 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001036 // C++ 9.6p3: A bit-field shall not be a static member.
1037 // "static member 'A' cannot be a bit-field"
1038 Diag(Loc, diag::err_static_not_bitfield)
1039 << Name << BitWidth->getSourceRange();
1040 } else if (isa<TypedefDecl>(Member)) {
1041 // "typedef member 'x' cannot be a bit-field"
1042 Diag(Loc, diag::err_typedef_not_bitfield)
1043 << Name << BitWidth->getSourceRange();
1044 } else {
1045 // A function typedef ("typedef int f(); f a;").
1046 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1047 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001048 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001049 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattnerd26760a2009-03-05 23:01:03 +00001052 BitWidth = 0;
1053 Member->setInvalidDecl();
1054 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001055
1056 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Douglas Gregor3447e762009-08-20 22:52:58 +00001058 // If we have declared a member function template, set the access of the
1059 // templated declaration as well.
1060 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1061 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001062 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001063
Anders Carlsson13a69102011-01-20 04:34:22 +00001064 if (VS.isOverrideSpecified()) {
1065 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1066 if (!MD || !MD->isVirtual()) {
1067 Diag(Member->getLocStart(),
1068 diag::override_keyword_only_allowed_on_virtual_member_functions)
1069 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001070 } else
1071 MD->setIsMarkedOverride(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001072 }
1073 if (VS.isFinalSpecified()) {
1074 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1075 if (!MD || !MD->isVirtual()) {
1076 Diag(Member->getLocStart(),
1077 diag::override_keyword_only_allowed_on_virtual_member_functions)
1078 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001079 } else
1080 MD->setIsMarkedFinal(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001081 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001082
Anders Carlssonc87f8612011-01-20 06:29:02 +00001083 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001084
Douglas Gregor92751d42008-11-17 22:58:34 +00001085 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001086
Douglas Gregor0c880302009-03-11 23:00:04 +00001087 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001088 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001089 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001090 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001091
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001092 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001093 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001094 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001095 }
John McCall48871652010-08-21 09:40:31 +00001096 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001097}
1098
Douglas Gregor15e77a22009-12-31 09:10:24 +00001099/// \brief Find the direct and/or virtual base specifiers that
1100/// correspond to the given base type, for use in base initialization
1101/// within a constructor.
1102static bool FindBaseInitializer(Sema &SemaRef,
1103 CXXRecordDecl *ClassDecl,
1104 QualType BaseType,
1105 const CXXBaseSpecifier *&DirectBaseSpec,
1106 const CXXBaseSpecifier *&VirtualBaseSpec) {
1107 // First, check for a direct base class.
1108 DirectBaseSpec = 0;
1109 for (CXXRecordDecl::base_class_const_iterator Base
1110 = ClassDecl->bases_begin();
1111 Base != ClassDecl->bases_end(); ++Base) {
1112 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1113 // We found a direct base of this type. That's what we're
1114 // initializing.
1115 DirectBaseSpec = &*Base;
1116 break;
1117 }
1118 }
1119
1120 // Check for a virtual base class.
1121 // FIXME: We might be able to short-circuit this if we know in advance that
1122 // there are no virtual bases.
1123 VirtualBaseSpec = 0;
1124 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1125 // We haven't found a base yet; search the class hierarchy for a
1126 // virtual base class.
1127 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1128 /*DetectVirtual=*/false);
1129 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1130 BaseType, Paths)) {
1131 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1132 Path != Paths.end(); ++Path) {
1133 if (Path->back().Base->isVirtual()) {
1134 VirtualBaseSpec = Path->back().Base;
1135 break;
1136 }
1137 }
1138 }
1139 }
1140
1141 return DirectBaseSpec || VirtualBaseSpec;
1142}
1143
Douglas Gregore8381c02008-11-05 04:29:56 +00001144/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001145MemInitResult
John McCall48871652010-08-21 09:40:31 +00001146Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001147 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001148 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001149 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001150 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001151 SourceLocation IdLoc,
1152 SourceLocation LParenLoc,
1153 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001154 SourceLocation RParenLoc,
1155 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001156 if (!ConstructorD)
1157 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001158
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001159 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001160
1161 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001162 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001163 if (!Constructor) {
1164 // The user wrote a constructor initializer on a function that is
1165 // not a C++ constructor. Ignore the error for now, because we may
1166 // have more member initializers coming; we'll diagnose it just
1167 // once in ActOnMemInitializers.
1168 return true;
1169 }
1170
1171 CXXRecordDecl *ClassDecl = Constructor->getParent();
1172
1173 // C++ [class.base.init]p2:
1174 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001175 // constructor's class and, if not found in that scope, are looked
1176 // up in the scope containing the constructor's definition.
1177 // [Note: if the constructor's class contains a member with the
1178 // same name as a direct or virtual base class of the class, a
1179 // mem-initializer-id naming the member or base class and composed
1180 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001181 // mem-initializer-id for the hidden base class may be specified
1182 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001183 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001184 // Look for a member, first.
1185 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001186 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001187 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001188 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001189 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001190
Douglas Gregor44e7df62011-01-04 00:32:56 +00001191 if (Member) {
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(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001197 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001198 }
1199
Francois Pichetd583da02010-12-04 09:14:42 +00001200 // Handle anonymous union case.
1201 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001202 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1203 if (EllipsisLoc.isValid())
1204 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1205 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1206
Francois Pichetd583da02010-12-04 09:14:42 +00001207 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1208 NumArgs, IdLoc,
1209 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001210 }
Francois Pichetd583da02010-12-04 09:14:42 +00001211 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001212 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001213 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001214 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001215 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001216
1217 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001218 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001219 } else {
1220 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1221 LookupParsedName(R, S, &SS);
1222
1223 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1224 if (!TyD) {
1225 if (R.isAmbiguous()) return true;
1226
John McCallda6841b2010-04-09 19:01:14 +00001227 // We don't want access-control diagnostics here.
1228 R.suppressDiagnostics();
1229
Douglas Gregora3b624a2010-01-19 06:46:48 +00001230 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1231 bool NotUnknownSpecialization = false;
1232 DeclContext *DC = computeDeclContext(SS, false);
1233 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1234 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1235
1236 if (!NotUnknownSpecialization) {
1237 // When the scope specifier can refer to a member of an unknown
1238 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001239 BaseType = CheckTypenameType(ETK_None,
1240 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001241 *MemberOrBase, SourceLocation(),
1242 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001243 if (BaseType.isNull())
1244 return true;
1245
Douglas Gregora3b624a2010-01-19 06:46:48 +00001246 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001247 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001248 }
1249 }
1250
Douglas Gregor15e77a22009-12-31 09:10:24 +00001251 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001252 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001253 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1254 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001255 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001256 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001257 // We have found a non-static data member with a similar
1258 // name to what was typed; complain and initialize that
1259 // member.
1260 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1261 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001262 << FixItHint::CreateReplacement(R.getNameLoc(),
1263 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001264 Diag(Member->getLocation(), diag::note_previous_decl)
1265 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001266
1267 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1268 LParenLoc, RParenLoc);
1269 }
1270 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1271 const CXXBaseSpecifier *DirectBaseSpec;
1272 const CXXBaseSpecifier *VirtualBaseSpec;
1273 if (FindBaseInitializer(*this, ClassDecl,
1274 Context.getTypeDeclType(Type),
1275 DirectBaseSpec, VirtualBaseSpec)) {
1276 // We have found a direct or virtual base class with a
1277 // similar name to what was typed; complain and initialize
1278 // that base class.
1279 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1280 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001281 << FixItHint::CreateReplacement(R.getNameLoc(),
1282 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001283
1284 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1285 : VirtualBaseSpec;
1286 Diag(BaseSpec->getSourceRange().getBegin(),
1287 diag::note_base_class_specified_here)
1288 << BaseSpec->getType()
1289 << BaseSpec->getSourceRange();
1290
Douglas Gregor15e77a22009-12-31 09:10:24 +00001291 TyD = Type;
1292 }
1293 }
1294 }
1295
Douglas Gregora3b624a2010-01-19 06:46:48 +00001296 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001297 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1298 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1299 return true;
1300 }
John McCallb5a0d312009-12-21 10:41:20 +00001301 }
1302
Douglas Gregora3b624a2010-01-19 06:46:48 +00001303 if (BaseType.isNull()) {
1304 BaseType = Context.getTypeDeclType(TyD);
1305 if (SS.isSet()) {
1306 NestedNameSpecifier *Qualifier =
1307 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001308
Douglas Gregora3b624a2010-01-19 06:46:48 +00001309 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001310 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001311 }
John McCallb5a0d312009-12-21 10:41:20 +00001312 }
1313 }
Mike Stump11289f42009-09-09 15:08:12 +00001314
John McCallbcd03502009-12-07 02:54:59 +00001315 if (!TInfo)
1316 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001317
John McCallbcd03502009-12-07 02:54:59 +00001318 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001319 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001320}
1321
John McCalle22a04a2009-11-04 23:02:40 +00001322/// Checks an initializer expression for use of uninitialized fields, such as
1323/// containing the field that is being initialized. Returns true if there is an
1324/// uninitialized field was used an updates the SourceLocation parameter; false
1325/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001326static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001327 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001328 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001329 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1330
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001331 if (isa<CallExpr>(S)) {
1332 // Do not descend into function calls or constructors, as the use
1333 // of an uninitialized field may be valid. One would have to inspect
1334 // the contents of the function/ctor to determine if it is safe or not.
1335 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1336 // may be safe, depending on what the function/ctor does.
1337 return false;
1338 }
1339 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1340 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001341
1342 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1343 // The member expression points to a static data member.
1344 assert(VD->isStaticDataMember() &&
1345 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001346 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001347 return false;
1348 }
1349
1350 if (isa<EnumConstantDecl>(RhsField)) {
1351 // The member expression points to an enum.
1352 return false;
1353 }
1354
John McCalle22a04a2009-11-04 23:02:40 +00001355 if (RhsField == LhsField) {
1356 // Initializing a field with itself. Throw a warning.
1357 // But wait; there are exceptions!
1358 // Exception #1: The field may not belong to this record.
1359 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001360 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001361 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1362 // Even though the field matches, it does not belong to this record.
1363 return false;
1364 }
1365 // None of the exceptions triggered; return true to indicate an
1366 // uninitialized field was used.
1367 *L = ME->getMemberLoc();
1368 return true;
1369 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001370 } else if (isa<SizeOfAlignOfExpr>(S)) {
1371 // sizeof/alignof doesn't reference contents, do not warn.
1372 return false;
1373 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1374 // address-of doesn't reference contents (the pointer may be dereferenced
1375 // in the same expression but it would be rare; and weird).
1376 if (UOE->getOpcode() == UO_AddrOf)
1377 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001378 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001379 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1380 it != e; ++it) {
1381 if (!*it) {
1382 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001383 continue;
1384 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001385 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1386 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001387 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001388 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001389}
1390
John McCallfaf5fb42010-08-26 23:41:50 +00001391MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001392Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001393 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001394 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001395 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001396 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1397 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1398 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001399 "Member must be a FieldDecl or IndirectFieldDecl");
1400
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001401 if (Member->isInvalidDecl())
1402 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001403
John McCalle22a04a2009-11-04 23:02:40 +00001404 // Diagnose value-uses of fields to initialize themselves, e.g.
1405 // foo(foo)
1406 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001407 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001408 for (unsigned i = 0; i < NumArgs; ++i) {
1409 SourceLocation L;
1410 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1411 // FIXME: Return true in the case when other fields are used before being
1412 // uninitialized. For example, let this field be the i'th field. When
1413 // initializing the i'th field, throw a warning if any of the >= i'th
1414 // fields are used, as they are not yet initialized.
1415 // Right now we are only handling the case where the i'th field uses
1416 // itself in its initializer.
1417 Diag(L, diag::warn_field_is_uninit);
1418 }
1419 }
1420
Eli Friedman8e1433b2009-07-29 19:44:27 +00001421 bool HasDependentArg = false;
1422 for (unsigned i = 0; i < NumArgs; i++)
1423 HasDependentArg |= Args[i]->isTypeDependent();
1424
Chandler Carruthd44c3102010-12-06 09:23:57 +00001425 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001426 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001427 // Can't check initialization for a member of dependent type or when
1428 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001429 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1430 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001431
1432 // Erase any temporaries within this evaluation context; we're not
1433 // going to track them in the AST, since we'll be rebuilding the
1434 // ASTs during template instantiation.
1435 ExprTemporaries.erase(
1436 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1437 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001438 } else {
1439 // Initialize the member.
1440 InitializedEntity MemberEntity =
1441 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1442 : InitializedEntity::InitializeMember(IndirectMember, 0);
1443 InitializationKind Kind =
1444 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001445
Chandler Carruthd44c3102010-12-06 09:23:57 +00001446 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1447
1448 ExprResult MemberInit =
1449 InitSeq.Perform(*this, MemberEntity, Kind,
1450 MultiExprArg(*this, Args, NumArgs), 0);
1451 if (MemberInit.isInvalid())
1452 return true;
1453
1454 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1455
1456 // C++0x [class.base.init]p7:
1457 // The initialization of each base and member constitutes a
1458 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001459 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001460 if (MemberInit.isInvalid())
1461 return true;
1462
1463 // If we are in a dependent context, template instantiation will
1464 // perform this type-checking again. Just save the arguments that we
1465 // received in a ParenListExpr.
1466 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1467 // of the information that we have about the member
1468 // initializer. However, deconstructing the ASTs is a dicey process,
1469 // and this approach is far more likely to get the corner cases right.
1470 if (CurContext->isDependentContext())
1471 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1472 RParenLoc);
1473 else
1474 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001475 }
1476
Chandler Carruthd44c3102010-12-06 09:23:57 +00001477 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001478 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001479 IdLoc, LParenLoc, Init,
1480 RParenLoc);
1481 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001482 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001483 IdLoc, LParenLoc, Init,
1484 RParenLoc);
1485 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001486}
1487
John McCallfaf5fb42010-08-26 23:41:50 +00001488MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001489Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1490 Expr **Args, unsigned NumArgs,
1491 SourceLocation LParenLoc,
1492 SourceLocation RParenLoc,
1493 CXXRecordDecl *ClassDecl,
1494 SourceLocation EllipsisLoc) {
1495 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1496 if (!LangOpts.CPlusPlus0x)
1497 return Diag(Loc, diag::err_delegation_0x_only)
1498 << TInfo->getTypeLoc().getLocalSourceRange();
1499
1500 return Diag(Loc, diag::err_delegation_unimplemented)
1501 << TInfo->getTypeLoc().getLocalSourceRange();
1502}
1503
1504MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001505Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001506 Expr **Args, unsigned NumArgs,
1507 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001508 CXXRecordDecl *ClassDecl,
1509 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001510 bool HasDependentArg = false;
1511 for (unsigned i = 0; i < NumArgs; i++)
1512 HasDependentArg |= Args[i]->isTypeDependent();
1513
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001514 SourceLocation BaseLoc
1515 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1516
1517 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1518 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1519 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1520
1521 // C++ [class.base.init]p2:
1522 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001523 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001524 // of that class, the mem-initializer is ill-formed. A
1525 // mem-initializer-list can initialize a base class using any
1526 // name that denotes that base class type.
1527 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1528
Douglas Gregor44e7df62011-01-04 00:32:56 +00001529 if (EllipsisLoc.isValid()) {
1530 // This is a pack expansion.
1531 if (!BaseType->containsUnexpandedParameterPack()) {
1532 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1533 << SourceRange(BaseLoc, RParenLoc);
1534
1535 EllipsisLoc = SourceLocation();
1536 }
1537 } else {
1538 // Check for any unexpanded parameter packs.
1539 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1540 return true;
1541
1542 for (unsigned I = 0; I != NumArgs; ++I)
1543 if (DiagnoseUnexpandedParameterPack(Args[I]))
1544 return true;
1545 }
1546
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001547 // Check for direct and virtual base classes.
1548 const CXXBaseSpecifier *DirectBaseSpec = 0;
1549 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1550 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001551 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1552 BaseType))
1553 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1554 LParenLoc, RParenLoc, ClassDecl,
1555 EllipsisLoc);
1556
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001557 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1558 VirtualBaseSpec);
1559
1560 // C++ [base.class.init]p2:
1561 // Unless the mem-initializer-id names a nonstatic data member of the
1562 // constructor's class or a direct or virtual base of that class, the
1563 // mem-initializer is ill-formed.
1564 if (!DirectBaseSpec && !VirtualBaseSpec) {
1565 // If the class has any dependent bases, then it's possible that
1566 // one of those types will resolve to the same type as
1567 // BaseType. Therefore, just treat this as a dependent base
1568 // class initialization. FIXME: Should we try to check the
1569 // initialization anyway? It seems odd.
1570 if (ClassDecl->hasAnyDependentBases())
1571 Dependent = true;
1572 else
1573 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1574 << BaseType << Context.getTypeDeclType(ClassDecl)
1575 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1576 }
1577 }
1578
1579 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001580 // Can't check initialization for a base of dependent type or when
1581 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001582 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001583 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1584 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001585
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001586 // Erase any temporaries within this evaluation context; we're not
1587 // going to track them in the AST, since we'll be rebuilding the
1588 // ASTs during template instantiation.
1589 ExprTemporaries.erase(
1590 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1591 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001592
Alexis Hunt1d792652011-01-08 20:30:50 +00001593 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001594 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001595 LParenLoc,
1596 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001597 RParenLoc,
1598 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001599 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001600
1601 // C++ [base.class.init]p2:
1602 // If a mem-initializer-id is ambiguous because it designates both
1603 // a direct non-virtual base class and an inherited virtual base
1604 // class, the mem-initializer is ill-formed.
1605 if (DirectBaseSpec && VirtualBaseSpec)
1606 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001607 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001608
1609 CXXBaseSpecifier *BaseSpec
1610 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1611 if (!BaseSpec)
1612 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1613
1614 // Initialize the base.
1615 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001616 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001617 InitializationKind Kind =
1618 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1619
1620 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1621
John McCalldadc5752010-08-24 06:29:42 +00001622 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001623 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001624 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001625 if (BaseInit.isInvalid())
1626 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001627
1628 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001629
1630 // C++0x [class.base.init]p7:
1631 // The initialization of each base and member constitutes a
1632 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001633 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001634 if (BaseInit.isInvalid())
1635 return true;
1636
1637 // If we are in a dependent context, template instantiation will
1638 // perform this type-checking again. Just save the arguments that we
1639 // received in a ParenListExpr.
1640 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1641 // of the information that we have about the base
1642 // initializer. However, deconstructing the ASTs is a dicey process,
1643 // and this approach is far more likely to get the corner cases right.
1644 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001645 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001646 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1647 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001648 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001649 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001650 LParenLoc,
1651 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001652 RParenLoc,
1653 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001654 }
1655
Alexis Hunt1d792652011-01-08 20:30:50 +00001656 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001657 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001658 LParenLoc,
1659 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001660 RParenLoc,
1661 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001662}
1663
Anders Carlsson1b00e242010-04-23 03:10:23 +00001664/// ImplicitInitializerKind - How an implicit base or member initializer should
1665/// initialize its base or member.
1666enum ImplicitInitializerKind {
1667 IIK_Default,
1668 IIK_Copy,
1669 IIK_Move
1670};
1671
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001672static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001673BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001674 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001675 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001676 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001677 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001678 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001679 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1680 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001681
John McCalldadc5752010-08-24 06:29:42 +00001682 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001683
1684 switch (ImplicitInitKind) {
1685 case IIK_Default: {
1686 InitializationKind InitKind
1687 = InitializationKind::CreateDefault(Constructor->getLocation());
1688 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1689 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001690 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001691 break;
1692 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001693
Anders Carlsson1b00e242010-04-23 03:10:23 +00001694 case IIK_Copy: {
1695 ParmVarDecl *Param = Constructor->getParamDecl(0);
1696 QualType ParamType = Param->getType().getNonReferenceType();
1697
1698 Expr *CopyCtorArg =
1699 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001700 Constructor->getLocation(), ParamType,
1701 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001702
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001703 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001704 QualType ArgTy =
1705 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1706 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001707
1708 CXXCastPath BasePath;
1709 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001710 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001711 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001712 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001713
Anders Carlsson1b00e242010-04-23 03:10:23 +00001714 InitializationKind InitKind
1715 = InitializationKind::CreateDirect(Constructor->getLocation(),
1716 SourceLocation(), SourceLocation());
1717 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1718 &CopyCtorArg, 1);
1719 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001720 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001721 break;
1722 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001723
Anders Carlsson1b00e242010-04-23 03:10:23 +00001724 case IIK_Move:
1725 assert(false && "Unhandled initializer kind!");
1726 }
John McCallb268a282010-08-23 23:25:46 +00001727
Douglas Gregora40433a2010-12-07 00:41:46 +00001728 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001729 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001730 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001731
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001732 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001733 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001734 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1735 SourceLocation()),
1736 BaseSpec->isVirtual(),
1737 SourceLocation(),
1738 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001739 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001740 SourceLocation());
1741
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001742 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001743}
1744
Anders Carlsson3c1db572010-04-23 02:15:47 +00001745static bool
1746BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001747 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001748 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001749 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001750 if (Field->isInvalidDecl())
1751 return true;
1752
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001753 SourceLocation Loc = Constructor->getLocation();
1754
Anders Carlsson423f5d82010-04-23 16:04:08 +00001755 if (ImplicitInitKind == IIK_Copy) {
1756 ParmVarDecl *Param = Constructor->getParamDecl(0);
1757 QualType ParamType = Param->getType().getNonReferenceType();
1758
1759 Expr *MemberExprBase =
1760 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001761 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001762
1763 // Build a reference to this field within the parameter.
1764 CXXScopeSpec SS;
1765 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1766 Sema::LookupMemberName);
1767 MemberLookup.addDecl(Field, AS_public);
1768 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001769 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001770 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001771 ParamType, Loc,
1772 /*IsArrow=*/false,
1773 SS,
1774 /*FirstQualifierInScope=*/0,
1775 MemberLookup,
1776 /*TemplateArgs=*/0);
1777 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001778 return true;
1779
Douglas Gregor94f9a482010-05-05 05:51:00 +00001780 // When the field we are copying is an array, create index variables for
1781 // each dimension of the array. We use these index variables to subscript
1782 // the source array, and other clients (e.g., CodeGen) will perform the
1783 // necessary iteration with these index variables.
1784 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1785 QualType BaseType = Field->getType();
1786 QualType SizeType = SemaRef.Context.getSizeType();
1787 while (const ConstantArrayType *Array
1788 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1789 // Create the iteration variable for this array index.
1790 IdentifierInfo *IterationVarName = 0;
1791 {
1792 llvm::SmallString<8> Str;
1793 llvm::raw_svector_ostream OS(Str);
1794 OS << "__i" << IndexVariables.size();
1795 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1796 }
1797 VarDecl *IterationVar
1798 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1799 IterationVarName, SizeType,
1800 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001801 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001802 IndexVariables.push_back(IterationVar);
1803
1804 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001805 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001806 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001807 assert(!IterationVarRef.isInvalid() &&
1808 "Reference to invented variable cannot fail!");
1809
1810 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001811 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001812 Loc,
John McCallb268a282010-08-23 23:25:46 +00001813 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001814 Loc);
1815 if (CopyCtorArg.isInvalid())
1816 return true;
1817
1818 BaseType = Array->getElementType();
1819 }
1820
1821 // Construct the entity that we will be initializing. For an array, this
1822 // will be first element in the array, which may require several levels
1823 // of array-subscript entities.
1824 llvm::SmallVector<InitializedEntity, 4> Entities;
1825 Entities.reserve(1 + IndexVariables.size());
1826 Entities.push_back(InitializedEntity::InitializeMember(Field));
1827 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1828 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1829 0,
1830 Entities.back()));
1831
1832 // Direct-initialize to use the copy constructor.
1833 InitializationKind InitKind =
1834 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1835
1836 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1837 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1838 &CopyCtorArgE, 1);
1839
John McCalldadc5752010-08-24 06:29:42 +00001840 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001841 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001842 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001843 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001844 if (MemberInit.isInvalid())
1845 return true;
1846
1847 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001848 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001849 MemberInit.takeAs<Expr>(), Loc,
1850 IndexVariables.data(),
1851 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001852 return false;
1853 }
1854
Anders Carlsson423f5d82010-04-23 16:04:08 +00001855 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1856
Anders Carlsson3c1db572010-04-23 02:15:47 +00001857 QualType FieldBaseElementType =
1858 SemaRef.Context.getBaseElementType(Field->getType());
1859
Anders Carlsson3c1db572010-04-23 02:15:47 +00001860 if (FieldBaseElementType->isRecordType()) {
1861 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001862 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001863 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001864
1865 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001866 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001867 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001868
Douglas Gregora40433a2010-12-07 00:41:46 +00001869 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001870 if (MemberInit.isInvalid())
1871 return true;
1872
1873 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001874 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001875 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001876 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001877 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001878 return false;
1879 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001880
1881 if (FieldBaseElementType->isReferenceType()) {
1882 SemaRef.Diag(Constructor->getLocation(),
1883 diag::err_uninitialized_member_in_ctor)
1884 << (int)Constructor->isImplicit()
1885 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1886 << 0 << Field->getDeclName();
1887 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1888 return true;
1889 }
1890
1891 if (FieldBaseElementType.isConstQualified()) {
1892 SemaRef.Diag(Constructor->getLocation(),
1893 diag::err_uninitialized_member_in_ctor)
1894 << (int)Constructor->isImplicit()
1895 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1896 << 1 << Field->getDeclName();
1897 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1898 return true;
1899 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001900
1901 // Nothing to initialize.
1902 CXXMemberInit = 0;
1903 return false;
1904}
John McCallbc83b3f2010-05-20 23:23:51 +00001905
1906namespace {
1907struct BaseAndFieldInfo {
1908 Sema &S;
1909 CXXConstructorDecl *Ctor;
1910 bool AnyErrorsInInits;
1911 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001912 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1913 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001914
1915 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1916 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1917 // FIXME: Handle implicit move constructors.
1918 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1919 IIK = IIK_Copy;
1920 else
1921 IIK = IIK_Default;
1922 }
1923};
1924}
1925
1926static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1927 FieldDecl *Top, FieldDecl *Field) {
1928
Chandler Carruth139e9622010-06-30 02:59:29 +00001929 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001930 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001931 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001932 return false;
1933 }
1934
1935 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1936 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1937 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001938 CXXRecordDecl *FieldClassDecl
1939 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001940
1941 // Even though union members never have non-trivial default
1942 // constructions in C++03, we still build member initializers for aggregate
1943 // record types which can be union members, and C++0x allows non-trivial
1944 // default constructors for union members, so we ensure that only one
1945 // member is initialized for these.
1946 if (FieldClassDecl->isUnion()) {
1947 // First check for an explicit initializer for one field.
1948 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1949 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001950 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001951 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001952
1953 // Once we've initialized a field of an anonymous union, the union
1954 // field in the class is also initialized, so exit immediately.
1955 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001956 } else if ((*FA)->isAnonymousStructOrUnion()) {
1957 if (CollectFieldInitializer(Info, Top, *FA))
1958 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001959 }
1960 }
1961
1962 // Fallthrough and construct a default initializer for the union as
1963 // a whole, which can call its default constructor if such a thing exists
1964 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1965 // behavior going forward with C++0x, when anonymous unions there are
1966 // finalized, we should revisit this.
1967 } else {
1968 // For structs, we simply descend through to initialize all members where
1969 // necessary.
1970 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1971 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1972 if (CollectFieldInitializer(Info, Top, *FA))
1973 return true;
1974 }
1975 }
John McCallbc83b3f2010-05-20 23:23:51 +00001976 }
1977
1978 // Don't try to build an implicit initializer if there were semantic
1979 // errors in any of the initializers (and therefore we might be
1980 // missing some that the user actually wrote).
1981 if (Info.AnyErrorsInInits)
1982 return false;
1983
Alexis Hunt1d792652011-01-08 20:30:50 +00001984 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001985 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1986 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001987
Francois Pichetd583da02010-12-04 09:14:42 +00001988 if (Init)
1989 Info.AllToInit.push_back(Init);
1990
John McCallbc83b3f2010-05-20 23:23:51 +00001991 return false;
1992}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001993
Eli Friedman9cf6b592009-11-09 19:20:36 +00001994bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001995Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1996 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001997 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001998 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001999 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002000 // Just store the initializers as written, they will be checked during
2001 // instantiation.
2002 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002003 Constructor->setNumCtorInitializers(NumInitializers);
2004 CXXCtorInitializer **baseOrMemberInitializers =
2005 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002006 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002007 NumInitializers * sizeof(CXXCtorInitializer*));
2008 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002009 }
2010
2011 return false;
2012 }
2013
John McCallbc83b3f2010-05-20 23:23:51 +00002014 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002015
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002016 // We need to build the initializer AST according to order of construction
2017 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002018 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002019 if (!ClassDecl)
2020 return true;
2021
Eli Friedman9cf6b592009-11-09 19:20:36 +00002022 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002023
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002024 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002025 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002026
2027 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002028 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002029 else
Francois Pichetd583da02010-12-04 09:14:42 +00002030 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002031 }
2032
Anders Carlsson43c64af2010-04-21 19:52:01 +00002033 // Keep track of the direct virtual bases.
2034 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2035 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2036 E = ClassDecl->bases_end(); I != E; ++I) {
2037 if (I->isVirtual())
2038 DirectVBases.insert(I);
2039 }
2040
Anders Carlssondb0a9652010-04-02 06:26:44 +00002041 // Push virtual bases before others.
2042 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2043 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2044
Alexis Hunt1d792652011-01-08 20:30:50 +00002045 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002046 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2047 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002048 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002049 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002050 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002051 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002052 VBase, IsInheritedVirtualBase,
2053 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002054 HadError = true;
2055 continue;
2056 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002057
John McCallbc83b3f2010-05-20 23:23:51 +00002058 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002059 }
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCallbc83b3f2010-05-20 23:23:51 +00002062 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002063 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2064 E = ClassDecl->bases_end(); Base != E; ++Base) {
2065 // Virtuals are in the virtual base list and already constructed.
2066 if (Base->isVirtual())
2067 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002068
Alexis Hunt1d792652011-01-08 20:30:50 +00002069 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002070 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2071 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002072 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002073 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002074 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002075 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002076 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002077 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002078 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002079 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002080
John McCallbc83b3f2010-05-20 23:23:51 +00002081 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002082 }
2083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
John McCallbc83b3f2010-05-20 23:23:51 +00002085 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002086 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002087 E = ClassDecl->field_end(); Field != E; ++Field) {
2088 if ((*Field)->getType()->isIncompleteArrayType()) {
2089 assert(ClassDecl->hasFlexibleArrayMember() &&
2090 "Incomplete array type is not valid");
2091 continue;
2092 }
John McCallbc83b3f2010-05-20 23:23:51 +00002093 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002094 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
John McCallbc83b3f2010-05-20 23:23:51 +00002097 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002098 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002099 Constructor->setNumCtorInitializers(NumInitializers);
2100 CXXCtorInitializer **baseOrMemberInitializers =
2101 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002102 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002103 NumInitializers * sizeof(CXXCtorInitializer*));
2104 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002105
John McCalla6309952010-03-16 21:39:52 +00002106 // Constructors implicitly reference the base and member
2107 // destructors.
2108 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2109 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002110 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002111
2112 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002113}
2114
Eli Friedman952c15d2009-07-21 19:28:10 +00002115static void *GetKeyForTopLevelField(FieldDecl *Field) {
2116 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002117 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002118 if (RT->getDecl()->isAnonymousStructOrUnion())
2119 return static_cast<void *>(RT->getDecl());
2120 }
2121 return static_cast<void *>(Field);
2122}
2123
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002124static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002125 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002126}
2127
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002128static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002129 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002130 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002131 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002132
Eli Friedman952c15d2009-07-21 19:28:10 +00002133 // For fields injected into the class via declaration of an anonymous union,
2134 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002135 FieldDecl *Field = Member->getAnyMember();
2136
John McCall23eebd92010-04-10 09:28:51 +00002137 // If the field is a member of an anonymous struct or union, our key
2138 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002139 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002140 if (RD->isAnonymousStructOrUnion()) {
2141 while (true) {
2142 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2143 if (Parent->isAnonymousStructOrUnion())
2144 RD = Parent;
2145 else
2146 break;
2147 }
2148
Anders Carlsson83ac3122010-03-30 16:19:37 +00002149 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
Anders Carlssona942dcd2010-03-30 15:39:27 +00002152 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002153}
2154
Anders Carlssone857b292010-04-02 03:37:03 +00002155static void
2156DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002157 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002158 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002159 unsigned NumInits) {
2160 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002161 return;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002163 // Don't check initializers order unless the warning is enabled at the
2164 // location of at least one initializer.
2165 bool ShouldCheckOrder = false;
2166 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002167 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002168 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2169 Init->getSourceLocation())
2170 != Diagnostic::Ignored) {
2171 ShouldCheckOrder = true;
2172 break;
2173 }
2174 }
2175 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002176 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002177
John McCallbb7b6582010-04-10 07:37:23 +00002178 // Build the list of bases and members in the order that they'll
2179 // actually be initialized. The explicit initializers should be in
2180 // this same order but may be missing things.
2181 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002182
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002183 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2184
John McCallbb7b6582010-04-10 07:37:23 +00002185 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002186 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002187 ClassDecl->vbases_begin(),
2188 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002189 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002190
John McCallbb7b6582010-04-10 07:37:23 +00002191 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002192 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002193 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002194 if (Base->isVirtual())
2195 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002196 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
John McCallbb7b6582010-04-10 07:37:23 +00002199 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002200 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2201 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002202 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002203
John McCallbb7b6582010-04-10 07:37:23 +00002204 unsigned NumIdealInits = IdealInitKeys.size();
2205 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002206
Alexis Hunt1d792652011-01-08 20:30:50 +00002207 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002208 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002209 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002210 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002211
2212 // Scan forward to try to find this initializer in the idealized
2213 // initializers list.
2214 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2215 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002216 break;
John McCallbb7b6582010-04-10 07:37:23 +00002217
2218 // If we didn't find this initializer, it must be because we
2219 // scanned past it on a previous iteration. That can only
2220 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002221 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002222 Sema::SemaDiagnosticBuilder D =
2223 SemaRef.Diag(PrevInit->getSourceLocation(),
2224 diag::warn_initializer_out_of_order);
2225
Francois Pichetd583da02010-12-04 09:14:42 +00002226 if (PrevInit->isAnyMemberInitializer())
2227 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002228 else
2229 D << 1 << PrevInit->getBaseClassInfo()->getType();
2230
Francois Pichetd583da02010-12-04 09:14:42 +00002231 if (Init->isAnyMemberInitializer())
2232 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002233 else
2234 D << 1 << Init->getBaseClassInfo()->getType();
2235
2236 // Move back to the initializer's location in the ideal list.
2237 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2238 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002239 break;
John McCallbb7b6582010-04-10 07:37:23 +00002240
2241 assert(IdealIndex != NumIdealInits &&
2242 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002243 }
John McCallbb7b6582010-04-10 07:37:23 +00002244
2245 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002246 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002247}
2248
John McCall23eebd92010-04-10 09:28:51 +00002249namespace {
2250bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002251 CXXCtorInitializer *Init,
2252 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002253 if (!PrevInit) {
2254 PrevInit = Init;
2255 return false;
2256 }
2257
2258 if (FieldDecl *Field = Init->getMember())
2259 S.Diag(Init->getSourceLocation(),
2260 diag::err_multiple_mem_initialization)
2261 << Field->getDeclName()
2262 << Init->getSourceRange();
2263 else {
John McCall424cec92011-01-19 06:33:43 +00002264 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002265 assert(BaseClass && "neither field nor base");
2266 S.Diag(Init->getSourceLocation(),
2267 diag::err_multiple_base_initialization)
2268 << QualType(BaseClass, 0)
2269 << Init->getSourceRange();
2270 }
2271 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2272 << 0 << PrevInit->getSourceRange();
2273
2274 return true;
2275}
2276
Alexis Hunt1d792652011-01-08 20:30:50 +00002277typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002278typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2279
2280bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002281 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002282 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002283 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002284 RecordDecl *Parent = Field->getParent();
2285 if (!Parent->isAnonymousStructOrUnion())
2286 return false;
2287
2288 NamedDecl *Child = Field;
2289 do {
2290 if (Parent->isUnion()) {
2291 UnionEntry &En = Unions[Parent];
2292 if (En.first && En.first != Child) {
2293 S.Diag(Init->getSourceLocation(),
2294 diag::err_multiple_mem_union_initialization)
2295 << Field->getDeclName()
2296 << Init->getSourceRange();
2297 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2298 << 0 << En.second->getSourceRange();
2299 return true;
2300 } else if (!En.first) {
2301 En.first = Child;
2302 En.second = Init;
2303 }
2304 }
2305
2306 Child = Parent;
2307 Parent = cast<RecordDecl>(Parent->getDeclContext());
2308 } while (Parent->isAnonymousStructOrUnion());
2309
2310 return false;
2311}
2312}
2313
Anders Carlssone857b292010-04-02 03:37:03 +00002314/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002315void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002316 SourceLocation ColonLoc,
2317 MemInitTy **meminits, unsigned NumMemInits,
2318 bool AnyErrors) {
2319 if (!ConstructorDecl)
2320 return;
2321
2322 AdjustDeclIfTemplate(ConstructorDecl);
2323
2324 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002325 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002326
2327 if (!Constructor) {
2328 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2329 return;
2330 }
2331
Alexis Hunt1d792652011-01-08 20:30:50 +00002332 CXXCtorInitializer **MemInits =
2333 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002334
2335 // Mapping for the duplicate initializers check.
2336 // For member initializers, this is keyed with a FieldDecl*.
2337 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002338 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002339
2340 // Mapping for the inconsistent anonymous-union initializers check.
2341 RedundantUnionMap MemberUnions;
2342
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002343 bool HadError = false;
2344 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002345 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002346
Abramo Bagnara341d7832010-05-26 18:09:23 +00002347 // Set the source order index.
2348 Init->setSourceOrder(i);
2349
Francois Pichetd583da02010-12-04 09:14:42 +00002350 if (Init->isAnyMemberInitializer()) {
2351 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002352 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2353 CheckRedundantUnionInit(*this, Init, MemberUnions))
2354 HadError = true;
2355 } else {
2356 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2357 if (CheckRedundantInit(*this, Init, Members[Key]))
2358 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002359 }
Anders Carlssone857b292010-04-02 03:37:03 +00002360 }
2361
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002362 if (HadError)
2363 return;
2364
Anders Carlssone857b292010-04-02 03:37:03 +00002365 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002366
Alexis Hunt1d792652011-01-08 20:30:50 +00002367 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002368}
2369
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002370void
John McCalla6309952010-03-16 21:39:52 +00002371Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2372 CXXRecordDecl *ClassDecl) {
2373 // Ignore dependent contexts.
2374 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002375 return;
John McCall1064d7e2010-03-16 05:22:47 +00002376
2377 // FIXME: all the access-control diagnostics are positioned on the
2378 // field/base declaration. That's probably good; that said, the
2379 // user might reasonably want to know why the destructor is being
2380 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002381
Anders Carlssondee9a302009-11-17 04:44:12 +00002382 // Non-static data members.
2383 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2384 E = ClassDecl->field_end(); I != E; ++I) {
2385 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002386 if (Field->isInvalidDecl())
2387 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002388 QualType FieldType = Context.getBaseElementType(Field->getType());
2389
2390 const RecordType* RT = FieldType->getAs<RecordType>();
2391 if (!RT)
2392 continue;
2393
2394 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2395 if (FieldClassDecl->hasTrivialDestructor())
2396 continue;
2397
Douglas Gregore71edda2010-07-01 22:47:18 +00002398 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002399 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002400 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002401 << Field->getDeclName()
2402 << FieldType);
2403
John McCalla6309952010-03-16 21:39:52 +00002404 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002405 }
2406
John McCall1064d7e2010-03-16 05:22:47 +00002407 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2408
Anders Carlssondee9a302009-11-17 04:44:12 +00002409 // Bases.
2410 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2411 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002412 // Bases are always records in a well-formed non-dependent class.
2413 const RecordType *RT = Base->getType()->getAs<RecordType>();
2414
2415 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002416 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002417 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002418
2419 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002420 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002421 if (BaseClassDecl->hasTrivialDestructor())
2422 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002423
Douglas Gregore71edda2010-07-01 22:47:18 +00002424 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002425
2426 // FIXME: caret should be on the start of the class name
2427 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002428 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002429 << Base->getType()
2430 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002431
John McCalla6309952010-03-16 21:39:52 +00002432 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002433 }
2434
2435 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002436 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2437 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002438
2439 // Bases are always records in a well-formed non-dependent class.
2440 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2441
2442 // Ignore direct virtual bases.
2443 if (DirectVirtualBases.count(RT))
2444 continue;
2445
Anders Carlssondee9a302009-11-17 04:44:12 +00002446 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002447 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002448 if (BaseClassDecl->hasTrivialDestructor())
2449 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002450
Douglas Gregore71edda2010-07-01 22:47:18 +00002451 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002452 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002453 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002454 << VBase->getType());
2455
John McCalla6309952010-03-16 21:39:52 +00002456 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002457 }
2458}
2459
John McCall48871652010-08-21 09:40:31 +00002460void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002461 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002462 return;
Mike Stump11289f42009-09-09 15:08:12 +00002463
Mike Stump11289f42009-09-09 15:08:12 +00002464 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002465 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002466 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002467}
2468
Mike Stump11289f42009-09-09 15:08:12 +00002469bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002470 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002471 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002472 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002473 else
John McCall02db245d2010-08-18 09:41:07 +00002474 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002475}
2476
Anders Carlssoneabf7702009-08-27 00:13:57 +00002477bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002478 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002479 if (!getLangOptions().CPlusPlus)
2480 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002481
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002482 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002483 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002484
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002485 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002486 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002487 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002488 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002489
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002490 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002491 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002492 }
Mike Stump11289f42009-09-09 15:08:12 +00002493
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002494 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002495 if (!RT)
2496 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002497
John McCall67da35c2010-02-04 22:26:26 +00002498 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002499
John McCall02db245d2010-08-18 09:41:07 +00002500 // We can't answer whether something is abstract until it has a
2501 // definition. If it's currently being defined, we'll walk back
2502 // over all the declarations when we have a full definition.
2503 const CXXRecordDecl *Def = RD->getDefinition();
2504 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002505 return false;
2506
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002507 if (!RD->isAbstract())
2508 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002509
Anders Carlssoneabf7702009-08-27 00:13:57 +00002510 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002511 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002512
John McCall02db245d2010-08-18 09:41:07 +00002513 return true;
2514}
2515
2516void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2517 // Check if we've already emitted the list of pure virtual functions
2518 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002519 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002520 return;
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregor4165bd62010-03-23 23:47:56 +00002522 CXXFinalOverriderMap FinalOverriders;
2523 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002524
Anders Carlssona2f74f32010-06-03 01:00:02 +00002525 // Keep a set of seen pure methods so we won't diagnose the same method
2526 // more than once.
2527 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2528
Douglas Gregor4165bd62010-03-23 23:47:56 +00002529 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2530 MEnd = FinalOverriders.end();
2531 M != MEnd;
2532 ++M) {
2533 for (OverridingMethods::iterator SO = M->second.begin(),
2534 SOEnd = M->second.end();
2535 SO != SOEnd; ++SO) {
2536 // C++ [class.abstract]p4:
2537 // A class is abstract if it contains or inherits at least one
2538 // pure virtual function for which the final overrider is pure
2539 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregor4165bd62010-03-23 23:47:56 +00002541 //
2542 if (SO->second.size() != 1)
2543 continue;
2544
2545 if (!SO->second.front().Method->isPure())
2546 continue;
2547
Anders Carlssona2f74f32010-06-03 01:00:02 +00002548 if (!SeenPureMethods.insert(SO->second.front().Method))
2549 continue;
2550
Douglas Gregor4165bd62010-03-23 23:47:56 +00002551 Diag(SO->second.front().Method->getLocation(),
2552 diag::note_pure_virtual_function)
2553 << SO->second.front().Method->getDeclName();
2554 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002555 }
2556
2557 if (!PureVirtualClassDiagSet)
2558 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2559 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002560}
2561
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002562namespace {
John McCall02db245d2010-08-18 09:41:07 +00002563struct AbstractUsageInfo {
2564 Sema &S;
2565 CXXRecordDecl *Record;
2566 CanQualType AbstractType;
2567 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002568
John McCall02db245d2010-08-18 09:41:07 +00002569 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2570 : S(S), Record(Record),
2571 AbstractType(S.Context.getCanonicalType(
2572 S.Context.getTypeDeclType(Record))),
2573 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002574
John McCall02db245d2010-08-18 09:41:07 +00002575 void DiagnoseAbstractType() {
2576 if (Invalid) return;
2577 S.DiagnoseAbstractType(Record);
2578 Invalid = true;
2579 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002580
John McCall02db245d2010-08-18 09:41:07 +00002581 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2582};
2583
2584struct CheckAbstractUsage {
2585 AbstractUsageInfo &Info;
2586 const NamedDecl *Ctx;
2587
2588 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2589 : Info(Info), Ctx(Ctx) {}
2590
2591 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2592 switch (TL.getTypeLocClass()) {
2593#define ABSTRACT_TYPELOC(CLASS, PARENT)
2594#define TYPELOC(CLASS, PARENT) \
2595 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2596#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002597 }
John McCall02db245d2010-08-18 09:41:07 +00002598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
John McCall02db245d2010-08-18 09:41:07 +00002600 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2601 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2602 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2603 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2604 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002605 }
John McCall02db245d2010-08-18 09:41:07 +00002606 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002607
John McCall02db245d2010-08-18 09:41:07 +00002608 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2609 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
John McCall02db245d2010-08-18 09:41:07 +00002612 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2613 // Visit the type parameters from a permissive context.
2614 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2615 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2616 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2617 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2618 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2619 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002620 }
John McCall02db245d2010-08-18 09:41:07 +00002621 }
Mike Stump11289f42009-09-09 15:08:12 +00002622
John McCall02db245d2010-08-18 09:41:07 +00002623 // Visit pointee types from a permissive context.
2624#define CheckPolymorphic(Type) \
2625 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2626 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2627 }
2628 CheckPolymorphic(PointerTypeLoc)
2629 CheckPolymorphic(ReferenceTypeLoc)
2630 CheckPolymorphic(MemberPointerTypeLoc)
2631 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002632
John McCall02db245d2010-08-18 09:41:07 +00002633 /// Handle all the types we haven't given a more specific
2634 /// implementation for above.
2635 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2636 // Every other kind of type that we haven't called out already
2637 // that has an inner type is either (1) sugar or (2) contains that
2638 // inner type in some way as a subobject.
2639 if (TypeLoc Next = TL.getNextTypeLoc())
2640 return Visit(Next, Sel);
2641
2642 // If there's no inner type and we're in a permissive context,
2643 // don't diagnose.
2644 if (Sel == Sema::AbstractNone) return;
2645
2646 // Check whether the type matches the abstract type.
2647 QualType T = TL.getType();
2648 if (T->isArrayType()) {
2649 Sel = Sema::AbstractArrayType;
2650 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002651 }
John McCall02db245d2010-08-18 09:41:07 +00002652 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2653 if (CT != Info.AbstractType) return;
2654
2655 // It matched; do some magic.
2656 if (Sel == Sema::AbstractArrayType) {
2657 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2658 << T << TL.getSourceRange();
2659 } else {
2660 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2661 << Sel << T << TL.getSourceRange();
2662 }
2663 Info.DiagnoseAbstractType();
2664 }
2665};
2666
2667void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2668 Sema::AbstractDiagSelID Sel) {
2669 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2670}
2671
2672}
2673
2674/// Check for invalid uses of an abstract type in a method declaration.
2675static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2676 CXXMethodDecl *MD) {
2677 // No need to do the check on definitions, which require that
2678 // the return/param types be complete.
2679 if (MD->isThisDeclarationADefinition())
2680 return;
2681
2682 // For safety's sake, just ignore it if we don't have type source
2683 // information. This should never happen for non-implicit methods,
2684 // but...
2685 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2686 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2687}
2688
2689/// Check for invalid uses of an abstract type within a class definition.
2690static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2691 CXXRecordDecl *RD) {
2692 for (CXXRecordDecl::decl_iterator
2693 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2694 Decl *D = *I;
2695 if (D->isImplicit()) continue;
2696
2697 // Methods and method templates.
2698 if (isa<CXXMethodDecl>(D)) {
2699 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2700 } else if (isa<FunctionTemplateDecl>(D)) {
2701 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2702 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2703
2704 // Fields and static variables.
2705 } else if (isa<FieldDecl>(D)) {
2706 FieldDecl *FD = cast<FieldDecl>(D);
2707 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2708 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2709 } else if (isa<VarDecl>(D)) {
2710 VarDecl *VD = cast<VarDecl>(D);
2711 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2712 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2713
2714 // Nested classes and class templates.
2715 } else if (isa<CXXRecordDecl>(D)) {
2716 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2717 } else if (isa<ClassTemplateDecl>(D)) {
2718 CheckAbstractClassUsage(Info,
2719 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2720 }
2721 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002722}
2723
Douglas Gregorc99f1552009-12-03 18:33:45 +00002724/// \brief Perform semantic checks on a class definition that has been
2725/// completing, introducing implicitly-declared members, checking for
2726/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002727void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002728 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002729 return;
2730
John McCall02db245d2010-08-18 09:41:07 +00002731 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2732 AbstractUsageInfo Info(*this, Record);
2733 CheckAbstractClassUsage(Info, Record);
2734 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002735
2736 // If this is not an aggregate type and has no user-declared constructor,
2737 // complain about any non-static data members of reference or const scalar
2738 // type, since they will never get initializers.
2739 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2740 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2741 bool Complained = false;
2742 for (RecordDecl::field_iterator F = Record->field_begin(),
2743 FEnd = Record->field_end();
2744 F != FEnd; ++F) {
2745 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002746 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002747 if (!Complained) {
2748 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2749 << Record->getTagKind() << Record;
2750 Complained = true;
2751 }
2752
2753 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2754 << F->getType()->isReferenceType()
2755 << F->getDeclName();
2756 }
2757 }
2758 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002759
2760 if (Record->isDynamicClass())
2761 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002762
2763 if (Record->getIdentifier()) {
2764 // C++ [class.mem]p13:
2765 // If T is the name of a class, then each of the following shall have a
2766 // name different from T:
2767 // - every member of every anonymous union that is a member of class T.
2768 //
2769 // C++ [class.mem]p14:
2770 // In addition, if class T has a user-declared constructor (12.1), every
2771 // non-static data member of class T shall have a name different from T.
2772 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002773 R.first != R.second; ++R.first) {
2774 NamedDecl *D = *R.first;
2775 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2776 isa<IndirectFieldDecl>(D)) {
2777 Diag(D->getLocation(), diag::err_member_name_of_class)
2778 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002779 break;
2780 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002781 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002782 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002783}
2784
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002785void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002786 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002787 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002788 SourceLocation RBrac,
2789 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002790 if (!TagDecl)
2791 return;
Mike Stump11289f42009-09-09 15:08:12 +00002792
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002793 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002794
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002795 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002796 // strict aliasing violation!
2797 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002798 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002799
Douglas Gregor0be31a22010-07-02 17:43:08 +00002800 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002801 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002802}
2803
Douglas Gregor95755162010-07-01 05:10:53 +00002804namespace {
2805 /// \brief Helper class that collects exception specifications for
2806 /// implicitly-declared special member functions.
2807 class ImplicitExceptionSpecification {
2808 ASTContext &Context;
2809 bool AllowsAllExceptions;
2810 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2811 llvm::SmallVector<QualType, 4> Exceptions;
2812
2813 public:
2814 explicit ImplicitExceptionSpecification(ASTContext &Context)
2815 : Context(Context), AllowsAllExceptions(false) { }
2816
2817 /// \brief Whether the special member function should have any
2818 /// exception specification at all.
2819 bool hasExceptionSpecification() const {
2820 return !AllowsAllExceptions;
2821 }
2822
2823 /// \brief Whether the special member function should have a
2824 /// throw(...) exception specification (a Microsoft extension).
2825 bool hasAnyExceptionSpecification() const {
2826 return false;
2827 }
2828
2829 /// \brief The number of exceptions in the exception specification.
2830 unsigned size() const { return Exceptions.size(); }
2831
2832 /// \brief The set of exceptions in the exception specification.
2833 const QualType *data() const { return Exceptions.data(); }
2834
2835 /// \brief Note that
2836 void CalledDecl(CXXMethodDecl *Method) {
2837 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002838 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002839 return;
2840
2841 const FunctionProtoType *Proto
2842 = Method->getType()->getAs<FunctionProtoType>();
2843
2844 // If this function can throw any exceptions, make a note of that.
2845 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2846 AllowsAllExceptions = true;
2847 ExceptionsSeen.clear();
2848 Exceptions.clear();
2849 return;
2850 }
2851
2852 // Record the exceptions in this function's exception specification.
2853 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2854 EEnd = Proto->exception_end();
2855 E != EEnd; ++E)
2856 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2857 Exceptions.push_back(*E);
2858 }
2859 };
2860}
2861
2862
Douglas Gregor05379422008-11-03 17:51:48 +00002863/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2864/// special functions, such as the default constructor, copy
2865/// constructor, or destructor, to the given C++ class (C++
2866/// [special]p1). This routine can only be executed just before the
2867/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002868void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002869 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002870 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002871
Douglas Gregor54be3392010-07-01 17:57:27 +00002872 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002873 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002874
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002875 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2876 ++ASTContext::NumImplicitCopyAssignmentOperators;
2877
2878 // If we have a dynamic class, then the copy assignment operator may be
2879 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2880 // it shows up in the right place in the vtable and that we diagnose
2881 // problems with the implicit exception specification.
2882 if (ClassDecl->isDynamicClass())
2883 DeclareImplicitCopyAssignment(ClassDecl);
2884 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002885
Douglas Gregor7454c562010-07-02 20:37:36 +00002886 if (!ClassDecl->hasUserDeclaredDestructor()) {
2887 ++ASTContext::NumImplicitDestructors;
2888
2889 // If we have a dynamic class, then the destructor may be virtual, so we
2890 // have to declare the destructor immediately. This ensures that, e.g., it
2891 // shows up in the right place in the vtable and that we diagnose problems
2892 // with the implicit exception specification.
2893 if (ClassDecl->isDynamicClass())
2894 DeclareImplicitDestructor(ClassDecl);
2895 }
Douglas Gregor05379422008-11-03 17:51:48 +00002896}
2897
John McCall48871652010-08-21 09:40:31 +00002898void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002899 if (!D)
2900 return;
2901
2902 TemplateParameterList *Params = 0;
2903 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2904 Params = Template->getTemplateParameters();
2905 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2906 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2907 Params = PartialSpec->getTemplateParameters();
2908 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002909 return;
2910
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002911 for (TemplateParameterList::iterator Param = Params->begin(),
2912 ParamEnd = Params->end();
2913 Param != ParamEnd; ++Param) {
2914 NamedDecl *Named = cast<NamedDecl>(*Param);
2915 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002916 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002917 IdResolver.AddDecl(Named);
2918 }
2919 }
2920}
2921
John McCall48871652010-08-21 09:40:31 +00002922void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002923 if (!RecordD) return;
2924 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002925 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002926 PushDeclContext(S, Record);
2927}
2928
John McCall48871652010-08-21 09:40:31 +00002929void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002930 if (!RecordD) return;
2931 PopDeclContext();
2932}
2933
Douglas Gregor4d87df52008-12-16 21:30:33 +00002934/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2935/// parsing a top-level (non-nested) C++ class, and we are now
2936/// parsing those parts of the given Method declaration that could
2937/// not be parsed earlier (C++ [class.mem]p2), such as default
2938/// arguments. This action should enter the scope of the given
2939/// Method declaration as if we had just parsed the qualified method
2940/// name. However, it should not bring the parameters into scope;
2941/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002942void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002943}
2944
2945/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2946/// C++ method declaration. We're (re-)introducing the given
2947/// function parameter into scope for use in parsing later parts of
2948/// the method declaration. For example, we could see an
2949/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002950void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002951 if (!ParamD)
2952 return;
Mike Stump11289f42009-09-09 15:08:12 +00002953
John McCall48871652010-08-21 09:40:31 +00002954 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002955
2956 // If this parameter has an unparsed default argument, clear it out
2957 // to make way for the parsed default argument.
2958 if (Param->hasUnparsedDefaultArg())
2959 Param->setDefaultArg(0);
2960
John McCall48871652010-08-21 09:40:31 +00002961 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002962 if (Param->getDeclName())
2963 IdResolver.AddDecl(Param);
2964}
2965
2966/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2967/// processing the delayed method declaration for Method. The method
2968/// declaration is now considered finished. There may be a separate
2969/// ActOnStartOfFunctionDef action later (not necessarily
2970/// immediately!) for this method, if it was also defined inside the
2971/// class body.
John McCall48871652010-08-21 09:40:31 +00002972void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002973 if (!MethodD)
2974 return;
Mike Stump11289f42009-09-09 15:08:12 +00002975
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002976 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002977
John McCall48871652010-08-21 09:40:31 +00002978 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002979
2980 // Now that we have our default arguments, check the constructor
2981 // again. It could produce additional diagnostics or affect whether
2982 // the class has implicitly-declared destructors, among other
2983 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002984 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2985 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002986
2987 // Check the default arguments, which we may have added.
2988 if (!Method->isInvalidDecl())
2989 CheckCXXDefaultArguments(Method);
2990}
2991
Douglas Gregor831c93f2008-11-05 20:51:48 +00002992/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002993/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002994/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002995/// emit diagnostics and set the invalid bit to true. In any case, the type
2996/// will be updated to reflect a well-formed type for the constructor and
2997/// returned.
2998QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002999 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003000 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003001
3002 // C++ [class.ctor]p3:
3003 // A constructor shall not be virtual (10.3) or static (9.4). A
3004 // constructor can be invoked for a const, volatile or const
3005 // volatile object. A constructor shall not be declared const,
3006 // volatile, or const volatile (9.3.2).
3007 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003008 if (!D.isInvalidType())
3009 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3010 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3011 << SourceRange(D.getIdentifierLoc());
3012 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003013 }
John McCall8e7d6562010-08-26 03:08:43 +00003014 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003015 if (!D.isInvalidType())
3016 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3017 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3018 << SourceRange(D.getIdentifierLoc());
3019 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003020 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003021 }
Mike Stump11289f42009-09-09 15:08:12 +00003022
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003023 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003024 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003025 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003026 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3027 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003028 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003029 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3030 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003031 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003032 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3033 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003034 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
Douglas Gregor831c93f2008-11-05 20:51:48 +00003037 // Rebuild the function type "R" without any type qualifiers (in
3038 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003039 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003040 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003041 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3042 return R;
3043
3044 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3045 EPI.TypeQuals = 0;
3046
Chris Lattner38378bf2009-04-25 08:28:21 +00003047 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003048 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003049}
3050
Douglas Gregor4d87df52008-12-16 21:30:33 +00003051/// CheckConstructor - Checks a fully-formed constructor for
3052/// well-formedness, issuing any diagnostics required. Returns true if
3053/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003054void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003055 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003056 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3057 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003058 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003059
3060 // C++ [class.copy]p3:
3061 // A declaration of a constructor for a class X is ill-formed if
3062 // its first parameter is of type (optionally cv-qualified) X and
3063 // either there are no other parameters or else all other
3064 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003065 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003066 ((Constructor->getNumParams() == 1) ||
3067 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003068 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3069 Constructor->getTemplateSpecializationKind()
3070 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003071 QualType ParamType = Constructor->getParamDecl(0)->getType();
3072 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3073 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003074 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003075 const char *ConstRef
3076 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3077 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003078 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003079 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003080
3081 // FIXME: Rather that making the constructor invalid, we should endeavor
3082 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003083 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003084 }
3085 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003086}
3087
John McCalldeb646e2010-08-04 01:04:25 +00003088/// CheckDestructor - Checks a fully-formed destructor definition for
3089/// well-formedness, issuing any diagnostics required. Returns true
3090/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003091bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003092 CXXRecordDecl *RD = Destructor->getParent();
3093
3094 if (Destructor->isVirtual()) {
3095 SourceLocation Loc;
3096
3097 if (!Destructor->isImplicit())
3098 Loc = Destructor->getLocation();
3099 else
3100 Loc = RD->getLocation();
3101
3102 // If we have a virtual destructor, look up the deallocation function
3103 FunctionDecl *OperatorDelete = 0;
3104 DeclarationName Name =
3105 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003106 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003107 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003108
3109 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003110
3111 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003112 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003113
3114 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003115}
3116
Mike Stump11289f42009-09-09 15:08:12 +00003117static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003118FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3119 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3120 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003121 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003122}
3123
Douglas Gregor831c93f2008-11-05 20:51:48 +00003124/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3125/// the well-formednes of the destructor declarator @p D with type @p
3126/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003127/// emit diagnostics and set the declarator to invalid. Even if this happens,
3128/// will be updated to reflect a well-formed type for the destructor and
3129/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003130QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003131 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003132 // C++ [class.dtor]p1:
3133 // [...] A typedef-name that names a class is a class-name
3134 // (7.1.3); however, a typedef-name that names a class shall not
3135 // be used as the identifier in the declarator for a destructor
3136 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003137 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003138 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003139 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003140 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003141
3142 // C++ [class.dtor]p2:
3143 // A destructor is used to destroy objects of its class type. A
3144 // destructor takes no parameters, and no return type can be
3145 // specified for it (not even void). The address of a destructor
3146 // shall not be taken. A destructor shall not be static. A
3147 // destructor can be invoked for a const, volatile or const
3148 // volatile object. A destructor shall not be declared const,
3149 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003150 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003151 if (!D.isInvalidType())
3152 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3153 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003154 << SourceRange(D.getIdentifierLoc())
3155 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3156
John McCall8e7d6562010-08-26 03:08:43 +00003157 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003158 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003159 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003160 // Destructors don't have return types, but the parser will
3161 // happily parse something like:
3162 //
3163 // class X {
3164 // float ~X();
3165 // };
3166 //
3167 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003168 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3169 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3170 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003171 }
Mike Stump11289f42009-09-09 15:08:12 +00003172
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003173 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003174 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003175 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003176 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3177 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003178 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003179 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3180 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003181 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003182 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3183 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003184 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003185 }
3186
3187 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003188 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003189 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3190
3191 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003192 FTI.freeArgs();
3193 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003194 }
3195
Mike Stump11289f42009-09-09 15:08:12 +00003196 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003197 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003198 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003199 D.setInvalidType();
3200 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003201
3202 // Rebuild the function type "R" without any type qualifiers or
3203 // parameters (in case any of the errors above fired) and with
3204 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003205 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003206 if (!D.isInvalidType())
3207 return R;
3208
Douglas Gregor95755162010-07-01 05:10:53 +00003209 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003210 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3211 EPI.Variadic = false;
3212 EPI.TypeQuals = 0;
3213 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003214}
3215
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003216/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3217/// well-formednes of the conversion function declarator @p D with
3218/// type @p R. If there are any errors in the declarator, this routine
3219/// will emit diagnostics and return true. Otherwise, it will return
3220/// false. Either way, the type @p R will be updated to reflect a
3221/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003222void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003223 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003224 // C++ [class.conv.fct]p1:
3225 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003226 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003227 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003228 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003229 if (!D.isInvalidType())
3230 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3231 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3232 << SourceRange(D.getIdentifierLoc());
3233 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003234 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003235 }
John McCall212fa2e2010-04-13 00:04:31 +00003236
3237 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3238
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003239 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003240 // Conversion functions don't have return types, but the parser will
3241 // happily parse something like:
3242 //
3243 // class X {
3244 // float operator bool();
3245 // };
3246 //
3247 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003248 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3249 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3250 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003251 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003252 }
3253
John McCall212fa2e2010-04-13 00:04:31 +00003254 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3255
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003256 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003257 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003258 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3259
3260 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003261 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003262 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003263 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003264 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003265 D.setInvalidType();
3266 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003267
John McCall212fa2e2010-04-13 00:04:31 +00003268 // Diagnose "&operator bool()" and other such nonsense. This
3269 // is actually a gcc extension which we don't support.
3270 if (Proto->getResultType() != ConvType) {
3271 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3272 << Proto->getResultType();
3273 D.setInvalidType();
3274 ConvType = Proto->getResultType();
3275 }
3276
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003277 // C++ [class.conv.fct]p4:
3278 // The conversion-type-id shall not represent a function type nor
3279 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003280 if (ConvType->isArrayType()) {
3281 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3282 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003283 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003284 } else if (ConvType->isFunctionType()) {
3285 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3286 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003287 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003288 }
3289
3290 // Rebuild the function type "R" without any parameters (in case any
3291 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003292 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003293 if (D.isInvalidType())
3294 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003295
Douglas Gregor5fb53972009-01-14 15:45:31 +00003296 // C++0x explicit conversion operators.
3297 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003298 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003299 diag::warn_explicit_conversion_functions)
3300 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003301}
3302
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003303/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3304/// the declaration of the given C++ conversion function. This routine
3305/// is responsible for recording the conversion function in the C++
3306/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003307Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003308 assert(Conversion && "Expected to receive a conversion function declaration");
3309
Douglas Gregor4287b372008-12-12 08:25:50 +00003310 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003311
3312 // Make sure we aren't redeclaring the conversion function.
3313 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003314
3315 // C++ [class.conv.fct]p1:
3316 // [...] A conversion function is never used to convert a
3317 // (possibly cv-qualified) object to the (possibly cv-qualified)
3318 // same object type (or a reference to it), to a (possibly
3319 // cv-qualified) base class of that type (or a reference to it),
3320 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003321 // FIXME: Suppress this warning if the conversion function ends up being a
3322 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003323 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003324 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003325 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003326 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003327 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3328 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003329 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003330 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003331 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3332 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003333 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003334 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003335 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003336 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003337 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003338 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003339 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003340 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003341 }
3342
Douglas Gregor457104e2010-09-29 04:25:11 +00003343 if (FunctionTemplateDecl *ConversionTemplate
3344 = Conversion->getDescribedFunctionTemplate())
3345 return ConversionTemplate;
3346
John McCall48871652010-08-21 09:40:31 +00003347 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003348}
3349
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003350//===----------------------------------------------------------------------===//
3351// Namespace Handling
3352//===----------------------------------------------------------------------===//
3353
John McCallb1be5232010-08-26 09:15:37 +00003354
3355
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003356/// ActOnStartNamespaceDef - This is called at the start of a namespace
3357/// definition.
John McCall48871652010-08-21 09:40:31 +00003358Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003359 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003360 SourceLocation IdentLoc,
3361 IdentifierInfo *II,
3362 SourceLocation LBrace,
3363 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003364 // anonymous namespace starts at its left brace
3365 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3366 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003367 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003368 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003369
3370 Scope *DeclRegionScope = NamespcScope->getParent();
3371
Anders Carlssona7bcade2010-02-07 01:09:23 +00003372 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3373
John McCall2faf32c2010-12-10 02:59:44 +00003374 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3375 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003376
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003377 if (II) {
3378 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003379 // The identifier in an original-namespace-definition shall not
3380 // have been previously defined in the declarative region in
3381 // which the original-namespace-definition appears. The
3382 // identifier in an original-namespace-definition is the name of
3383 // the namespace. Subsequently in that declarative region, it is
3384 // treated as an original-namespace-name.
3385 //
3386 // Since namespace names are unique in their scope, and we don't
3387 // look through using directives, just
3388 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3389 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003390
Douglas Gregor91f84212008-12-11 16:49:14 +00003391 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3392 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003393 if (Namespc->isInline() != OrigNS->isInline()) {
3394 // inline-ness must match
3395 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3396 << Namespc->isInline();
3397 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3398 Namespc->setInvalidDecl();
3399 // Recover by ignoring the new namespace's inline status.
3400 Namespc->setInline(OrigNS->isInline());
3401 }
3402
Douglas Gregor91f84212008-12-11 16:49:14 +00003403 // Attach this namespace decl to the chain of extended namespace
3404 // definitions.
3405 OrigNS->setNextNamespace(Namespc);
3406 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003407
Mike Stump11289f42009-09-09 15:08:12 +00003408 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003409 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003410 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003411 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003412 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003413 } else if (PrevDecl) {
3414 // This is an invalid name redefinition.
3415 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3416 << Namespc->getDeclName();
3417 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3418 Namespc->setInvalidDecl();
3419 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003420 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003421 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003422 // This is the first "real" definition of the namespace "std", so update
3423 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003424 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003425 // We had already defined a dummy namespace "std". Link this new
3426 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003427 StdNS->setNextNamespace(Namespc);
3428 StdNS->setLocation(IdentLoc);
3429 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003430 }
3431
3432 // Make our StdNamespace cache point at the first real definition of the
3433 // "std" namespace.
3434 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003435 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003436
3437 PushOnScopeChains(Namespc, DeclRegionScope);
3438 } else {
John McCall4fa53422009-10-01 00:25:31 +00003439 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003440 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003441
3442 // Link the anonymous namespace into its parent.
3443 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003444 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003445 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3446 PrevDecl = TU->getAnonymousNamespace();
3447 TU->setAnonymousNamespace(Namespc);
3448 } else {
3449 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3450 PrevDecl = ND->getAnonymousNamespace();
3451 ND->setAnonymousNamespace(Namespc);
3452 }
3453
3454 // Link the anonymous namespace with its previous declaration.
3455 if (PrevDecl) {
3456 assert(PrevDecl->isAnonymousNamespace());
3457 assert(!PrevDecl->getNextNamespace());
3458 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3459 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003460
3461 if (Namespc->isInline() != PrevDecl->isInline()) {
3462 // inline-ness must match
3463 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3464 << Namespc->isInline();
3465 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3466 Namespc->setInvalidDecl();
3467 // Recover by ignoring the new namespace's inline status.
3468 Namespc->setInline(PrevDecl->isInline());
3469 }
John McCall0db42252009-12-16 02:06:49 +00003470 }
John McCall4fa53422009-10-01 00:25:31 +00003471
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003472 CurContext->addDecl(Namespc);
3473
John McCall4fa53422009-10-01 00:25:31 +00003474 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3475 // behaves as if it were replaced by
3476 // namespace unique { /* empty body */ }
3477 // using namespace unique;
3478 // namespace unique { namespace-body }
3479 // where all occurrences of 'unique' in a translation unit are
3480 // replaced by the same identifier and this identifier differs
3481 // from all other identifiers in the entire program.
3482
3483 // We just create the namespace with an empty name and then add an
3484 // implicit using declaration, just like the standard suggests.
3485 //
3486 // CodeGen enforces the "universally unique" aspect by giving all
3487 // declarations semantically contained within an anonymous
3488 // namespace internal linkage.
3489
John McCall0db42252009-12-16 02:06:49 +00003490 if (!PrevDecl) {
3491 UsingDirectiveDecl* UD
3492 = UsingDirectiveDecl::Create(Context, CurContext,
3493 /* 'using' */ LBrace,
3494 /* 'namespace' */ SourceLocation(),
3495 /* qualifier */ SourceRange(),
3496 /* NNS */ NULL,
3497 /* identifier */ SourceLocation(),
3498 Namespc,
3499 /* Ancestor */ CurContext);
3500 UD->setImplicit();
3501 CurContext->addDecl(UD);
3502 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003503 }
3504
3505 // Although we could have an invalid decl (i.e. the namespace name is a
3506 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003507 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3508 // for the namespace has the declarations that showed up in that particular
3509 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003510 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003511 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003512}
3513
Sebastian Redla6602e92009-11-23 15:34:23 +00003514/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3515/// is a namespace alias, returns the namespace it points to.
3516static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3517 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3518 return AD->getNamespace();
3519 return dyn_cast_or_null<NamespaceDecl>(D);
3520}
3521
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003522/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3523/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003524void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003525 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3526 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3527 Namespc->setRBracLoc(RBrace);
3528 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003529 if (Namespc->hasAttr<VisibilityAttr>())
3530 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003531}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003532
John McCall28a0cf72010-08-25 07:42:41 +00003533CXXRecordDecl *Sema::getStdBadAlloc() const {
3534 return cast_or_null<CXXRecordDecl>(
3535 StdBadAlloc.get(Context.getExternalSource()));
3536}
3537
3538NamespaceDecl *Sema::getStdNamespace() const {
3539 return cast_or_null<NamespaceDecl>(
3540 StdNamespace.get(Context.getExternalSource()));
3541}
3542
Douglas Gregorcdf87022010-06-29 17:53:46 +00003543/// \brief Retrieve the special "std" namespace, which may require us to
3544/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003545NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003546 if (!StdNamespace) {
3547 // The "std" namespace has not yet been defined, so build one implicitly.
3548 StdNamespace = NamespaceDecl::Create(Context,
3549 Context.getTranslationUnitDecl(),
3550 SourceLocation(),
3551 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003552 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003553 }
3554
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003555 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003556}
3557
John McCall48871652010-08-21 09:40:31 +00003558Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003559 SourceLocation UsingLoc,
3560 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003561 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003562 SourceLocation IdentLoc,
3563 IdentifierInfo *NamespcName,
3564 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003565 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3566 assert(NamespcName && "Invalid NamespcName.");
3567 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003568
3569 // This can only happen along a recovery path.
3570 while (S->getFlags() & Scope::TemplateParamScope)
3571 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003572 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003573
Douglas Gregor889ceb72009-02-03 19:21:40 +00003574 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003575 NestedNameSpecifier *Qualifier = 0;
3576 if (SS.isSet())
3577 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3578
Douglas Gregor34074322009-01-14 22:20:51 +00003579 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003580 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3581 LookupParsedName(R, S, &SS);
3582 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003583 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003584
Douglas Gregorcdf87022010-06-29 17:53:46 +00003585 if (R.empty()) {
3586 // Allow "using namespace std;" or "using namespace ::std;" even if
3587 // "std" hasn't been defined yet, for GCC compatibility.
3588 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3589 NamespcName->isStr("std")) {
3590 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003591 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003592 R.resolveKind();
3593 }
3594 // Otherwise, attempt typo correction.
3595 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3596 CTC_NoKeywords, 0)) {
3597 if (R.getAsSingle<NamespaceDecl>() ||
3598 R.getAsSingle<NamespaceAliasDecl>()) {
3599 if (DeclContext *DC = computeDeclContext(SS, false))
3600 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3601 << NamespcName << DC << Corrected << SS.getRange()
3602 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3603 else
3604 Diag(IdentLoc, diag::err_using_directive_suggest)
3605 << NamespcName << Corrected
3606 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3607 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3608 << Corrected;
3609
3610 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003611 } else {
3612 R.clear();
3613 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003614 }
3615 }
3616 }
3617
John McCall9f3059a2009-10-09 21:13:30 +00003618 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003619 NamedDecl *Named = R.getFoundDecl();
3620 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3621 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003622 // C++ [namespace.udir]p1:
3623 // A using-directive specifies that the names in the nominated
3624 // namespace can be used in the scope in which the
3625 // using-directive appears after the using-directive. During
3626 // unqualified name lookup (3.4.1), the names appear as if they
3627 // were declared in the nearest enclosing namespace which
3628 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003629 // namespace. [Note: in this context, "contains" means "contains
3630 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003631
3632 // Find enclosing context containing both using-directive and
3633 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003634 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003635 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3636 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3637 CommonAncestor = CommonAncestor->getParent();
3638
Sebastian Redla6602e92009-11-23 15:34:23 +00003639 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003640 SS.getRange(),
3641 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003642 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003643 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003644 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003645 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003646 }
3647
Douglas Gregor889ceb72009-02-03 19:21:40 +00003648 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003649 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003650}
3651
3652void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3653 // If scope has associated entity, then using directive is at namespace
3654 // or translation unit scope. We add UsingDirectiveDecls, into
3655 // it's lookup structure.
3656 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003657 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003658 else
3659 // Otherwise it is block-sope. using-directives will affect lookup
3660 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003661 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003662}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003663
Douglas Gregorfec52632009-06-20 00:51:54 +00003664
John McCall48871652010-08-21 09:40:31 +00003665Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003666 AccessSpecifier AS,
3667 bool HasUsingKeyword,
3668 SourceLocation UsingLoc,
3669 CXXScopeSpec &SS,
3670 UnqualifiedId &Name,
3671 AttributeList *AttrList,
3672 bool IsTypeName,
3673 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003674 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003675
Douglas Gregor220f4272009-11-04 16:30:06 +00003676 switch (Name.getKind()) {
3677 case UnqualifiedId::IK_Identifier:
3678 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003679 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003680 case UnqualifiedId::IK_ConversionFunctionId:
3681 break;
3682
3683 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003684 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003685 // C++0x inherited constructors.
3686 if (getLangOptions().CPlusPlus0x) break;
3687
Douglas Gregor220f4272009-11-04 16:30:06 +00003688 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3689 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003690 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003691
3692 case UnqualifiedId::IK_DestructorName:
3693 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3694 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003695 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003696
3697 case UnqualifiedId::IK_TemplateId:
3698 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3699 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003700 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003701 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003702
3703 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3704 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003705 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003706 return 0;
John McCall3969e302009-12-08 07:46:18 +00003707
John McCalla0097262009-12-11 02:10:03 +00003708 // Warn about using declarations.
3709 // TODO: store that the declaration was written without 'using' and
3710 // talk about access decls instead of using decls in the
3711 // diagnostics.
3712 if (!HasUsingKeyword) {
3713 UsingLoc = Name.getSourceRange().getBegin();
3714
3715 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003716 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003717 }
3718
Douglas Gregorc4356532010-12-16 00:46:58 +00003719 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3720 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3721 return 0;
3722
John McCall3f746822009-11-17 05:59:44 +00003723 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003724 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003725 /* IsInstantiation */ false,
3726 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003727 if (UD)
3728 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003729
John McCall48871652010-08-21 09:40:31 +00003730 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003731}
3732
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003733/// \brief Determine whether a using declaration considers the given
3734/// declarations as "equivalent", e.g., if they are redeclarations of
3735/// the same entity or are both typedefs of the same type.
3736static bool
3737IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3738 bool &SuppressRedeclaration) {
3739 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3740 SuppressRedeclaration = false;
3741 return true;
3742 }
3743
3744 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3745 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3746 SuppressRedeclaration = true;
3747 return Context.hasSameType(TD1->getUnderlyingType(),
3748 TD2->getUnderlyingType());
3749 }
3750
3751 return false;
3752}
3753
3754
John McCall84d87672009-12-10 09:41:52 +00003755/// Determines whether to create a using shadow decl for a particular
3756/// decl, given the set of decls existing prior to this using lookup.
3757bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3758 const LookupResult &Previous) {
3759 // Diagnose finding a decl which is not from a base class of the
3760 // current class. We do this now because there are cases where this
3761 // function will silently decide not to build a shadow decl, which
3762 // will pre-empt further diagnostics.
3763 //
3764 // We don't need to do this in C++0x because we do the check once on
3765 // the qualifier.
3766 //
3767 // FIXME: diagnose the following if we care enough:
3768 // struct A { int foo; };
3769 // struct B : A { using A::foo; };
3770 // template <class T> struct C : A {};
3771 // template <class T> struct D : C<T> { using B::foo; } // <---
3772 // This is invalid (during instantiation) in C++03 because B::foo
3773 // resolves to the using decl in B, which is not a base class of D<T>.
3774 // We can't diagnose it immediately because C<T> is an unknown
3775 // specialization. The UsingShadowDecl in D<T> then points directly
3776 // to A::foo, which will look well-formed when we instantiate.
3777 // The right solution is to not collapse the shadow-decl chain.
3778 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3779 DeclContext *OrigDC = Orig->getDeclContext();
3780
3781 // Handle enums and anonymous structs.
3782 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3783 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3784 while (OrigRec->isAnonymousStructOrUnion())
3785 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3786
3787 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3788 if (OrigDC == CurContext) {
3789 Diag(Using->getLocation(),
3790 diag::err_using_decl_nested_name_specifier_is_current_class)
3791 << Using->getNestedNameRange();
3792 Diag(Orig->getLocation(), diag::note_using_decl_target);
3793 return true;
3794 }
3795
3796 Diag(Using->getNestedNameRange().getBegin(),
3797 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3798 << Using->getTargetNestedNameDecl()
3799 << cast<CXXRecordDecl>(CurContext)
3800 << Using->getNestedNameRange();
3801 Diag(Orig->getLocation(), diag::note_using_decl_target);
3802 return true;
3803 }
3804 }
3805
3806 if (Previous.empty()) return false;
3807
3808 NamedDecl *Target = Orig;
3809 if (isa<UsingShadowDecl>(Target))
3810 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3811
John McCalla17e83e2009-12-11 02:33:26 +00003812 // If the target happens to be one of the previous declarations, we
3813 // don't have a conflict.
3814 //
3815 // FIXME: but we might be increasing its access, in which case we
3816 // should redeclare it.
3817 NamedDecl *NonTag = 0, *Tag = 0;
3818 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3819 I != E; ++I) {
3820 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003821 bool Result;
3822 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3823 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003824
3825 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3826 }
3827
John McCall84d87672009-12-10 09:41:52 +00003828 if (Target->isFunctionOrFunctionTemplate()) {
3829 FunctionDecl *FD;
3830 if (isa<FunctionTemplateDecl>(Target))
3831 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3832 else
3833 FD = cast<FunctionDecl>(Target);
3834
3835 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003836 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003837 case Ovl_Overload:
3838 return false;
3839
3840 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003841 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003842 break;
3843
3844 // We found a decl with the exact signature.
3845 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003846 // If we're in a record, we want to hide the target, so we
3847 // return true (without a diagnostic) to tell the caller not to
3848 // build a shadow decl.
3849 if (CurContext->isRecord())
3850 return true;
3851
3852 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003853 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003854 break;
3855 }
3856
3857 Diag(Target->getLocation(), diag::note_using_decl_target);
3858 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3859 return true;
3860 }
3861
3862 // Target is not a function.
3863
John McCall84d87672009-12-10 09:41:52 +00003864 if (isa<TagDecl>(Target)) {
3865 // No conflict between a tag and a non-tag.
3866 if (!Tag) return false;
3867
John McCalle29c5cd2009-12-10 19:51:03 +00003868 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003869 Diag(Target->getLocation(), diag::note_using_decl_target);
3870 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3871 return true;
3872 }
3873
3874 // No conflict between a tag and a non-tag.
3875 if (!NonTag) return false;
3876
John McCalle29c5cd2009-12-10 19:51:03 +00003877 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003878 Diag(Target->getLocation(), diag::note_using_decl_target);
3879 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3880 return true;
3881}
3882
John McCall3f746822009-11-17 05:59:44 +00003883/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003884UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003885 UsingDecl *UD,
3886 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003887
3888 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003889 NamedDecl *Target = Orig;
3890 if (isa<UsingShadowDecl>(Target)) {
3891 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3892 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003893 }
3894
3895 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003896 = UsingShadowDecl::Create(Context, CurContext,
3897 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003898 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003899
3900 Shadow->setAccess(UD->getAccess());
3901 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3902 Shadow->setInvalidDecl();
3903
John McCall3f746822009-11-17 05:59:44 +00003904 if (S)
John McCall3969e302009-12-08 07:46:18 +00003905 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003906 else
John McCall3969e302009-12-08 07:46:18 +00003907 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003908
John McCall3969e302009-12-08 07:46:18 +00003909
John McCall84d87672009-12-10 09:41:52 +00003910 return Shadow;
3911}
John McCall3969e302009-12-08 07:46:18 +00003912
John McCall84d87672009-12-10 09:41:52 +00003913/// Hides a using shadow declaration. This is required by the current
3914/// using-decl implementation when a resolvable using declaration in a
3915/// class is followed by a declaration which would hide or override
3916/// one or more of the using decl's targets; for example:
3917///
3918/// struct Base { void foo(int); };
3919/// struct Derived : Base {
3920/// using Base::foo;
3921/// void foo(int);
3922/// };
3923///
3924/// The governing language is C++03 [namespace.udecl]p12:
3925///
3926/// When a using-declaration brings names from a base class into a
3927/// derived class scope, member functions in the derived class
3928/// override and/or hide member functions with the same name and
3929/// parameter types in a base class (rather than conflicting).
3930///
3931/// There are two ways to implement this:
3932/// (1) optimistically create shadow decls when they're not hidden
3933/// by existing declarations, or
3934/// (2) don't create any shadow decls (or at least don't make them
3935/// visible) until we've fully parsed/instantiated the class.
3936/// The problem with (1) is that we might have to retroactively remove
3937/// a shadow decl, which requires several O(n) operations because the
3938/// decl structures are (very reasonably) not designed for removal.
3939/// (2) avoids this but is very fiddly and phase-dependent.
3940void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003941 if (Shadow->getDeclName().getNameKind() ==
3942 DeclarationName::CXXConversionFunctionName)
3943 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3944
John McCall84d87672009-12-10 09:41:52 +00003945 // Remove it from the DeclContext...
3946 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003947
John McCall84d87672009-12-10 09:41:52 +00003948 // ...and the scope, if applicable...
3949 if (S) {
John McCall48871652010-08-21 09:40:31 +00003950 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003951 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003952 }
3953
John McCall84d87672009-12-10 09:41:52 +00003954 // ...and the using decl.
3955 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3956
3957 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003958 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003959}
3960
John McCalle61f2ba2009-11-18 02:36:19 +00003961/// Builds a using declaration.
3962///
3963/// \param IsInstantiation - Whether this call arises from an
3964/// instantiation of an unresolved using declaration. We treat
3965/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003966NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3967 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003968 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003969 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003970 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003971 bool IsInstantiation,
3972 bool IsTypeName,
3973 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003974 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003975 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003976 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003977
Anders Carlssonf038fc22009-08-28 05:49:21 +00003978 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003979
Anders Carlsson59140b32009-08-28 03:16:11 +00003980 if (SS.isEmpty()) {
3981 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003982 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003983 }
Mike Stump11289f42009-09-09 15:08:12 +00003984
John McCall84d87672009-12-10 09:41:52 +00003985 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003986 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003987 ForRedeclaration);
3988 Previous.setHideTags(false);
3989 if (S) {
3990 LookupName(Previous, S);
3991
3992 // It is really dumb that we have to do this.
3993 LookupResult::Filter F = Previous.makeFilter();
3994 while (F.hasNext()) {
3995 NamedDecl *D = F.next();
3996 if (!isDeclInScope(D, CurContext, S))
3997 F.erase();
3998 }
3999 F.done();
4000 } else {
4001 assert(IsInstantiation && "no scope in non-instantiation");
4002 assert(CurContext->isRecord() && "scope not record in instantiation");
4003 LookupQualifiedName(Previous, CurContext);
4004 }
4005
Mike Stump11289f42009-09-09 15:08:12 +00004006 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00004007 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4008
John McCall84d87672009-12-10 09:41:52 +00004009 // Check for invalid redeclarations.
4010 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4011 return 0;
4012
4013 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004014 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4015 return 0;
4016
John McCall84c16cf2009-11-12 03:15:40 +00004017 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004018 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00004019 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004020 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004021 // FIXME: not all declaration name kinds are legal here
4022 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4023 UsingLoc, TypenameLoc,
4024 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004025 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004026 } else {
4027 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004028 UsingLoc, SS.getRange(),
4029 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004030 }
John McCallb96ec562009-12-04 22:46:56 +00004031 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004032 D = UsingDecl::Create(Context, CurContext,
4033 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00004034 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004035 }
John McCallb96ec562009-12-04 22:46:56 +00004036 D->setAccess(AS);
4037 CurContext->addDecl(D);
4038
4039 if (!LookupContext) return D;
4040 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004041
John McCall0b66eb32010-05-01 00:40:08 +00004042 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004043 UD->setInvalidDecl();
4044 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004045 }
4046
John McCall3969e302009-12-08 07:46:18 +00004047 // Look up the target name.
4048
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004049 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004050
John McCall3969e302009-12-08 07:46:18 +00004051 // Unlike most lookups, we don't always want to hide tag
4052 // declarations: tag names are visible through the using declaration
4053 // even if hidden by ordinary names, *except* in a dependent context
4054 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004055 if (!IsInstantiation)
4056 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004057
John McCall27b18f82009-11-17 02:14:36 +00004058 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004059
John McCall9f3059a2009-10-09 21:13:30 +00004060 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004061 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004062 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004063 UD->setInvalidDecl();
4064 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004065 }
4066
John McCallb96ec562009-12-04 22:46:56 +00004067 if (R.isAmbiguous()) {
4068 UD->setInvalidDecl();
4069 return UD;
4070 }
Mike Stump11289f42009-09-09 15:08:12 +00004071
John McCalle61f2ba2009-11-18 02:36:19 +00004072 if (IsTypeName) {
4073 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004074 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004075 Diag(IdentLoc, diag::err_using_typename_non_type);
4076 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4077 Diag((*I)->getUnderlyingDecl()->getLocation(),
4078 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004079 UD->setInvalidDecl();
4080 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004081 }
4082 } else {
4083 // If we asked for a non-typename and we got a type, error out,
4084 // but only if this is an instantiation of an unresolved using
4085 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004086 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004087 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4088 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004089 UD->setInvalidDecl();
4090 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004091 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004092 }
4093
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004094 // C++0x N2914 [namespace.udecl]p6:
4095 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004096 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004097 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4098 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004099 UD->setInvalidDecl();
4100 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004101 }
Mike Stump11289f42009-09-09 15:08:12 +00004102
John McCall84d87672009-12-10 09:41:52 +00004103 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4104 if (!CheckUsingShadowDecl(UD, *I, Previous))
4105 BuildUsingShadowDecl(S, UD, *I);
4106 }
John McCall3f746822009-11-17 05:59:44 +00004107
4108 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004109}
4110
John McCall84d87672009-12-10 09:41:52 +00004111/// Checks that the given using declaration is not an invalid
4112/// redeclaration. Note that this is checking only for the using decl
4113/// itself, not for any ill-formedness among the UsingShadowDecls.
4114bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4115 bool isTypeName,
4116 const CXXScopeSpec &SS,
4117 SourceLocation NameLoc,
4118 const LookupResult &Prev) {
4119 // C++03 [namespace.udecl]p8:
4120 // C++0x [namespace.udecl]p10:
4121 // A using-declaration is a declaration and can therefore be used
4122 // repeatedly where (and only where) multiple declarations are
4123 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004124 //
John McCall032092f2010-11-29 18:01:58 +00004125 // That's in non-member contexts.
4126 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004127 return false;
4128
4129 NestedNameSpecifier *Qual
4130 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4131
4132 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4133 NamedDecl *D = *I;
4134
4135 bool DTypename;
4136 NestedNameSpecifier *DQual;
4137 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4138 DTypename = UD->isTypeName();
4139 DQual = UD->getTargetNestedNameDecl();
4140 } else if (UnresolvedUsingValueDecl *UD
4141 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4142 DTypename = false;
4143 DQual = UD->getTargetNestedNameSpecifier();
4144 } else if (UnresolvedUsingTypenameDecl *UD
4145 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4146 DTypename = true;
4147 DQual = UD->getTargetNestedNameSpecifier();
4148 } else continue;
4149
4150 // using decls differ if one says 'typename' and the other doesn't.
4151 // FIXME: non-dependent using decls?
4152 if (isTypeName != DTypename) continue;
4153
4154 // using decls differ if they name different scopes (but note that
4155 // template instantiation can cause this check to trigger when it
4156 // didn't before instantiation).
4157 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4158 Context.getCanonicalNestedNameSpecifier(DQual))
4159 continue;
4160
4161 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004162 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004163 return true;
4164 }
4165
4166 return false;
4167}
4168
John McCall3969e302009-12-08 07:46:18 +00004169
John McCallb96ec562009-12-04 22:46:56 +00004170/// Checks that the given nested-name qualifier used in a using decl
4171/// in the current context is appropriately related to the current
4172/// scope. If an error is found, diagnoses it and returns true.
4173bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4174 const CXXScopeSpec &SS,
4175 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004176 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004177
John McCall3969e302009-12-08 07:46:18 +00004178 if (!CurContext->isRecord()) {
4179 // C++03 [namespace.udecl]p3:
4180 // C++0x [namespace.udecl]p8:
4181 // A using-declaration for a class member shall be a member-declaration.
4182
4183 // If we weren't able to compute a valid scope, it must be a
4184 // dependent class scope.
4185 if (!NamedContext || NamedContext->isRecord()) {
4186 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4187 << SS.getRange();
4188 return true;
4189 }
4190
4191 // Otherwise, everything is known to be fine.
4192 return false;
4193 }
4194
4195 // The current scope is a record.
4196
4197 // If the named context is dependent, we can't decide much.
4198 if (!NamedContext) {
4199 // FIXME: in C++0x, we can diagnose if we can prove that the
4200 // nested-name-specifier does not refer to a base class, which is
4201 // still possible in some cases.
4202
4203 // Otherwise we have to conservatively report that things might be
4204 // okay.
4205 return false;
4206 }
4207
4208 if (!NamedContext->isRecord()) {
4209 // Ideally this would point at the last name in the specifier,
4210 // but we don't have that level of source info.
4211 Diag(SS.getRange().getBegin(),
4212 diag::err_using_decl_nested_name_specifier_is_not_class)
4213 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4214 return true;
4215 }
4216
Douglas Gregor7c842292010-12-21 07:41:49 +00004217 if (!NamedContext->isDependentContext() &&
4218 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4219 return true;
4220
John McCall3969e302009-12-08 07:46:18 +00004221 if (getLangOptions().CPlusPlus0x) {
4222 // C++0x [namespace.udecl]p3:
4223 // In a using-declaration used as a member-declaration, the
4224 // nested-name-specifier shall name a base class of the class
4225 // being defined.
4226
4227 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4228 cast<CXXRecordDecl>(NamedContext))) {
4229 if (CurContext == NamedContext) {
4230 Diag(NameLoc,
4231 diag::err_using_decl_nested_name_specifier_is_current_class)
4232 << SS.getRange();
4233 return true;
4234 }
4235
4236 Diag(SS.getRange().getBegin(),
4237 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4238 << (NestedNameSpecifier*) SS.getScopeRep()
4239 << cast<CXXRecordDecl>(CurContext)
4240 << SS.getRange();
4241 return true;
4242 }
4243
4244 return false;
4245 }
4246
4247 // C++03 [namespace.udecl]p4:
4248 // A using-declaration used as a member-declaration shall refer
4249 // to a member of a base class of the class being defined [etc.].
4250
4251 // Salient point: SS doesn't have to name a base class as long as
4252 // lookup only finds members from base classes. Therefore we can
4253 // diagnose here only if we can prove that that can't happen,
4254 // i.e. if the class hierarchies provably don't intersect.
4255
4256 // TODO: it would be nice if "definitely valid" results were cached
4257 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4258 // need to be repeated.
4259
4260 struct UserData {
4261 llvm::DenseSet<const CXXRecordDecl*> Bases;
4262
4263 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4264 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4265 Data->Bases.insert(Base);
4266 return true;
4267 }
4268
4269 bool hasDependentBases(const CXXRecordDecl *Class) {
4270 return !Class->forallBases(collect, this);
4271 }
4272
4273 /// Returns true if the base is dependent or is one of the
4274 /// accumulated base classes.
4275 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4276 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4277 return !Data->Bases.count(Base);
4278 }
4279
4280 bool mightShareBases(const CXXRecordDecl *Class) {
4281 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4282 }
4283 };
4284
4285 UserData Data;
4286
4287 // Returns false if we find a dependent base.
4288 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4289 return false;
4290
4291 // Returns false if the class has a dependent base or if it or one
4292 // of its bases is present in the base set of the current context.
4293 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4294 return false;
4295
4296 Diag(SS.getRange().getBegin(),
4297 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4298 << (NestedNameSpecifier*) SS.getScopeRep()
4299 << cast<CXXRecordDecl>(CurContext)
4300 << SS.getRange();
4301
4302 return true;
John McCallb96ec562009-12-04 22:46:56 +00004303}
4304
John McCall48871652010-08-21 09:40:31 +00004305Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004306 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004307 SourceLocation AliasLoc,
4308 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004309 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004310 SourceLocation IdentLoc,
4311 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004312
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004313 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004314 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4315 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004316
Anders Carlssondca83c42009-03-28 06:23:46 +00004317 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004318 NamedDecl *PrevDecl
4319 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4320 ForRedeclaration);
4321 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4322 PrevDecl = 0;
4323
4324 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004325 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004326 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004327 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004328 // FIXME: At some point, we'll want to create the (redundant)
4329 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004330 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004331 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004332 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004333 }
Mike Stump11289f42009-09-09 15:08:12 +00004334
Anders Carlssondca83c42009-03-28 06:23:46 +00004335 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4336 diag::err_redefinition_different_kind;
4337 Diag(AliasLoc, DiagID) << Alias;
4338 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004339 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004340 }
4341
John McCall27b18f82009-11-17 02:14:36 +00004342 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004343 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004344
John McCall9f3059a2009-10-09 21:13:30 +00004345 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004346 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4347 CTC_NoKeywords, 0)) {
4348 if (R.getAsSingle<NamespaceDecl>() ||
4349 R.getAsSingle<NamespaceAliasDecl>()) {
4350 if (DeclContext *DC = computeDeclContext(SS, false))
4351 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4352 << Ident << DC << Corrected << SS.getRange()
4353 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4354 else
4355 Diag(IdentLoc, diag::err_using_directive_suggest)
4356 << Ident << Corrected
4357 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4358
4359 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4360 << Corrected;
4361
4362 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004363 } else {
4364 R.clear();
4365 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004366 }
4367 }
4368
4369 if (R.empty()) {
4370 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004371 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004372 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004373 }
Mike Stump11289f42009-09-09 15:08:12 +00004374
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004375 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004376 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4377 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004378 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004379 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004380
John McCalld8d0d432010-02-16 06:53:13 +00004381 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004382 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004383}
4384
Douglas Gregora57478e2010-05-01 15:04:51 +00004385namespace {
4386 /// \brief Scoped object used to handle the state changes required in Sema
4387 /// to implicitly define the body of a C++ member function;
4388 class ImplicitlyDefinedFunctionScope {
4389 Sema &S;
4390 DeclContext *PreviousContext;
4391
4392 public:
4393 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4394 : S(S), PreviousContext(S.CurContext)
4395 {
4396 S.CurContext = Method;
4397 S.PushFunctionScope();
4398 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4399 }
4400
4401 ~ImplicitlyDefinedFunctionScope() {
4402 S.PopExpressionEvaluationContext();
4403 S.PopFunctionOrBlockScope();
4404 S.CurContext = PreviousContext;
4405 }
4406 };
4407}
4408
Sebastian Redlc15c3262010-09-13 22:02:47 +00004409static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4410 CXXRecordDecl *D) {
4411 ASTContext &Context = Self.Context;
4412 QualType ClassType = Context.getTypeDeclType(D);
4413 DeclarationName ConstructorName
4414 = Context.DeclarationNames.getCXXConstructorName(
4415 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4416
4417 DeclContext::lookup_const_iterator Con, ConEnd;
4418 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4419 Con != ConEnd; ++Con) {
4420 // FIXME: In C++0x, a constructor template can be a default constructor.
4421 if (isa<FunctionTemplateDecl>(*Con))
4422 continue;
4423
4424 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4425 if (Constructor->isDefaultConstructor())
4426 return Constructor;
4427 }
4428 return 0;
4429}
4430
Douglas Gregor0be31a22010-07-02 17:43:08 +00004431CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4432 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004433 // C++ [class.ctor]p5:
4434 // A default constructor for a class X is a constructor of class X
4435 // that can be called without an argument. If there is no
4436 // user-declared constructor for class X, a default constructor is
4437 // implicitly declared. An implicitly-declared default constructor
4438 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004439 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4440 "Should not build implicit default constructor!");
4441
Douglas Gregor6d880b12010-07-01 22:31:05 +00004442 // C++ [except.spec]p14:
4443 // An implicitly declared special member function (Clause 12) shall have an
4444 // exception-specification. [...]
4445 ImplicitExceptionSpecification ExceptSpec(Context);
4446
4447 // Direct base-class destructors.
4448 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4449 BEnd = ClassDecl->bases_end();
4450 B != BEnd; ++B) {
4451 if (B->isVirtual()) // Handled below.
4452 continue;
4453
Douglas Gregor9672f922010-07-03 00:47:00 +00004454 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4455 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4456 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4457 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004458 else if (CXXConstructorDecl *Constructor
4459 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004460 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004461 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004462 }
4463
4464 // Virtual base-class destructors.
4465 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4466 BEnd = ClassDecl->vbases_end();
4467 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004468 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4469 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4470 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4471 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4472 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004473 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004474 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004475 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004476 }
4477
4478 // Field destructors.
4479 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4480 FEnd = ClassDecl->field_end();
4481 F != FEnd; ++F) {
4482 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004483 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4484 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4485 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4486 ExceptSpec.CalledDecl(
4487 DeclareImplicitDefaultConstructor(FieldClassDecl));
4488 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004489 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004490 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004491 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004492 }
John McCalldb40c7f2010-12-14 08:05:40 +00004493
4494 FunctionProtoType::ExtProtoInfo EPI;
4495 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4496 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4497 EPI.NumExceptions = ExceptSpec.size();
4498 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004499
4500 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004501 CanQualType ClassType
4502 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4503 DeclarationName Name
4504 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004505 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004506 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004507 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004508 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004509 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004510 /*TInfo=*/0,
4511 /*isExplicit=*/false,
4512 /*isInline=*/true,
4513 /*isImplicitlyDeclared=*/true);
4514 DefaultCon->setAccess(AS_public);
4515 DefaultCon->setImplicit();
4516 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004517
4518 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004519 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4520
Douglas Gregor0be31a22010-07-02 17:43:08 +00004521 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004522 PushOnScopeChains(DefaultCon, S, false);
4523 ClassDecl->addDecl(DefaultCon);
4524
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004525 return DefaultCon;
4526}
4527
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004528void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4529 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004530 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004531 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004532 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004533
Anders Carlsson423f5d82010-04-23 16:04:08 +00004534 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004535 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004536
Douglas Gregora57478e2010-05-01 15:04:51 +00004537 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004538 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004539 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004540 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004541 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004542 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004543 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004544 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004545 }
Douglas Gregor73193272010-09-20 16:48:21 +00004546
4547 SourceLocation Loc = Constructor->getLocation();
4548 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4549
4550 Constructor->setUsed();
4551 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004552}
4553
Douglas Gregor0be31a22010-07-02 17:43:08 +00004554CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004555 // C++ [class.dtor]p2:
4556 // If a class has no user-declared destructor, a destructor is
4557 // declared implicitly. An implicitly-declared destructor is an
4558 // inline public member of its class.
4559
4560 // C++ [except.spec]p14:
4561 // An implicitly declared special member function (Clause 12) shall have
4562 // an exception-specification.
4563 ImplicitExceptionSpecification ExceptSpec(Context);
4564
4565 // Direct base-class destructors.
4566 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4567 BEnd = ClassDecl->bases_end();
4568 B != BEnd; ++B) {
4569 if (B->isVirtual()) // Handled below.
4570 continue;
4571
4572 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4573 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004574 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004575 }
4576
4577 // Virtual base-class destructors.
4578 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4579 BEnd = ClassDecl->vbases_end();
4580 B != BEnd; ++B) {
4581 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4582 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004583 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004584 }
4585
4586 // Field destructors.
4587 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4588 FEnd = ClassDecl->field_end();
4589 F != FEnd; ++F) {
4590 if (const RecordType *RecordTy
4591 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4592 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004593 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004594 }
4595
Douglas Gregor7454c562010-07-02 20:37:36 +00004596 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004597 FunctionProtoType::ExtProtoInfo EPI;
4598 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4599 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4600 EPI.NumExceptions = ExceptSpec.size();
4601 EPI.Exceptions = ExceptSpec.data();
4602 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004603
4604 CanQualType ClassType
4605 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4606 DeclarationName Name
4607 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004608 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004609 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004610 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004611 /*isInline=*/true,
4612 /*isImplicitlyDeclared=*/true);
4613 Destructor->setAccess(AS_public);
4614 Destructor->setImplicit();
4615 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004616
4617 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004618 ++ASTContext::NumImplicitDestructorsDeclared;
4619
4620 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004621 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004622 PushOnScopeChains(Destructor, S, false);
4623 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004624
4625 // This could be uniqued if it ever proves significant.
4626 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4627
4628 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004629
Douglas Gregorf1203042010-07-01 19:09:28 +00004630 return Destructor;
4631}
4632
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004633void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004634 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004635 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004636 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004637 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004638 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004639
Douglas Gregor54818f02010-05-12 16:39:35 +00004640 if (Destructor->isInvalidDecl())
4641 return;
4642
Douglas Gregora57478e2010-05-01 15:04:51 +00004643 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004644
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004645 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004646 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4647 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004648
Douglas Gregor54818f02010-05-12 16:39:35 +00004649 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004650 Diag(CurrentLocation, diag::note_member_synthesized_at)
4651 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4652
4653 Destructor->setInvalidDecl();
4654 return;
4655 }
4656
Douglas Gregor73193272010-09-20 16:48:21 +00004657 SourceLocation Loc = Destructor->getLocation();
4658 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4659
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004660 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004661 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004662}
4663
Douglas Gregorb139cd52010-05-01 20:49:11 +00004664/// \brief Builds a statement that copies the given entity from \p From to
4665/// \c To.
4666///
4667/// This routine is used to copy the members of a class with an
4668/// implicitly-declared copy assignment operator. When the entities being
4669/// copied are arrays, this routine builds for loops to copy them.
4670///
4671/// \param S The Sema object used for type-checking.
4672///
4673/// \param Loc The location where the implicit copy is being generated.
4674///
4675/// \param T The type of the expressions being copied. Both expressions must
4676/// have this type.
4677///
4678/// \param To The expression we are copying to.
4679///
4680/// \param From The expression we are copying from.
4681///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004682/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4683/// Otherwise, it's a non-static member subobject.
4684///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004685/// \param Depth Internal parameter recording the depth of the recursion.
4686///
4687/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004688static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004689BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004690 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004691 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004692 // C++0x [class.copy]p30:
4693 // Each subobject is assigned in the manner appropriate to its type:
4694 //
4695 // - if the subobject is of class type, the copy assignment operator
4696 // for the class is used (as if by explicit qualification; that is,
4697 // ignoring any possible virtual overriding functions in more derived
4698 // classes);
4699 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4700 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4701
4702 // Look for operator=.
4703 DeclarationName Name
4704 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4705 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4706 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4707
4708 // Filter out any result that isn't a copy-assignment operator.
4709 LookupResult::Filter F = OpLookup.makeFilter();
4710 while (F.hasNext()) {
4711 NamedDecl *D = F.next();
4712 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4713 if (Method->isCopyAssignmentOperator())
4714 continue;
4715
4716 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004717 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004718 F.done();
4719
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004720 // Suppress the protected check (C++ [class.protected]) for each of the
4721 // assignment operators we found. This strange dance is required when
4722 // we're assigning via a base classes's copy-assignment operator. To
4723 // ensure that we're getting the right base class subobject (without
4724 // ambiguities), we need to cast "this" to that subobject type; to
4725 // ensure that we don't go through the virtual call mechanism, we need
4726 // to qualify the operator= name with the base class (see below). However,
4727 // this means that if the base class has a protected copy assignment
4728 // operator, the protected member access check will fail. So, we
4729 // rewrite "protected" access to "public" access in this case, since we
4730 // know by construction that we're calling from a derived class.
4731 if (CopyingBaseSubobject) {
4732 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4733 L != LEnd; ++L) {
4734 if (L.getAccess() == AS_protected)
4735 L.setAccess(AS_public);
4736 }
4737 }
4738
Douglas Gregorb139cd52010-05-01 20:49:11 +00004739 // Create the nested-name-specifier that will be used to qualify the
4740 // reference to operator=; this is required to suppress the virtual
4741 // call mechanism.
4742 CXXScopeSpec SS;
4743 SS.setRange(Loc);
4744 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4745 T.getTypePtr()));
4746
4747 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004748 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004749 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004750 /*FirstQualifierInScope=*/0, OpLookup,
4751 /*TemplateArgs=*/0,
4752 /*SuppressQualifierCheck=*/true);
4753 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004754 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004755
4756 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004757
John McCalldadc5752010-08-24 06:29:42 +00004758 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004759 OpEqualRef.takeAs<Expr>(),
4760 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004761 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004762 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004763
4764 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004765 }
John McCallab8c2732010-03-16 06:11:48 +00004766
Douglas Gregorb139cd52010-05-01 20:49:11 +00004767 // - if the subobject is of scalar type, the built-in assignment
4768 // operator is used.
4769 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4770 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004771 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004772 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004773 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004774
4775 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004776 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004777
4778 // - if the subobject is an array, each element is assigned, in the
4779 // manner appropriate to the element type;
4780
4781 // Construct a loop over the array bounds, e.g.,
4782 //
4783 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4784 //
4785 // that will copy each of the array elements.
4786 QualType SizeType = S.Context.getSizeType();
4787
4788 // Create the iteration variable.
4789 IdentifierInfo *IterationVarName = 0;
4790 {
4791 llvm::SmallString<8> Str;
4792 llvm::raw_svector_ostream OS(Str);
4793 OS << "__i" << Depth;
4794 IterationVarName = &S.Context.Idents.get(OS.str());
4795 }
4796 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4797 IterationVarName, SizeType,
4798 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004799 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004800
4801 // Initialize the iteration variable to zero.
4802 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004803 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004804
4805 // Create a reference to the iteration variable; we'll use this several
4806 // times throughout.
4807 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004808 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004809 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4810
4811 // Create the DeclStmt that holds the iteration variable.
4812 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4813
4814 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004815 llvm::APInt Upper
4816 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004817 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004818 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004819 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4820 BO_NE, S.Context.BoolTy,
4821 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004822
4823 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004824 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004825 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4826 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004827
4828 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004829 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4830 IterationVarRef, Loc));
4831 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4832 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004833
4834 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004835 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4836 To, From, CopyingBaseSubobject,
4837 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004838 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004839 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004840
4841 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004842 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004843 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004844 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004845 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004846}
4847
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004848/// \brief Determine whether the given class has a copy assignment operator
4849/// that accepts a const-qualified argument.
4850static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4851 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4852
4853 if (!Class->hasDeclaredCopyAssignment())
4854 S.DeclareImplicitCopyAssignment(Class);
4855
4856 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4857 DeclarationName OpName
4858 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4859
4860 DeclContext::lookup_const_iterator Op, OpEnd;
4861 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4862 // C++ [class.copy]p9:
4863 // A user-declared copy assignment operator is a non-static non-template
4864 // member function of class X with exactly one parameter of type X, X&,
4865 // const X&, volatile X& or const volatile X&.
4866 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4867 if (!Method)
4868 continue;
4869
4870 if (Method->isStatic())
4871 continue;
4872 if (Method->getPrimaryTemplate())
4873 continue;
4874 const FunctionProtoType *FnType =
4875 Method->getType()->getAs<FunctionProtoType>();
4876 assert(FnType && "Overloaded operator has no prototype.");
4877 // Don't assert on this; an invalid decl might have been left in the AST.
4878 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4879 continue;
4880 bool AcceptsConst = true;
4881 QualType ArgType = FnType->getArgType(0);
4882 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4883 ArgType = Ref->getPointeeType();
4884 // Is it a non-const lvalue reference?
4885 if (!ArgType.isConstQualified())
4886 AcceptsConst = false;
4887 }
4888 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4889 continue;
4890
4891 // We have a single argument of type cv X or cv X&, i.e. we've found the
4892 // copy assignment operator. Return whether it accepts const arguments.
4893 return AcceptsConst;
4894 }
4895 assert(Class->isInvalidDecl() &&
4896 "No copy assignment operator declared in valid code.");
4897 return false;
4898}
4899
Douglas Gregor0be31a22010-07-02 17:43:08 +00004900CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004901 // Note: The following rules are largely analoguous to the copy
4902 // constructor rules. Note that virtual bases are not taken into account
4903 // for determining the argument type of the operator. Note also that
4904 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004905
4906
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004907 // C++ [class.copy]p10:
4908 // If the class definition does not explicitly declare a copy
4909 // assignment operator, one is declared implicitly.
4910 // The implicitly-defined copy assignment operator for a class X
4911 // will have the form
4912 //
4913 // X& X::operator=(const X&)
4914 //
4915 // if
4916 bool HasConstCopyAssignment = true;
4917
4918 // -- each direct base class B of X has a copy assignment operator
4919 // whose parameter is of type const B&, const volatile B& or B,
4920 // and
4921 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4922 BaseEnd = ClassDecl->bases_end();
4923 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4924 assert(!Base->getType()->isDependentType() &&
4925 "Cannot generate implicit members for class with dependent bases.");
4926 const CXXRecordDecl *BaseClassDecl
4927 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004928 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004929 }
4930
4931 // -- for all the nonstatic data members of X that are of a class
4932 // type M (or array thereof), each such class type has a copy
4933 // assignment operator whose parameter is of type const M&,
4934 // const volatile M& or M.
4935 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4936 FieldEnd = ClassDecl->field_end();
4937 HasConstCopyAssignment && Field != FieldEnd;
4938 ++Field) {
4939 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4940 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4941 const CXXRecordDecl *FieldClassDecl
4942 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004943 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004944 }
4945 }
4946
4947 // Otherwise, the implicitly declared copy assignment operator will
4948 // have the form
4949 //
4950 // X& X::operator=(X&)
4951 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4952 QualType RetType = Context.getLValueReferenceType(ArgType);
4953 if (HasConstCopyAssignment)
4954 ArgType = ArgType.withConst();
4955 ArgType = Context.getLValueReferenceType(ArgType);
4956
Douglas Gregor68e11362010-07-01 17:48:08 +00004957 // C++ [except.spec]p14:
4958 // An implicitly declared special member function (Clause 12) shall have an
4959 // exception-specification. [...]
4960 ImplicitExceptionSpecification ExceptSpec(Context);
4961 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4962 BaseEnd = ClassDecl->bases_end();
4963 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004964 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004965 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004966
4967 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4968 DeclareImplicitCopyAssignment(BaseClassDecl);
4969
Douglas Gregor68e11362010-07-01 17:48:08 +00004970 if (CXXMethodDecl *CopyAssign
4971 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4972 ExceptSpec.CalledDecl(CopyAssign);
4973 }
4974 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4975 FieldEnd = ClassDecl->field_end();
4976 Field != FieldEnd;
4977 ++Field) {
4978 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4979 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004980 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004981 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004982
4983 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4984 DeclareImplicitCopyAssignment(FieldClassDecl);
4985
Douglas Gregor68e11362010-07-01 17:48:08 +00004986 if (CXXMethodDecl *CopyAssign
4987 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4988 ExceptSpec.CalledDecl(CopyAssign);
4989 }
4990 }
4991
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004992 // An implicitly-declared copy assignment operator is an inline public
4993 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004994 FunctionProtoType::ExtProtoInfo EPI;
4995 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4996 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4997 EPI.NumExceptions = ExceptSpec.size();
4998 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004999 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005000 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005001 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005002 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005003 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005004 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005005 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005006 /*isInline=*/true);
5007 CopyAssignment->setAccess(AS_public);
5008 CopyAssignment->setImplicit();
5009 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005010
5011 // Add the parameter to the operator.
5012 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5013 ClassDecl->getLocation(),
5014 /*Id=*/0,
5015 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005016 SC_None,
5017 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005018 CopyAssignment->setParams(&FromParam, 1);
5019
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005020 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005021 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5022
Douglas Gregor0be31a22010-07-02 17:43:08 +00005023 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005024 PushOnScopeChains(CopyAssignment, S, false);
5025 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005026
5027 AddOverriddenMethods(ClassDecl, CopyAssignment);
5028 return CopyAssignment;
5029}
5030
Douglas Gregorb139cd52010-05-01 20:49:11 +00005031void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5032 CXXMethodDecl *CopyAssignOperator) {
5033 assert((CopyAssignOperator->isImplicit() &&
5034 CopyAssignOperator->isOverloadedOperator() &&
5035 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005036 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005037 "DefineImplicitCopyAssignment called for wrong function");
5038
5039 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5040
5041 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5042 CopyAssignOperator->setInvalidDecl();
5043 return;
5044 }
5045
5046 CopyAssignOperator->setUsed();
5047
5048 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005049 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005050
5051 // C++0x [class.copy]p30:
5052 // The implicitly-defined or explicitly-defaulted copy assignment operator
5053 // for a non-union class X performs memberwise copy assignment of its
5054 // subobjects. The direct base classes of X are assigned first, in the
5055 // order of their declaration in the base-specifier-list, and then the
5056 // immediate non-static data members of X are assigned, in the order in
5057 // which they were declared in the class definition.
5058
5059 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005060 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005061
5062 // The parameter for the "other" object, which we are copying from.
5063 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5064 Qualifiers OtherQuals = Other->getType().getQualifiers();
5065 QualType OtherRefType = Other->getType();
5066 if (const LValueReferenceType *OtherRef
5067 = OtherRefType->getAs<LValueReferenceType>()) {
5068 OtherRefType = OtherRef->getPointeeType();
5069 OtherQuals = OtherRefType.getQualifiers();
5070 }
5071
5072 // Our location for everything implicitly-generated.
5073 SourceLocation Loc = CopyAssignOperator->getLocation();
5074
5075 // Construct a reference to the "other" object. We'll be using this
5076 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005077 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005078 assert(OtherRef && "Reference to parameter cannot fail!");
5079
5080 // Construct the "this" pointer. We'll be using this throughout the generated
5081 // ASTs.
5082 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5083 assert(This && "Reference to this cannot fail!");
5084
5085 // Assign base classes.
5086 bool Invalid = false;
5087 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5088 E = ClassDecl->bases_end(); Base != E; ++Base) {
5089 // Form the assignment:
5090 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5091 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005092 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005093 Invalid = true;
5094 continue;
5095 }
5096
John McCallcf142162010-08-07 06:22:56 +00005097 CXXCastPath BasePath;
5098 BasePath.push_back(Base);
5099
Douglas Gregorb139cd52010-05-01 20:49:11 +00005100 // Construct the "from" expression, which is an implicit cast to the
5101 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005102 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005103 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005104 CK_UncheckedDerivedToBase,
5105 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005106
5107 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005108 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005109
5110 // Implicitly cast "this" to the appropriately-qualified base type.
5111 Expr *ToE = To.takeAs<Expr>();
5112 ImpCastExprToType(ToE,
5113 Context.getCVRQualifiedType(BaseType,
5114 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005115 CK_UncheckedDerivedToBase,
5116 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005117 To = Owned(ToE);
5118
5119 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005120 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005121 To.get(), From,
5122 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005123 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005124 Diag(CurrentLocation, diag::note_member_synthesized_at)
5125 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5126 CopyAssignOperator->setInvalidDecl();
5127 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005128 }
5129
5130 // Success! Record the copy.
5131 Statements.push_back(Copy.takeAs<Expr>());
5132 }
5133
5134 // \brief Reference to the __builtin_memcpy function.
5135 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005136 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005137 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005138
5139 // Assign non-static members.
5140 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5141 FieldEnd = ClassDecl->field_end();
5142 Field != FieldEnd; ++Field) {
5143 // Check for members of reference type; we can't copy those.
5144 if (Field->getType()->isReferenceType()) {
5145 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5146 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5147 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005148 Diag(CurrentLocation, diag::note_member_synthesized_at)
5149 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005150 Invalid = true;
5151 continue;
5152 }
5153
5154 // Check for members of const-qualified, non-class type.
5155 QualType BaseType = Context.getBaseElementType(Field->getType());
5156 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5157 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5158 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5159 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005160 Diag(CurrentLocation, diag::note_member_synthesized_at)
5161 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005162 Invalid = true;
5163 continue;
5164 }
5165
5166 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005167 if (FieldType->isIncompleteArrayType()) {
5168 assert(ClassDecl->hasFlexibleArrayMember() &&
5169 "Incomplete array type is not valid");
5170 continue;
5171 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005172
5173 // Build references to the field in the object we're copying from and to.
5174 CXXScopeSpec SS; // Intentionally empty
5175 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5176 LookupMemberName);
5177 MemberLookup.addDecl(*Field);
5178 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005179 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005180 Loc, /*IsArrow=*/false,
5181 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005182 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005183 Loc, /*IsArrow=*/true,
5184 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005185 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5186 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5187
5188 // If the field should be copied with __builtin_memcpy rather than via
5189 // explicit assignments, do so. This optimization only applies for arrays
5190 // of scalars and arrays of class type with trivial copy-assignment
5191 // operators.
5192 if (FieldType->isArrayType() &&
5193 (!BaseType->isRecordType() ||
5194 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5195 ->hasTrivialCopyAssignment())) {
5196 // Compute the size of the memory buffer to be copied.
5197 QualType SizeType = Context.getSizeType();
5198 llvm::APInt Size(Context.getTypeSize(SizeType),
5199 Context.getTypeSizeInChars(BaseType).getQuantity());
5200 for (const ConstantArrayType *Array
5201 = Context.getAsConstantArrayType(FieldType);
5202 Array;
5203 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005204 llvm::APInt ArraySize
5205 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005206 Size *= ArraySize;
5207 }
5208
5209 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005210 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5211 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005212
5213 bool NeedsCollectableMemCpy =
5214 (BaseType->isRecordType() &&
5215 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5216
5217 if (NeedsCollectableMemCpy) {
5218 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005219 // Create a reference to the __builtin_objc_memmove_collectable function.
5220 LookupResult R(*this,
5221 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005222 Loc, LookupOrdinaryName);
5223 LookupName(R, TUScope, true);
5224
5225 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5226 if (!CollectableMemCpy) {
5227 // Something went horribly wrong earlier, and we will have
5228 // complained about it.
5229 Invalid = true;
5230 continue;
5231 }
5232
5233 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5234 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005235 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005236 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5237 }
5238 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005239 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005240 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005241 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5242 LookupOrdinaryName);
5243 LookupName(R, TUScope, true);
5244
5245 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5246 if (!BuiltinMemCpy) {
5247 // Something went horribly wrong earlier, and we will have complained
5248 // about it.
5249 Invalid = true;
5250 continue;
5251 }
5252
5253 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5254 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005255 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005256 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5257 }
5258
John McCall37ad5512010-08-23 06:44:23 +00005259 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005260 CallArgs.push_back(To.takeAs<Expr>());
5261 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005262 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005263 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005264 if (NeedsCollectableMemCpy)
5265 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005266 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005267 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005268 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005269 else
5270 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005271 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005272 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005273 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005274
Douglas Gregorb139cd52010-05-01 20:49:11 +00005275 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5276 Statements.push_back(Call.takeAs<Expr>());
5277 continue;
5278 }
5279
5280 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005281 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005282 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005283 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005284 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005285 Diag(CurrentLocation, diag::note_member_synthesized_at)
5286 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5287 CopyAssignOperator->setInvalidDecl();
5288 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005289 }
5290
5291 // Success! Record the copy.
5292 Statements.push_back(Copy.takeAs<Stmt>());
5293 }
5294
5295 if (!Invalid) {
5296 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005297 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005298
John McCalldadc5752010-08-24 06:29:42 +00005299 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005300 if (Return.isInvalid())
5301 Invalid = true;
5302 else {
5303 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005304
5305 if (Trap.hasErrorOccurred()) {
5306 Diag(CurrentLocation, diag::note_member_synthesized_at)
5307 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5308 Invalid = true;
5309 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005310 }
5311 }
5312
5313 if (Invalid) {
5314 CopyAssignOperator->setInvalidDecl();
5315 return;
5316 }
5317
John McCalldadc5752010-08-24 06:29:42 +00005318 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005319 /*isStmtExpr=*/false);
5320 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5321 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005322}
5323
Douglas Gregor0be31a22010-07-02 17:43:08 +00005324CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5325 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005326 // C++ [class.copy]p4:
5327 // If the class definition does not explicitly declare a copy
5328 // constructor, one is declared implicitly.
5329
Douglas Gregor54be3392010-07-01 17:57:27 +00005330 // C++ [class.copy]p5:
5331 // The implicitly-declared copy constructor for a class X will
5332 // have the form
5333 //
5334 // X::X(const X&)
5335 //
5336 // if
5337 bool HasConstCopyConstructor = true;
5338
5339 // -- each direct or virtual base class B of X has a copy
5340 // constructor whose first parameter is of type const B& or
5341 // const volatile B&, and
5342 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5343 BaseEnd = ClassDecl->bases_end();
5344 HasConstCopyConstructor && Base != BaseEnd;
5345 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005346 // Virtual bases are handled below.
5347 if (Base->isVirtual())
5348 continue;
5349
Douglas Gregora6d69502010-07-02 23:41:54 +00005350 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005351 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005352 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5353 DeclareImplicitCopyConstructor(BaseClassDecl);
5354
Douglas Gregorcfe68222010-07-01 18:27:03 +00005355 HasConstCopyConstructor
5356 = BaseClassDecl->hasConstCopyConstructor(Context);
5357 }
5358
5359 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5360 BaseEnd = ClassDecl->vbases_end();
5361 HasConstCopyConstructor && Base != BaseEnd;
5362 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005363 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005364 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005365 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5366 DeclareImplicitCopyConstructor(BaseClassDecl);
5367
Douglas Gregor54be3392010-07-01 17:57:27 +00005368 HasConstCopyConstructor
5369 = BaseClassDecl->hasConstCopyConstructor(Context);
5370 }
5371
5372 // -- for all the nonstatic data members of X that are of a
5373 // class type M (or array thereof), each such class type
5374 // has a copy constructor whose first parameter is of type
5375 // const M& or const volatile M&.
5376 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5377 FieldEnd = ClassDecl->field_end();
5378 HasConstCopyConstructor && Field != FieldEnd;
5379 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005380 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005381 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005382 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005383 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005384 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5385 DeclareImplicitCopyConstructor(FieldClassDecl);
5386
Douglas Gregor54be3392010-07-01 17:57:27 +00005387 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005388 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005389 }
5390 }
5391
5392 // Otherwise, the implicitly declared copy constructor will have
5393 // the form
5394 //
5395 // X::X(X&)
5396 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5397 QualType ArgType = ClassType;
5398 if (HasConstCopyConstructor)
5399 ArgType = ArgType.withConst();
5400 ArgType = Context.getLValueReferenceType(ArgType);
5401
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005402 // C++ [except.spec]p14:
5403 // An implicitly declared special member function (Clause 12) shall have an
5404 // exception-specification. [...]
5405 ImplicitExceptionSpecification ExceptSpec(Context);
5406 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5407 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5408 BaseEnd = ClassDecl->bases_end();
5409 Base != BaseEnd;
5410 ++Base) {
5411 // Virtual bases are handled below.
5412 if (Base->isVirtual())
5413 continue;
5414
Douglas Gregora6d69502010-07-02 23:41:54 +00005415 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005416 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005417 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5418 DeclareImplicitCopyConstructor(BaseClassDecl);
5419
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005420 if (CXXConstructorDecl *CopyConstructor
5421 = BaseClassDecl->getCopyConstructor(Context, Quals))
5422 ExceptSpec.CalledDecl(CopyConstructor);
5423 }
5424 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5425 BaseEnd = ClassDecl->vbases_end();
5426 Base != BaseEnd;
5427 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005428 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005429 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005430 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5431 DeclareImplicitCopyConstructor(BaseClassDecl);
5432
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005433 if (CXXConstructorDecl *CopyConstructor
5434 = BaseClassDecl->getCopyConstructor(Context, Quals))
5435 ExceptSpec.CalledDecl(CopyConstructor);
5436 }
5437 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5438 FieldEnd = ClassDecl->field_end();
5439 Field != FieldEnd;
5440 ++Field) {
5441 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5442 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005443 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005444 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005445 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5446 DeclareImplicitCopyConstructor(FieldClassDecl);
5447
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005448 if (CXXConstructorDecl *CopyConstructor
5449 = FieldClassDecl->getCopyConstructor(Context, Quals))
5450 ExceptSpec.CalledDecl(CopyConstructor);
5451 }
5452 }
5453
Douglas Gregor54be3392010-07-01 17:57:27 +00005454 // An implicitly-declared copy constructor is an inline public
5455 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005456 FunctionProtoType::ExtProtoInfo EPI;
5457 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5458 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5459 EPI.NumExceptions = ExceptSpec.size();
5460 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005461 DeclarationName Name
5462 = Context.DeclarationNames.getCXXConstructorName(
5463 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005464 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005465 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005466 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005467 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005468 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005469 /*TInfo=*/0,
5470 /*isExplicit=*/false,
5471 /*isInline=*/true,
5472 /*isImplicitlyDeclared=*/true);
5473 CopyConstructor->setAccess(AS_public);
5474 CopyConstructor->setImplicit();
5475 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5476
Douglas Gregora6d69502010-07-02 23:41:54 +00005477 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005478 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5479
Douglas Gregor54be3392010-07-01 17:57:27 +00005480 // Add the parameter to the constructor.
5481 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5482 ClassDecl->getLocation(),
5483 /*IdentifierInfo=*/0,
5484 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005485 SC_None,
5486 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005487 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005488 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005489 PushOnScopeChains(CopyConstructor, S, false);
5490 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005491
5492 return CopyConstructor;
5493}
5494
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005495void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5496 CXXConstructorDecl *CopyConstructor,
5497 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005498 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005499 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005500 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005501 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005502
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005503 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005504 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005505
Douglas Gregora57478e2010-05-01 15:04:51 +00005506 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005507 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005508
Alexis Hunt1d792652011-01-08 20:30:50 +00005509 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005510 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005511 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005512 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005513 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005514 } else {
5515 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5516 CopyConstructor->getLocation(),
5517 MultiStmtArg(*this, 0, 0),
5518 /*isStmtExpr=*/false)
5519 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005520 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005521
5522 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005523}
5524
John McCalldadc5752010-08-24 06:29:42 +00005525ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005526Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005527 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005528 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005529 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005530 unsigned ConstructKind,
5531 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005532 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005533
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005534 // C++0x [class.copy]p34:
5535 // When certain criteria are met, an implementation is allowed to
5536 // omit the copy/move construction of a class object, even if the
5537 // copy/move constructor and/or destructor for the object have
5538 // side effects. [...]
5539 // - when a temporary class object that has not been bound to a
5540 // reference (12.2) would be copied/moved to a class object
5541 // with the same cv-unqualified type, the copy/move operation
5542 // can be omitted by constructing the temporary object
5543 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005544 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5545 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005546 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005547 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005548 }
Mike Stump11289f42009-09-09 15:08:12 +00005549
5550 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005551 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005552 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005553}
5554
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005555/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5556/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005557ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005558Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5559 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005560 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005561 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005562 unsigned ConstructKind,
5563 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005564 unsigned NumExprs = ExprArgs.size();
5565 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005566
Douglas Gregor27381f32009-11-23 12:27:39 +00005567 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005568 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005569 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005570 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005571 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5572 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005573}
5574
Mike Stump11289f42009-09-09 15:08:12 +00005575bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005576 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005577 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005578 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005579 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005580 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005581 move(Exprs), false, CXXConstructExpr::CK_Complete,
5582 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005583 if (TempResult.isInvalid())
5584 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005585
Anders Carlsson6eb55572009-08-25 05:12:04 +00005586 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005587 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005588 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005589 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005590 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005591
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005592 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005593}
5594
John McCall03c48482010-02-02 09:10:11 +00005595void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5596 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005597 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005598 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005599 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005600 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005601 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005602 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005603 << VD->getDeclName()
5604 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005605
John McCall386dfc72010-09-18 05:25:11 +00005606 // TODO: this should be re-enabled for static locals by !CXAAtExit
5607 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005608 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005609 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005610}
5611
Mike Stump11289f42009-09-09 15:08:12 +00005612/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005613/// ActOnDeclarator, when a C++ direct initializer is present.
5614/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005615void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005616 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005617 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005618 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005619 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005620
5621 // If there is no declaration, there was an error parsing it. Just ignore
5622 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005623 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005624 return;
Mike Stump11289f42009-09-09 15:08:12 +00005625
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005626 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5627 if (!VDecl) {
5628 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5629 RealDecl->setInvalidDecl();
5630 return;
5631 }
5632
Douglas Gregor402250f2009-08-26 21:14:46 +00005633 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005634 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005635 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5636 //
5637 // Clients that want to distinguish between the two forms, can check for
5638 // direct initializer using VarDecl::hasCXXDirectInitializer().
5639 // A major benefit is that clients that don't particularly care about which
5640 // exactly form was it (like the CodeGen) can handle both cases without
5641 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005642
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005643 // C++ 8.5p11:
5644 // The form of initialization (using parentheses or '=') is generally
5645 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005646 // class type.
5647
Douglas Gregor50dc2192010-02-11 22:55:30 +00005648 if (!VDecl->getType()->isDependentType() &&
5649 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005650 diag::err_typecheck_decl_incomplete_type)) {
5651 VDecl->setInvalidDecl();
5652 return;
5653 }
5654
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005655 // The variable can not have an abstract class type.
5656 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5657 diag::err_abstract_type_in_decl,
5658 AbstractVariableType))
5659 VDecl->setInvalidDecl();
5660
Sebastian Redl5ca79842010-02-01 20:16:42 +00005661 const VarDecl *Def;
5662 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005663 Diag(VDecl->getLocation(), diag::err_redefinition)
5664 << VDecl->getDeclName();
5665 Diag(Def->getLocation(), diag::note_previous_definition);
5666 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005667 return;
5668 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005669
Douglas Gregorf0f83692010-08-24 05:27:49 +00005670 // C++ [class.static.data]p4
5671 // If a static data member is of const integral or const
5672 // enumeration type, its declaration in the class definition can
5673 // specify a constant-initializer which shall be an integral
5674 // constant expression (5.19). In that case, the member can appear
5675 // in integral constant expressions. The member shall still be
5676 // defined in a namespace scope if it is used in the program and the
5677 // namespace scope definition shall not contain an initializer.
5678 //
5679 // We already performed a redefinition check above, but for static
5680 // data members we also need to check whether there was an in-class
5681 // declaration with an initializer.
5682 const VarDecl* PrevInit = 0;
5683 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5684 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5685 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5686 return;
5687 }
5688
Douglas Gregor71f39c92010-12-16 01:31:22 +00005689 bool IsDependent = false;
5690 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5691 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5692 VDecl->setInvalidDecl();
5693 return;
5694 }
5695
5696 if (Exprs.get()[I]->isTypeDependent())
5697 IsDependent = true;
5698 }
5699
Douglas Gregor50dc2192010-02-11 22:55:30 +00005700 // If either the declaration has a dependent type or if any of the
5701 // expressions is type-dependent, we represent the initialization
5702 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005703 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005704 // Let clients know that initialization was done with a direct initializer.
5705 VDecl->setCXXDirectInitializer(true);
5706
5707 // Store the initialization expressions as a ParenListExpr.
5708 unsigned NumExprs = Exprs.size();
5709 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5710 (Expr **)Exprs.release(),
5711 NumExprs, RParenLoc));
5712 return;
5713 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005714
5715 // Capture the variable that is being initialized and the style of
5716 // initialization.
5717 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5718
5719 // FIXME: Poor source location information.
5720 InitializationKind Kind
5721 = InitializationKind::CreateDirect(VDecl->getLocation(),
5722 LParenLoc, RParenLoc);
5723
5724 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005725 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005726 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005727 if (Result.isInvalid()) {
5728 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005729 return;
5730 }
John McCallacf0ee52010-10-08 02:01:28 +00005731
5732 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005733
Douglas Gregora40433a2010-12-07 00:41:46 +00005734 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005735 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005736 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005737
John McCall8b7fd8f12011-01-19 11:48:09 +00005738 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005739}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005740
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005741/// \brief Given a constructor and the set of arguments provided for the
5742/// constructor, convert the arguments and add any required default arguments
5743/// to form a proper call to this constructor.
5744///
5745/// \returns true if an error occurred, false otherwise.
5746bool
5747Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5748 MultiExprArg ArgsPtr,
5749 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005750 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005751 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5752 unsigned NumArgs = ArgsPtr.size();
5753 Expr **Args = (Expr **)ArgsPtr.get();
5754
5755 const FunctionProtoType *Proto
5756 = Constructor->getType()->getAs<FunctionProtoType>();
5757 assert(Proto && "Constructor without a prototype?");
5758 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005759
5760 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005761 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005762 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005763 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005764 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005765
5766 VariadicCallType CallType =
5767 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5768 llvm::SmallVector<Expr *, 8> AllArgs;
5769 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5770 Proto, 0, Args, NumArgs, AllArgs,
5771 CallType);
5772 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5773 ConvertedArgs.push_back(AllArgs[i]);
5774 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005775}
5776
Anders Carlssone363c8e2009-12-12 00:32:00 +00005777static inline bool
5778CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5779 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005780 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005781 if (isa<NamespaceDecl>(DC)) {
5782 return SemaRef.Diag(FnDecl->getLocation(),
5783 diag::err_operator_new_delete_declared_in_namespace)
5784 << FnDecl->getDeclName();
5785 }
5786
5787 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005788 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005789 return SemaRef.Diag(FnDecl->getLocation(),
5790 diag::err_operator_new_delete_declared_static)
5791 << FnDecl->getDeclName();
5792 }
5793
Anders Carlsson60659a82009-12-12 02:43:16 +00005794 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005795}
5796
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005797static inline bool
5798CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5799 CanQualType ExpectedResultType,
5800 CanQualType ExpectedFirstParamType,
5801 unsigned DependentParamTypeDiag,
5802 unsigned InvalidParamTypeDiag) {
5803 QualType ResultType =
5804 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5805
5806 // Check that the result type is not dependent.
5807 if (ResultType->isDependentType())
5808 return SemaRef.Diag(FnDecl->getLocation(),
5809 diag::err_operator_new_delete_dependent_result_type)
5810 << FnDecl->getDeclName() << ExpectedResultType;
5811
5812 // Check that the result type is what we expect.
5813 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5814 return SemaRef.Diag(FnDecl->getLocation(),
5815 diag::err_operator_new_delete_invalid_result_type)
5816 << FnDecl->getDeclName() << ExpectedResultType;
5817
5818 // A function template must have at least 2 parameters.
5819 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5820 return SemaRef.Diag(FnDecl->getLocation(),
5821 diag::err_operator_new_delete_template_too_few_parameters)
5822 << FnDecl->getDeclName();
5823
5824 // The function decl must have at least 1 parameter.
5825 if (FnDecl->getNumParams() == 0)
5826 return SemaRef.Diag(FnDecl->getLocation(),
5827 diag::err_operator_new_delete_too_few_parameters)
5828 << FnDecl->getDeclName();
5829
5830 // Check the the first parameter type is not dependent.
5831 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5832 if (FirstParamType->isDependentType())
5833 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5834 << FnDecl->getDeclName() << ExpectedFirstParamType;
5835
5836 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005837 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005838 ExpectedFirstParamType)
5839 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5840 << FnDecl->getDeclName() << ExpectedFirstParamType;
5841
5842 return false;
5843}
5844
Anders Carlsson12308f42009-12-11 23:23:22 +00005845static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005846CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005847 // C++ [basic.stc.dynamic.allocation]p1:
5848 // A program is ill-formed if an allocation function is declared in a
5849 // namespace scope other than global scope or declared static in global
5850 // scope.
5851 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5852 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005853
5854 CanQualType SizeTy =
5855 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5856
5857 // C++ [basic.stc.dynamic.allocation]p1:
5858 // The return type shall be void*. The first parameter shall have type
5859 // std::size_t.
5860 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5861 SizeTy,
5862 diag::err_operator_new_dependent_param_type,
5863 diag::err_operator_new_param_type))
5864 return true;
5865
5866 // C++ [basic.stc.dynamic.allocation]p1:
5867 // The first parameter shall not have an associated default argument.
5868 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005869 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005870 diag::err_operator_new_default_arg)
5871 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5872
5873 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005874}
5875
5876static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005877CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5878 // C++ [basic.stc.dynamic.deallocation]p1:
5879 // A program is ill-formed if deallocation functions are declared in a
5880 // namespace scope other than global scope or declared static in global
5881 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005882 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5883 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005884
5885 // C++ [basic.stc.dynamic.deallocation]p2:
5886 // Each deallocation function shall return void and its first parameter
5887 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005888 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5889 SemaRef.Context.VoidPtrTy,
5890 diag::err_operator_delete_dependent_param_type,
5891 diag::err_operator_delete_param_type))
5892 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005893
Anders Carlsson12308f42009-12-11 23:23:22 +00005894 return false;
5895}
5896
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005897/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5898/// of this overloaded operator is well-formed. If so, returns false;
5899/// otherwise, emits appropriate diagnostics and returns true.
5900bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005901 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005902 "Expected an overloaded operator declaration");
5903
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005904 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5905
Mike Stump11289f42009-09-09 15:08:12 +00005906 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005907 // The allocation and deallocation functions, operator new,
5908 // operator new[], operator delete and operator delete[], are
5909 // described completely in 3.7.3. The attributes and restrictions
5910 // found in the rest of this subclause do not apply to them unless
5911 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005912 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005913 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005914
Anders Carlsson22f443f2009-12-12 00:26:23 +00005915 if (Op == OO_New || Op == OO_Array_New)
5916 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005917
5918 // C++ [over.oper]p6:
5919 // An operator function shall either be a non-static member
5920 // function or be a non-member function and have at least one
5921 // parameter whose type is a class, a reference to a class, an
5922 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005923 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5924 if (MethodDecl->isStatic())
5925 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005926 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005927 } else {
5928 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005929 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5930 ParamEnd = FnDecl->param_end();
5931 Param != ParamEnd; ++Param) {
5932 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005933 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5934 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005935 ClassOrEnumParam = true;
5936 break;
5937 }
5938 }
5939
Douglas Gregord69246b2008-11-17 16:14:12 +00005940 if (!ClassOrEnumParam)
5941 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005942 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005943 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005944 }
5945
5946 // C++ [over.oper]p8:
5947 // An operator function cannot have default arguments (8.3.6),
5948 // except where explicitly stated below.
5949 //
Mike Stump11289f42009-09-09 15:08:12 +00005950 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005951 // (C++ [over.call]p1).
5952 if (Op != OO_Call) {
5953 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5954 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005955 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005956 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005957 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005958 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005959 }
5960 }
5961
Douglas Gregor6cf08062008-11-10 13:38:07 +00005962 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5963 { false, false, false }
5964#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5965 , { Unary, Binary, MemberOnly }
5966#include "clang/Basic/OperatorKinds.def"
5967 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005968
Douglas Gregor6cf08062008-11-10 13:38:07 +00005969 bool CanBeUnaryOperator = OperatorUses[Op][0];
5970 bool CanBeBinaryOperator = OperatorUses[Op][1];
5971 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005972
5973 // C++ [over.oper]p8:
5974 // [...] Operator functions cannot have more or fewer parameters
5975 // than the number required for the corresponding operator, as
5976 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005977 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005978 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005979 if (Op != OO_Call &&
5980 ((NumParams == 1 && !CanBeUnaryOperator) ||
5981 (NumParams == 2 && !CanBeBinaryOperator) ||
5982 (NumParams < 1) || (NumParams > 2))) {
5983 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005984 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005985 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005986 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005987 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005988 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005989 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005990 assert(CanBeBinaryOperator &&
5991 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005992 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005993 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005994
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005995 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005996 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005997 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005998
Douglas Gregord69246b2008-11-17 16:14:12 +00005999 // Overloaded operators other than operator() cannot be variadic.
6000 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006001 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006002 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006003 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006004 }
6005
6006 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006007 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6008 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006009 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006010 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006011 }
6012
6013 // C++ [over.inc]p1:
6014 // The user-defined function called operator++ implements the
6015 // prefix and postfix ++ operator. If this function is a member
6016 // function with no parameters, or a non-member function with one
6017 // parameter of class or enumeration type, it defines the prefix
6018 // increment operator ++ for objects of that type. If the function
6019 // is a member function with one parameter (which shall be of type
6020 // int) or a non-member function with two parameters (the second
6021 // of which shall be of type int), it defines the postfix
6022 // increment operator ++ for objects of that type.
6023 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6024 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6025 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006026 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006027 ParamIsInt = BT->getKind() == BuiltinType::Int;
6028
Chris Lattner2b786902008-11-21 07:50:02 +00006029 if (!ParamIsInt)
6030 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006031 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006032 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006033 }
6034
Douglas Gregord69246b2008-11-17 16:14:12 +00006035 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006036}
Chris Lattner3b024a32008-12-17 07:09:26 +00006037
Alexis Huntc88db062010-01-13 09:01:02 +00006038/// CheckLiteralOperatorDeclaration - Check whether the declaration
6039/// of this literal operator function is well-formed. If so, returns
6040/// false; otherwise, emits appropriate diagnostics and returns true.
6041bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6042 DeclContext *DC = FnDecl->getDeclContext();
6043 Decl::Kind Kind = DC->getDeclKind();
6044 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6045 Kind != Decl::LinkageSpec) {
6046 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6047 << FnDecl->getDeclName();
6048 return true;
6049 }
6050
6051 bool Valid = false;
6052
Alexis Hunt7dd26172010-04-07 23:11:06 +00006053 // template <char...> type operator "" name() is the only valid template
6054 // signature, and the only valid signature with no parameters.
6055 if (FnDecl->param_size() == 0) {
6056 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6057 // Must have only one template parameter
6058 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6059 if (Params->size() == 1) {
6060 NonTypeTemplateParmDecl *PmDecl =
6061 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006062
Alexis Hunt7dd26172010-04-07 23:11:06 +00006063 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006064 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6065 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6066 Valid = true;
6067 }
6068 }
6069 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006070 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006071 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6072
Alexis Huntc88db062010-01-13 09:01:02 +00006073 QualType T = (*Param)->getType();
6074
Alexis Hunt079a6f72010-04-07 22:57:35 +00006075 // unsigned long long int, long double, and any character type are allowed
6076 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006077 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6078 Context.hasSameType(T, Context.LongDoubleTy) ||
6079 Context.hasSameType(T, Context.CharTy) ||
6080 Context.hasSameType(T, Context.WCharTy) ||
6081 Context.hasSameType(T, Context.Char16Ty) ||
6082 Context.hasSameType(T, Context.Char32Ty)) {
6083 if (++Param == FnDecl->param_end())
6084 Valid = true;
6085 goto FinishedParams;
6086 }
6087
Alexis Hunt079a6f72010-04-07 22:57:35 +00006088 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006089 const PointerType *PT = T->getAs<PointerType>();
6090 if (!PT)
6091 goto FinishedParams;
6092 T = PT->getPointeeType();
6093 if (!T.isConstQualified())
6094 goto FinishedParams;
6095 T = T.getUnqualifiedType();
6096
6097 // Move on to the second parameter;
6098 ++Param;
6099
6100 // If there is no second parameter, the first must be a const char *
6101 if (Param == FnDecl->param_end()) {
6102 if (Context.hasSameType(T, Context.CharTy))
6103 Valid = true;
6104 goto FinishedParams;
6105 }
6106
6107 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6108 // are allowed as the first parameter to a two-parameter function
6109 if (!(Context.hasSameType(T, Context.CharTy) ||
6110 Context.hasSameType(T, Context.WCharTy) ||
6111 Context.hasSameType(T, Context.Char16Ty) ||
6112 Context.hasSameType(T, Context.Char32Ty)))
6113 goto FinishedParams;
6114
6115 // The second and final parameter must be an std::size_t
6116 T = (*Param)->getType().getUnqualifiedType();
6117 if (Context.hasSameType(T, Context.getSizeType()) &&
6118 ++Param == FnDecl->param_end())
6119 Valid = true;
6120 }
6121
6122 // FIXME: This diagnostic is absolutely terrible.
6123FinishedParams:
6124 if (!Valid) {
6125 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6126 << FnDecl->getDeclName();
6127 return true;
6128 }
6129
6130 return false;
6131}
6132
Douglas Gregor07665a62009-01-05 19:45:36 +00006133/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6134/// linkage specification, including the language and (if present)
6135/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6136/// the location of the language string literal, which is provided
6137/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6138/// the '{' brace. Otherwise, this linkage specification does not
6139/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006140Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6141 SourceLocation LangLoc,
6142 llvm::StringRef Lang,
6143 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006144 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006145 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006146 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006147 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006148 Language = LinkageSpecDecl::lang_cxx;
6149 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006150 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006151 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006152 }
Mike Stump11289f42009-09-09 15:08:12 +00006153
Chris Lattner438e5012008-12-17 07:13:27 +00006154 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006155
Douglas Gregor07665a62009-01-05 19:45:36 +00006156 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006157 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006158 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006159 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006160 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006161 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006162}
6163
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006164/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006165/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6166/// valid, it's the position of the closing '}' brace in a linkage
6167/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006168Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6169 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006170 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006171 if (LinkageSpec)
6172 PopDeclContext();
6173 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006174}
6175
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006176/// \brief Perform semantic analysis for the variable declaration that
6177/// occurs within a C++ catch clause, returning the newly-created
6178/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006179VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006180 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006181 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006182 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006183 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006184 QualType ExDeclType = TInfo->getType();
6185
Sebastian Redl54c04d42008-12-22 19:15:10 +00006186 // Arrays and functions decay.
6187 if (ExDeclType->isArrayType())
6188 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6189 else if (ExDeclType->isFunctionType())
6190 ExDeclType = Context.getPointerType(ExDeclType);
6191
6192 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6193 // The exception-declaration shall not denote a pointer or reference to an
6194 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006195 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006196 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006197 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006198 Invalid = true;
6199 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006200
Douglas Gregor104ee002010-03-08 01:47:36 +00006201 // GCC allows catching pointers and references to incomplete types
6202 // as an extension; so do we, but we warn by default.
6203
Sebastian Redl54c04d42008-12-22 19:15:10 +00006204 QualType BaseType = ExDeclType;
6205 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006206 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006207 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006208 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006209 BaseType = Ptr->getPointeeType();
6210 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006211 DK = diag::ext_catch_incomplete_ptr;
6212 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006213 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006214 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006215 BaseType = Ref->getPointeeType();
6216 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006217 DK = diag::ext_catch_incomplete_ref;
6218 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006219 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006220 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006221 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6222 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006223 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006224
Mike Stump11289f42009-09-09 15:08:12 +00006225 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006226 RequireNonAbstractType(Loc, ExDeclType,
6227 diag::err_abstract_type_in_decl,
6228 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006229 Invalid = true;
6230
John McCall2ca705e2010-07-24 00:37:23 +00006231 // Only the non-fragile NeXT runtime currently supports C++ catches
6232 // of ObjC types, and no runtime supports catching ObjC types by value.
6233 if (!Invalid && getLangOptions().ObjC1) {
6234 QualType T = ExDeclType;
6235 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6236 T = RT->getPointeeType();
6237
6238 if (T->isObjCObjectType()) {
6239 Diag(Loc, diag::err_objc_object_catch);
6240 Invalid = true;
6241 } else if (T->isObjCObjectPointerType()) {
6242 if (!getLangOptions().NeXTRuntime) {
6243 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6244 Invalid = true;
6245 } else if (!getLangOptions().ObjCNonFragileABI) {
6246 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6247 Invalid = true;
6248 }
6249 }
6250 }
6251
Mike Stump11289f42009-09-09 15:08:12 +00006252 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006253 Name, ExDeclType, TInfo, SC_None,
6254 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006255 ExDecl->setExceptionVariable(true);
6256
Douglas Gregor6de584c2010-03-05 23:38:39 +00006257 if (!Invalid) {
6258 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6259 // C++ [except.handle]p16:
6260 // The object declared in an exception-declaration or, if the
6261 // exception-declaration does not specify a name, a temporary (12.2) is
6262 // copy-initialized (8.5) from the exception object. [...]
6263 // The object is destroyed when the handler exits, after the destruction
6264 // of any automatic objects initialized within the handler.
6265 //
6266 // We just pretend to initialize the object with itself, then make sure
6267 // it can be destroyed later.
6268 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6269 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006270 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006271 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6272 SourceLocation());
6273 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006275 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006276 if (Result.isInvalid())
6277 Invalid = true;
6278 else
6279 FinalizeVarWithDestructor(ExDecl, RecordTy);
6280 }
6281 }
6282
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006283 if (Invalid)
6284 ExDecl->setInvalidDecl();
6285
6286 return ExDecl;
6287}
6288
6289/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6290/// handler.
John McCall48871652010-08-21 09:40:31 +00006291Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006292 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006293 bool Invalid = D.isInvalidType();
6294
6295 // Check for unexpanded parameter packs.
6296 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6297 UPPC_ExceptionType)) {
6298 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6299 D.getIdentifierLoc());
6300 Invalid = true;
6301 }
6302
Sebastian Redl54c04d42008-12-22 19:15:10 +00006303 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006304 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006305 LookupOrdinaryName,
6306 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006307 // The scope should be freshly made just for us. There is just no way
6308 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006309 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006310 if (PrevDecl->isTemplateParameter()) {
6311 // Maybe we will complain about the shadowed template parameter.
6312 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006313 }
6314 }
6315
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006316 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006317 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6318 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006319 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006320 }
6321
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006322 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006323 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006324 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006325
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006326 if (Invalid)
6327 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006328
Sebastian Redl54c04d42008-12-22 19:15:10 +00006329 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006330 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006331 PushOnScopeChains(ExDecl, S);
6332 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006333 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006334
Douglas Gregor758a8692009-06-17 21:51:59 +00006335 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006336 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006337}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006338
John McCall48871652010-08-21 09:40:31 +00006339Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006340 Expr *AssertExpr,
6341 Expr *AssertMessageExpr_) {
6342 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006343
Anders Carlsson54b26982009-03-14 00:33:21 +00006344 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6345 llvm::APSInt Value(32);
6346 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6347 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6348 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006349 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006350 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006351
Anders Carlsson54b26982009-03-14 00:33:21 +00006352 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006353 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006354 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006355 }
6356 }
Mike Stump11289f42009-09-09 15:08:12 +00006357
Douglas Gregoref68fee2010-12-15 23:55:21 +00006358 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6359 return 0;
6360
Mike Stump11289f42009-09-09 15:08:12 +00006361 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006362 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006363
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006364 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006365 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006366}
Sebastian Redlf769df52009-03-24 22:27:57 +00006367
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006368/// \brief Perform semantic analysis of the given friend type declaration.
6369///
6370/// \returns A friend declaration that.
6371FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6372 TypeSourceInfo *TSInfo) {
6373 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6374
6375 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006376 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006377
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006378 if (!getLangOptions().CPlusPlus0x) {
6379 // C++03 [class.friend]p2:
6380 // An elaborated-type-specifier shall be used in a friend declaration
6381 // for a class.*
6382 //
6383 // * The class-key of the elaborated-type-specifier is required.
6384 if (!ActiveTemplateInstantiations.empty()) {
6385 // Do not complain about the form of friend template types during
6386 // template instantiation; we will already have complained when the
6387 // template was declared.
6388 } else if (!T->isElaboratedTypeSpecifier()) {
6389 // If we evaluated the type to a record type, suggest putting
6390 // a tag in front.
6391 if (const RecordType *RT = T->getAs<RecordType>()) {
6392 RecordDecl *RD = RT->getDecl();
6393
6394 std::string InsertionText = std::string(" ") + RD->getKindName();
6395
6396 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6397 << (unsigned) RD->getTagKind()
6398 << T
6399 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6400 InsertionText);
6401 } else {
6402 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6403 << T
6404 << SourceRange(FriendLoc, TypeRange.getEnd());
6405 }
6406 } else if (T->getAs<EnumType>()) {
6407 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006408 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006409 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006410 }
6411 }
6412
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006413 // C++0x [class.friend]p3:
6414 // If the type specifier in a friend declaration designates a (possibly
6415 // cv-qualified) class type, that class is declared as a friend; otherwise,
6416 // the friend declaration is ignored.
6417
6418 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6419 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006420
6421 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6422}
6423
John McCallace48cd2010-10-19 01:40:49 +00006424/// Handle a friend tag declaration where the scope specifier was
6425/// templated.
6426Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6427 unsigned TagSpec, SourceLocation TagLoc,
6428 CXXScopeSpec &SS,
6429 IdentifierInfo *Name, SourceLocation NameLoc,
6430 AttributeList *Attr,
6431 MultiTemplateParamsArg TempParamLists) {
6432 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6433
6434 bool isExplicitSpecialization = false;
6435 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6436 bool Invalid = false;
6437
6438 if (TemplateParameterList *TemplateParams
6439 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6440 TempParamLists.get(),
6441 TempParamLists.size(),
6442 /*friend*/ true,
6443 isExplicitSpecialization,
6444 Invalid)) {
6445 --NumMatchedTemplateParamLists;
6446
6447 if (TemplateParams->size() > 0) {
6448 // This is a declaration of a class template.
6449 if (Invalid)
6450 return 0;
6451
6452 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6453 SS, Name, NameLoc, Attr,
6454 TemplateParams, AS_public).take();
6455 } else {
6456 // The "template<>" header is extraneous.
6457 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6458 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6459 isExplicitSpecialization = true;
6460 }
6461 }
6462
6463 if (Invalid) return 0;
6464
6465 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6466
6467 bool isAllExplicitSpecializations = true;
6468 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6469 if (TempParamLists.get()[I]->size()) {
6470 isAllExplicitSpecializations = false;
6471 break;
6472 }
6473 }
6474
6475 // FIXME: don't ignore attributes.
6476
6477 // If it's explicit specializations all the way down, just forget
6478 // about the template header and build an appropriate non-templated
6479 // friend. TODO: for source fidelity, remember the headers.
6480 if (isAllExplicitSpecializations) {
6481 ElaboratedTypeKeyword Keyword
6482 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6483 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6484 TagLoc, SS.getRange(), NameLoc);
6485 if (T.isNull())
6486 return 0;
6487
6488 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6489 if (isa<DependentNameType>(T)) {
6490 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6491 TL.setKeywordLoc(TagLoc);
6492 TL.setQualifierRange(SS.getRange());
6493 TL.setNameLoc(NameLoc);
6494 } else {
6495 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6496 TL.setKeywordLoc(TagLoc);
6497 TL.setQualifierRange(SS.getRange());
6498 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6499 }
6500
6501 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6502 TSI, FriendLoc);
6503 Friend->setAccess(AS_public);
6504 CurContext->addDecl(Friend);
6505 return Friend;
6506 }
6507
6508 // Handle the case of a templated-scope friend class. e.g.
6509 // template <class T> class A<T>::B;
6510 // FIXME: we don't support these right now.
6511 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6512 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6513 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6514 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6515 TL.setKeywordLoc(TagLoc);
6516 TL.setQualifierRange(SS.getRange());
6517 TL.setNameLoc(NameLoc);
6518
6519 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6520 TSI, FriendLoc);
6521 Friend->setAccess(AS_public);
6522 Friend->setUnsupportedFriend(true);
6523 CurContext->addDecl(Friend);
6524 return Friend;
6525}
6526
6527
John McCall11083da2009-09-16 22:47:08 +00006528/// Handle a friend type declaration. This works in tandem with
6529/// ActOnTag.
6530///
6531/// Notes on friend class templates:
6532///
6533/// We generally treat friend class declarations as if they were
6534/// declaring a class. So, for example, the elaborated type specifier
6535/// in a friend declaration is required to obey the restrictions of a
6536/// class-head (i.e. no typedefs in the scope chain), template
6537/// parameters are required to match up with simple template-ids, &c.
6538/// However, unlike when declaring a template specialization, it's
6539/// okay to refer to a template specialization without an empty
6540/// template parameter declaration, e.g.
6541/// friend class A<T>::B<unsigned>;
6542/// We permit this as a special case; if there are any template
6543/// parameters present at all, require proper matching, i.e.
6544/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006545Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006546 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006547 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006548
6549 assert(DS.isFriendSpecified());
6550 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6551
John McCall11083da2009-09-16 22:47:08 +00006552 // Try to convert the decl specifier to a type. This works for
6553 // friend templates because ActOnTag never produces a ClassTemplateDecl
6554 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006555 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006556 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6557 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006558 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006559 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006560
Douglas Gregor6c110f32010-12-16 01:14:37 +00006561 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6562 return 0;
6563
John McCall11083da2009-09-16 22:47:08 +00006564 // This is definitely an error in C++98. It's probably meant to
6565 // be forbidden in C++0x, too, but the specification is just
6566 // poorly written.
6567 //
6568 // The problem is with declarations like the following:
6569 // template <T> friend A<T>::foo;
6570 // where deciding whether a class C is a friend or not now hinges
6571 // on whether there exists an instantiation of A that causes
6572 // 'foo' to equal C. There are restrictions on class-heads
6573 // (which we declare (by fiat) elaborated friend declarations to
6574 // be) that makes this tractable.
6575 //
6576 // FIXME: handle "template <> friend class A<T>;", which
6577 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006578 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006579 Diag(Loc, diag::err_tagless_friend_type_template)
6580 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006581 return 0;
John McCall11083da2009-09-16 22:47:08 +00006582 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006583
John McCallaa74a0c2009-08-28 07:59:38 +00006584 // C++98 [class.friend]p1: A friend of a class is a function
6585 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006586 // This is fixed in DR77, which just barely didn't make the C++03
6587 // deadline. It's also a very silly restriction that seriously
6588 // affects inner classes and which nobody else seems to implement;
6589 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006590 //
6591 // But note that we could warn about it: it's always useless to
6592 // friend one of your own members (it's not, however, worthless to
6593 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006594
John McCall11083da2009-09-16 22:47:08 +00006595 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006596 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006597 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006598 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006599 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006600 TSI,
John McCall11083da2009-09-16 22:47:08 +00006601 DS.getFriendSpecLoc());
6602 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006603 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6604
6605 if (!D)
John McCall48871652010-08-21 09:40:31 +00006606 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006607
John McCall11083da2009-09-16 22:47:08 +00006608 D->setAccess(AS_public);
6609 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006610
John McCall48871652010-08-21 09:40:31 +00006611 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006612}
6613
John McCallde3fd222010-10-12 23:13:28 +00006614Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6615 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006616 const DeclSpec &DS = D.getDeclSpec();
6617
6618 assert(DS.isFriendSpecified());
6619 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6620
6621 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006622 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6623 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006624
6625 // C++ [class.friend]p1
6626 // A friend of a class is a function or class....
6627 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006628 // It *doesn't* see through dependent types, which is correct
6629 // according to [temp.arg.type]p3:
6630 // If a declaration acquires a function type through a
6631 // type dependent on a template-parameter and this causes
6632 // a declaration that does not use the syntactic form of a
6633 // function declarator to have a function type, the program
6634 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006635 if (!T->isFunctionType()) {
6636 Diag(Loc, diag::err_unexpected_friend);
6637
6638 // It might be worthwhile to try to recover by creating an
6639 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006640 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006641 }
6642
6643 // C++ [namespace.memdef]p3
6644 // - If a friend declaration in a non-local class first declares a
6645 // class or function, the friend class or function is a member
6646 // of the innermost enclosing namespace.
6647 // - The name of the friend is not found by simple name lookup
6648 // until a matching declaration is provided in that namespace
6649 // scope (either before or after the class declaration granting
6650 // friendship).
6651 // - If a friend function is called, its name may be found by the
6652 // name lookup that considers functions from namespaces and
6653 // classes associated with the types of the function arguments.
6654 // - When looking for a prior declaration of a class or a function
6655 // declared as a friend, scopes outside the innermost enclosing
6656 // namespace scope are not considered.
6657
John McCallde3fd222010-10-12 23:13:28 +00006658 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006659 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6660 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006661 assert(Name);
6662
Douglas Gregor6c110f32010-12-16 01:14:37 +00006663 // Check for unexpanded parameter packs.
6664 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6665 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6666 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6667 return 0;
6668
John McCall07e91c02009-08-06 02:15:43 +00006669 // The context we found the declaration in, or in which we should
6670 // create the declaration.
6671 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006672 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006673 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006674 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006675
John McCallde3fd222010-10-12 23:13:28 +00006676 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006677
John McCallde3fd222010-10-12 23:13:28 +00006678 // There are four cases here.
6679 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006680 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006681 // there as appropriate.
6682 // Recover from invalid scope qualifiers as if they just weren't there.
6683 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006684 // C++0x [namespace.memdef]p3:
6685 // If the name in a friend declaration is neither qualified nor
6686 // a template-id and the declaration is a function or an
6687 // elaborated-type-specifier, the lookup to determine whether
6688 // the entity has been previously declared shall not consider
6689 // any scopes outside the innermost enclosing namespace.
6690 // C++0x [class.friend]p11:
6691 // If a friend declaration appears in a local class and the name
6692 // specified is an unqualified name, a prior declaration is
6693 // looked up without considering scopes that are outside the
6694 // innermost enclosing non-class scope. For a friend function
6695 // declaration, if there is no prior declaration, the program is
6696 // ill-formed.
6697 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006698 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006699
John McCallf7cfb222010-10-13 05:45:15 +00006700 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006701 DC = CurContext;
6702 while (true) {
6703 // Skip class contexts. If someone can cite chapter and verse
6704 // for this behavior, that would be nice --- it's what GCC and
6705 // EDG do, and it seems like a reasonable intent, but the spec
6706 // really only says that checks for unqualified existing
6707 // declarations should stop at the nearest enclosing namespace,
6708 // not that they should only consider the nearest enclosing
6709 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006710 while (DC->isRecord())
6711 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006712
John McCall1f82f242009-11-18 22:49:29 +00006713 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006714
6715 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006716 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006717 break;
John McCallf7cfb222010-10-13 05:45:15 +00006718
John McCallf4776592010-10-14 22:22:28 +00006719 if (isTemplateId) {
6720 if (isa<TranslationUnitDecl>(DC)) break;
6721 } else {
6722 if (DC->isFileContext()) break;
6723 }
John McCall07e91c02009-08-06 02:15:43 +00006724 DC = DC->getParent();
6725 }
6726
6727 // C++ [class.friend]p1: A friend of a class is a function or
6728 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006729 // C++0x changes this for both friend types and functions.
6730 // Most C++ 98 compilers do seem to give an error here, so
6731 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006732 if (!Previous.empty() && DC->Equals(CurContext)
6733 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006734 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006735
John McCallccbc0322010-10-13 06:22:15 +00006736 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006737
John McCallde3fd222010-10-12 23:13:28 +00006738 // - There's a non-dependent scope specifier, in which case we
6739 // compute it and do a previous lookup there for a function
6740 // or function template.
6741 } else if (!SS.getScopeRep()->isDependent()) {
6742 DC = computeDeclContext(SS);
6743 if (!DC) return 0;
6744
6745 if (RequireCompleteDeclContext(SS, DC)) return 0;
6746
6747 LookupQualifiedName(Previous, DC);
6748
6749 // Ignore things found implicitly in the wrong scope.
6750 // TODO: better diagnostics for this case. Suggesting the right
6751 // qualified scope would be nice...
6752 LookupResult::Filter F = Previous.makeFilter();
6753 while (F.hasNext()) {
6754 NamedDecl *D = F.next();
6755 if (!DC->InEnclosingNamespaceSetOf(
6756 D->getDeclContext()->getRedeclContext()))
6757 F.erase();
6758 }
6759 F.done();
6760
6761 if (Previous.empty()) {
6762 D.setInvalidType();
6763 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6764 return 0;
6765 }
6766
6767 // C++ [class.friend]p1: A friend of a class is a function or
6768 // class that is not a member of the class . . .
6769 if (DC->Equals(CurContext))
6770 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6771
6772 // - There's a scope specifier that does not match any template
6773 // parameter lists, in which case we use some arbitrary context,
6774 // create a method or method template, and wait for instantiation.
6775 // - There's a scope specifier that does match some template
6776 // parameter lists, which we don't handle right now.
6777 } else {
6778 DC = CurContext;
6779 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006780 }
6781
John McCallf7cfb222010-10-13 05:45:15 +00006782 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006783 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006784 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6785 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6786 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006787 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006788 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6789 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006790 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006791 }
John McCall07e91c02009-08-06 02:15:43 +00006792 }
6793
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006794 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006795 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006796 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006797 IsDefinition,
6798 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006799 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006800
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006801 assert(ND->getDeclContext() == DC);
6802 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006803
John McCall759e32b2009-08-31 22:39:49 +00006804 // Add the function declaration to the appropriate lookup tables,
6805 // adjusting the redeclarations list as necessary. We don't
6806 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006807 //
John McCall759e32b2009-08-31 22:39:49 +00006808 // Also update the scope-based lookup if the target context's
6809 // lookup context is in lexical scope.
6810 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006811 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006812 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006813 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006814 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006815 }
John McCallaa74a0c2009-08-28 07:59:38 +00006816
6817 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006818 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006819 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006820 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006821 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006822
John McCallde3fd222010-10-12 23:13:28 +00006823 if (ND->isInvalidDecl())
6824 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006825 else {
6826 FunctionDecl *FD;
6827 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6828 FD = FTD->getTemplatedDecl();
6829 else
6830 FD = cast<FunctionDecl>(ND);
6831
6832 // Mark templated-scope function declarations as unsupported.
6833 if (FD->getNumTemplateParameterLists())
6834 FrD->setUnsupportedFriend(true);
6835 }
John McCallde3fd222010-10-12 23:13:28 +00006836
John McCall48871652010-08-21 09:40:31 +00006837 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006838}
6839
John McCall48871652010-08-21 09:40:31 +00006840void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6841 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006842
Sebastian Redlf769df52009-03-24 22:27:57 +00006843 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6844 if (!Fn) {
6845 Diag(DelLoc, diag::err_deleted_non_function);
6846 return;
6847 }
6848 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6849 Diag(DelLoc, diag::err_deleted_decl_not_first);
6850 Diag(Prev->getLocation(), diag::note_previous_declaration);
6851 // If the declaration wasn't the first, we delete the function anyway for
6852 // recovery.
6853 }
6854 Fn->setDeleted();
6855}
Sebastian Redl4c018662009-04-27 21:33:24 +00006856
6857static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6858 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6859 ++CI) {
6860 Stmt *SubStmt = *CI;
6861 if (!SubStmt)
6862 continue;
6863 if (isa<ReturnStmt>(SubStmt))
6864 Self.Diag(SubStmt->getSourceRange().getBegin(),
6865 diag::err_return_in_constructor_handler);
6866 if (!isa<Expr>(SubStmt))
6867 SearchForReturnInStmt(Self, SubStmt);
6868 }
6869}
6870
6871void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6872 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6873 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6874 SearchForReturnInStmt(*this, Handler);
6875 }
6876}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006877
Mike Stump11289f42009-09-09 15:08:12 +00006878bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006879 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006880 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6881 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006882
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006883 if (Context.hasSameType(NewTy, OldTy) ||
6884 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006885 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006886
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006887 // Check if the return types are covariant
6888 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006889
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006890 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006891 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6892 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006893 NewClassTy = NewPT->getPointeeType();
6894 OldClassTy = OldPT->getPointeeType();
6895 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006896 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6897 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6898 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6899 NewClassTy = NewRT->getPointeeType();
6900 OldClassTy = OldRT->getPointeeType();
6901 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006902 }
6903 }
Mike Stump11289f42009-09-09 15:08:12 +00006904
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006905 // The return types aren't either both pointers or references to a class type.
6906 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006907 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006908 diag::err_different_return_type_for_overriding_virtual_function)
6909 << New->getDeclName() << NewTy << OldTy;
6910 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006911
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006912 return true;
6913 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006914
Anders Carlssone60365b2009-12-31 18:34:24 +00006915 // C++ [class.virtual]p6:
6916 // If the return type of D::f differs from the return type of B::f, the
6917 // class type in the return type of D::f shall be complete at the point of
6918 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006919 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6920 if (!RT->isBeingDefined() &&
6921 RequireCompleteType(New->getLocation(), NewClassTy,
6922 PDiag(diag::err_covariant_return_incomplete)
6923 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006924 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006925 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006926
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006927 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006928 // Check if the new class derives from the old class.
6929 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6930 Diag(New->getLocation(),
6931 diag::err_covariant_return_not_derived)
6932 << New->getDeclName() << NewTy << OldTy;
6933 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6934 return true;
6935 }
Mike Stump11289f42009-09-09 15:08:12 +00006936
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006937 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006938 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006939 diag::err_covariant_return_inaccessible_base,
6940 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6941 // FIXME: Should this point to the return type?
6942 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006943 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6944 return true;
6945 }
6946 }
Mike Stump11289f42009-09-09 15:08:12 +00006947
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006948 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006949 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006950 Diag(New->getLocation(),
6951 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006952 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006953 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6954 return true;
6955 };
Mike Stump11289f42009-09-09 15:08:12 +00006956
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006957
6958 // The new class type must have the same or less qualifiers as the old type.
6959 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6960 Diag(New->getLocation(),
6961 diag::err_covariant_return_type_class_type_more_qualified)
6962 << New->getDeclName() << NewTy << OldTy;
6963 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6964 return true;
6965 };
Mike Stump11289f42009-09-09 15:08:12 +00006966
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006967 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006968}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006969
Douglas Gregor21920e372009-12-01 17:24:26 +00006970/// \brief Mark the given method pure.
6971///
6972/// \param Method the method to be marked pure.
6973///
6974/// \param InitRange the source range that covers the "0" initializer.
6975bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6976 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6977 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006978 return false;
6979 }
6980
6981 if (!Method->isInvalidDecl())
6982 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6983 << Method->getDeclName() << InitRange;
6984 return true;
6985}
6986
John McCall1f4ee7b2009-12-19 09:28:58 +00006987/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6988/// an initializer for the out-of-line declaration 'Dcl'. The scope
6989/// is a fresh scope pushed for just this purpose.
6990///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006991/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6992/// static data member of class X, names should be looked up in the scope of
6993/// class X.
John McCall48871652010-08-21 09:40:31 +00006994void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006995 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006996 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006997
John McCall1f4ee7b2009-12-19 09:28:58 +00006998 // We should only get called for declarations with scope specifiers, like:
6999 // int foo::bar;
7000 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007001 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007002}
7003
7004/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007005/// initializer for the out-of-line declaration 'D'.
7006void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007007 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007008 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007009
John McCall1f4ee7b2009-12-19 09:28:58 +00007010 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007011 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007012}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007013
7014/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7015/// C++ if/switch/while/for statement.
7016/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007017DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007018 // C++ 6.4p2:
7019 // The declarator shall not specify a function or an array.
7020 // The type-specifier-seq shall not contain typedef and shall not declare a
7021 // new class or enumeration.
7022 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7023 "Parser allowed 'typedef' as storage class of condition decl.");
7024
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007025 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007026 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7027 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007028
7029 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7030 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7031 // would be created and CXXConditionDeclExpr wants a VarDecl.
7032 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7033 << D.getSourceRange();
7034 return DeclResult();
7035 } else if (OwnedTag && OwnedTag->isDefinition()) {
7036 // The type-specifier-seq shall not declare a new class or enumeration.
7037 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7038 }
7039
John McCall48871652010-08-21 09:40:31 +00007040 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007041 if (!Dcl)
7042 return DeclResult();
7043
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007044 return Dcl;
7045}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007046
Douglas Gregor88d292c2010-05-13 16:44:06 +00007047void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7048 bool DefinitionRequired) {
7049 // Ignore any vtable uses in unevaluated operands or for classes that do
7050 // not have a vtable.
7051 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7052 CurContext->isDependentContext() ||
7053 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007054 return;
7055
Douglas Gregor88d292c2010-05-13 16:44:06 +00007056 // Try to insert this class into the map.
7057 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7058 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7059 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7060 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007061 // If we already had an entry, check to see if we are promoting this vtable
7062 // to required a definition. If so, we need to reappend to the VTableUses
7063 // list, since we may have already processed the first entry.
7064 if (DefinitionRequired && !Pos.first->second) {
7065 Pos.first->second = true;
7066 } else {
7067 // Otherwise, we can early exit.
7068 return;
7069 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007070 }
7071
7072 // Local classes need to have their virtual members marked
7073 // immediately. For all other classes, we mark their virtual members
7074 // at the end of the translation unit.
7075 if (Class->isLocalClass())
7076 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007077 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007078 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007079}
7080
Douglas Gregor88d292c2010-05-13 16:44:06 +00007081bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007082 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007083 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007084
Douglas Gregor88d292c2010-05-13 16:44:06 +00007085 // Note: The VTableUses vector could grow as a result of marking
7086 // the members of a class as "used", so we check the size each
7087 // time through the loop and prefer indices (with are stable) to
7088 // iterators (which are not).
7089 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007090 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007091 if (!Class)
7092 continue;
7093
7094 SourceLocation Loc = VTableUses[I].second;
7095
7096 // If this class has a key function, but that key function is
7097 // defined in another translation unit, we don't need to emit the
7098 // vtable even though we're using it.
7099 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007100 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007101 switch (KeyFunction->getTemplateSpecializationKind()) {
7102 case TSK_Undeclared:
7103 case TSK_ExplicitSpecialization:
7104 case TSK_ExplicitInstantiationDeclaration:
7105 // The key function is in another translation unit.
7106 continue;
7107
7108 case TSK_ExplicitInstantiationDefinition:
7109 case TSK_ImplicitInstantiation:
7110 // We will be instantiating the key function.
7111 break;
7112 }
7113 } else if (!KeyFunction) {
7114 // If we have a class with no key function that is the subject
7115 // of an explicit instantiation declaration, suppress the
7116 // vtable; it will live with the explicit instantiation
7117 // definition.
7118 bool IsExplicitInstantiationDeclaration
7119 = Class->getTemplateSpecializationKind()
7120 == TSK_ExplicitInstantiationDeclaration;
7121 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7122 REnd = Class->redecls_end();
7123 R != REnd; ++R) {
7124 TemplateSpecializationKind TSK
7125 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7126 if (TSK == TSK_ExplicitInstantiationDeclaration)
7127 IsExplicitInstantiationDeclaration = true;
7128 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7129 IsExplicitInstantiationDeclaration = false;
7130 break;
7131 }
7132 }
7133
7134 if (IsExplicitInstantiationDeclaration)
7135 continue;
7136 }
7137
7138 // Mark all of the virtual members of this class as referenced, so
7139 // that we can build a vtable. Then, tell the AST consumer that a
7140 // vtable for this class is required.
7141 MarkVirtualMembersReferenced(Loc, Class);
7142 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7143 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7144
7145 // Optionally warn if we're emitting a weak vtable.
7146 if (Class->getLinkage() == ExternalLinkage &&
7147 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007148 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007149 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7150 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007151 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007152 VTableUses.clear();
7153
Anders Carlsson82fccd02009-12-07 08:24:59 +00007154 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007155}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007156
Rafael Espindola5b334082010-03-26 00:36:59 +00007157void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7158 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007159 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7160 e = RD->method_end(); i != e; ++i) {
7161 CXXMethodDecl *MD = *i;
7162
7163 // C++ [basic.def.odr]p2:
7164 // [...] A virtual member function is used if it is not pure. [...]
7165 if (MD->isVirtual() && !MD->isPure())
7166 MarkDeclarationReferenced(Loc, MD);
7167 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007168
7169 // Only classes that have virtual bases need a VTT.
7170 if (RD->getNumVBases() == 0)
7171 return;
7172
7173 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7174 e = RD->bases_end(); i != e; ++i) {
7175 const CXXRecordDecl *Base =
7176 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007177 if (Base->getNumVBases() == 0)
7178 continue;
7179 MarkVirtualMembersReferenced(Loc, Base);
7180 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007181}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007182
7183/// SetIvarInitializers - This routine builds initialization ASTs for the
7184/// Objective-C implementation whose ivars need be initialized.
7185void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7186 if (!getLangOptions().CPlusPlus)
7187 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007188 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007189 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7190 CollectIvarsToConstructOrDestruct(OID, ivars);
7191 if (ivars.empty())
7192 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007193 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007194 for (unsigned i = 0; i < ivars.size(); i++) {
7195 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007196 if (Field->isInvalidDecl())
7197 continue;
7198
Alexis Hunt1d792652011-01-08 20:30:50 +00007199 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007200 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7201 InitializationKind InitKind =
7202 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7203
7204 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007205 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007206 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007207 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007208 // Note, MemberInit could actually come back empty if no initialization
7209 // is required (e.g., because it would call a trivial default constructor)
7210 if (!MemberInit.get() || MemberInit.isInvalid())
7211 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007212
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007213 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007214 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7215 SourceLocation(),
7216 MemberInit.takeAs<Expr>(),
7217 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007218 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007219
7220 // Be sure that the destructor is accessible and is marked as referenced.
7221 if (const RecordType *RecordTy
7222 = Context.getBaseElementType(Field->getType())
7223 ->getAs<RecordType>()) {
7224 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007225 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007226 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7227 CheckDestructorAccess(Field->getLocation(), Destructor,
7228 PDiag(diag::err_access_dtor_ivar)
7229 << Context.getBaseElementType(Field->getType()));
7230 }
7231 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007232 }
7233 ObjCImplementation->setIvarInitializers(Context,
7234 AllToInit.data(), AllToInit.size());
7235 }
7236}