blob: c1523cffc14545ea95144ad6246c52a2f5de2f1d [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
Alexis Hunt96d5c762009-11-21 08:43:09 +0000524 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
525 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
526 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000531
John McCall3696dcb2010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539}
540
Douglas Gregor556877c2008-04-13 21:30:24 +0000541/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
542/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000546BaseResult
John McCall48871652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregorc40290e2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky19b9f952010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000561
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000573}
Douglas Gregor556877c2008-04-13 21:30:24 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575/// \brief Performs the actual work of attaching the given base class
576/// specifiers to a C++ class.
577bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
578 unsigned NumBases) {
579 if (NumBases == 0)
580 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000581
582 // Used to keep track of which base types we have already seen, so
583 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000595 if (!Class->hasObjectMember()) {
596 if (const RecordType *FDTTy =
597 NewBaseType.getTypePtr()->getAs<RecordType>())
598 if (FDTTy->getDecl()->hasObjectMember())
599 Class->setHasObjectMember(true);
600 }
601
Douglas Gregor29a92472008-10-22 17:49:05 +0000602 if (KnownBaseTypes[NewBaseType]) {
603 // C++ [class.mi]p3:
604 // A class shall not be specified as a direct base class of a
605 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
626 // Delete the remaining (good) base class specifiers, since their
627 // data has been copied into the CXXRecordDecl.
628 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000630
631 return Invalid;
632}
633
634/// ActOnBaseSpecifiers - Attach the given base specifiers to the
635/// class, after checking whether there are any duplicate base
636/// classes.
John McCall48871652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000646
John McCalle78aac42010-03-10 03:28:59 +0000647static CXXRecordDecl *GetClassForType(QualType T) {
648 if (const RecordType *RT = T->getAs<RecordType>())
649 return cast<CXXRecordDecl>(RT->getDecl());
650 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
651 return ICT->getDecl();
652 else
653 return 0;
654}
655
Douglas Gregor36d1b142009-10-06 17:59:45 +0000656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
John McCalle78aac42010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
John McCalle78aac42010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCall67da35c2010-02-04 22:26:26 +0000670 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
671 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672}
673
674/// \brief Determine whether the type \p Derived is a C++ class that is
675/// derived from the type \p Base.
676bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
677 if (!getLangOptions().CPlusPlus)
678 return false;
679
John McCalle78aac42010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlssona70cff62010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000693 assert(BasePathArray.empty() && "Base path array must be empty!");
694 assert(Paths.isRecordingPaths() && "Must record paths!");
695
696 const CXXBasePath &Path = Paths.front();
697
698 // We first go backward and check if we have a virtual base.
699 // FIXME: It would be better if CXXBasePath had the base specifier for
700 // the nearest virtual base.
701 unsigned Start = 0;
702 for (unsigned I = Path.size(); I != 0; --I) {
703 if (Path[I - 1].Base->isVirtual()) {
704 Start = I - 1;
705 break;
706 }
707 }
708
709 // Now add all bases.
710 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000712}
713
Douglas Gregor88d292c2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallcf142162010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregor36d1b142009-10-06 17:59:45 +0000726/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
727/// conversion (where Derived and Base are class types) is
728/// well-formed, meaning that the conversion is unambiguous (and
729/// that all of the base classes are accessible). Returns true
730/// and emits a diagnostic if the code is ill-formed, returns false
731/// otherwise. Loc is the location where this routine should point to
732/// if there is an error, and Range is the source range to highlight
733/// if there is an error.
734bool
735Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 // First, determine whether the path from Derived to Base is
742 // ambiguous. This is slightly more expensive than checking whether
743 // the Derived to Base conversion exists, because here we need to
744 // explore multiple paths to determine if there is an ambiguity.
745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
746 /*DetectVirtual=*/false);
747 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(DerivationOkay &&
749 "Can only be used with a derived-to-base conversion");
750 (void)DerivationOkay;
751
752 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000753 if (InaccessibleBaseID) {
754 // Check that the base class can be accessed.
755 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
756 InaccessibleBaseID)) {
757 case AR_inaccessible:
758 return true;
759 case AR_accessible:
760 case AR_dependent:
761 case AR_delayed:
762 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000763 }
John McCall5b0829a2010-02-10 09:31:12 +0000764 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000770 }
771
772 // We know that the derived-to-base conversion is ambiguous, and
773 // we're going to produce a diagnostic. Perform the derived-to-base
774 // search just one more time to compute all of the possible paths so
775 // that we can print them out. This is more expensive than any of
776 // the previous derived-to-base checks we've done, but at this point
777 // performance isn't as much of an issue.
778 Paths.clear();
779 Paths.setRecordingPaths(true);
780 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(StillOkay && "Can only be used with a derived-to-base conversion");
782 (void)StillOkay;
783
784 // Build up a textual representation of the ambiguous paths, e.g.,
785 // D -> B -> A, that will be used to illustrate the ambiguous
786 // conversions in the diagnostic. We only print one of the paths
787 // to each base class subobject.
788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
789
790 Diag(Loc, AmbigiousBaseConvID)
791 << Derived << Base << PathDisplayStr << Range << Name;
792 return true;
793}
794
795bool
796Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806}
807
808
809/// @brief Builds a string representing ambiguous paths from a
810/// specific derived class to different subobjects of the same base
811/// class.
812///
813/// This function builds a string that can be used in error messages
814/// to show the different paths that one can take through the
815/// inheritance hierarchy to go from the derived class to different
816/// subobjects of a base class. The result looks something like this:
817/// @code
818/// struct D -> struct B -> struct A
819/// struct D -> struct C -> struct A
820/// @endcode
821std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
822 std::string PathDisplayStr;
823 std::set<unsigned> DisplayedPaths;
824 for (CXXBasePaths::paths_iterator Path = Paths.begin();
825 Path != Paths.end(); ++Path) {
826 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
827 // We haven't displayed a path to this particular base
828 // class subobject yet.
829 PathDisplayStr += "\n ";
830 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
831 for (CXXBasePath::const_iterator Element = Path->begin();
832 Element != Path->end(); ++Element)
833 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
834 }
835 }
836
837 return PathDisplayStr;
838}
839
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnarad7340582010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853}
854
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000855/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
856/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
857/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000858/// any.
John McCall48871652010-08-21 09:40:31 +0000859Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000862 ExprTy *BW, const VirtSpecifiers &VS,
863 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000864 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000865 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000866 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
867 DeclarationName Name = NameInfo.getName();
868 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000869
870 // For anonymous bitfields, the location should point to the type.
871 if (Loc.isInvalid())
872 Loc = D.getSourceRange().getBegin();
873
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000874 Expr *BitWidth = static_cast<Expr*>(BW);
875 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876
John McCallb1cd7da2010-06-04 08:34:12 +0000877 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000878 assert(!DS.isFriendSpecified());
879
John McCallb1cd7da2010-06-04 08:34:12 +0000880 bool isFunc = false;
881 if (D.isFunctionDeclarator())
882 isFunc = true;
883 else if (D.getNumTypeObjects() == 0 &&
884 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000885 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000886 isFunc = TDType->isFunctionType();
887 }
888
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000889 // C++ 9.2p6: A member shall not be declared to have automatic storage
890 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000891 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
892 // data members and cannot be applied to names declared const or static,
893 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 switch (DS.getStorageClassSpec()) {
895 case DeclSpec::SCS_unspecified:
896 case DeclSpec::SCS_typedef:
897 case DeclSpec::SCS_static:
898 // FALL THROUGH.
899 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000900 case DeclSpec::SCS_mutable:
901 if (isFunc) {
902 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000903 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000904 else
Chris Lattner3b054132008-11-19 05:08:23 +0000905 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Sebastian Redl8071edb2008-11-17 23:24:37 +0000907 // FIXME: It would be nicer if the keyword was ignored only for this
908 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000909 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000910 }
911 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000912 default:
913 if (DS.getStorageClassSpecLoc().isValid())
914 Diag(DS.getStorageClassSpecLoc(),
915 diag::err_storageclass_invalid_for_member);
916 else
917 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
918 D.getMutableDeclSpec().ClearStorageClassSpecs();
919 }
920
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000921 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
922 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000923 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000924
925 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000926 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000927 CXXScopeSpec &SS = D.getCXXScopeSpec();
928
929
930 if (SS.isSet() && !SS.isInvalid()) {
931 // The user provided a superfluous scope specifier inside a class
932 // definition:
933 //
934 // class X {
935 // int X::member;
936 // };
937 DeclContext *DC = 0;
938 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
939 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
940 << Name << FixItHint::CreateRemoval(SS.getRange());
941 else
942 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
943 << Name << SS.getRange();
944
945 SS.clear();
946 }
947
Douglas Gregor3447e762009-08-20 22:52:58 +0000948 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000949 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000950 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
951 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000952 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000953 } else {
John McCall48871652010-08-21 09:40:31 +0000954 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000955 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000956 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000957 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000958
959 // Non-instance-fields can't have a bitfield.
960 if (BitWidth) {
961 if (Member->isInvalidDecl()) {
962 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000963 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000964 // C++ 9.6p3: A bit-field shall not be a static member.
965 // "static member 'A' cannot be a bit-field"
966 Diag(Loc, diag::err_static_not_bitfield)
967 << Name << BitWidth->getSourceRange();
968 } else if (isa<TypedefDecl>(Member)) {
969 // "typedef member 'x' cannot be a bit-field"
970 Diag(Loc, diag::err_typedef_not_bitfield)
971 << Name << BitWidth->getSourceRange();
972 } else {
973 // A function typedef ("typedef int f(); f a;").
974 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
975 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000976 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000977 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Chris Lattnerd26760a2009-03-05 23:01:03 +0000980 BitWidth = 0;
981 Member->setInvalidDecl();
982 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000983
984 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregor3447e762009-08-20 22:52:58 +0000986 // If we have declared a member function template, set the access of the
987 // templated declaration as well.
988 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
989 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000990 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000991
Douglas Gregor92751d42008-11-17 22:58:34 +0000992 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000993
Douglas Gregor0c880302009-03-11 23:00:04 +0000994 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000995 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000996 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000997 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000999 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001000 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001001 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001002 }
John McCall48871652010-08-21 09:40:31 +00001003 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001004}
1005
Douglas Gregor15e77a22009-12-31 09:10:24 +00001006/// \brief Find the direct and/or virtual base specifiers that
1007/// correspond to the given base type, for use in base initialization
1008/// within a constructor.
1009static bool FindBaseInitializer(Sema &SemaRef,
1010 CXXRecordDecl *ClassDecl,
1011 QualType BaseType,
1012 const CXXBaseSpecifier *&DirectBaseSpec,
1013 const CXXBaseSpecifier *&VirtualBaseSpec) {
1014 // First, check for a direct base class.
1015 DirectBaseSpec = 0;
1016 for (CXXRecordDecl::base_class_const_iterator Base
1017 = ClassDecl->bases_begin();
1018 Base != ClassDecl->bases_end(); ++Base) {
1019 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1020 // We found a direct base of this type. That's what we're
1021 // initializing.
1022 DirectBaseSpec = &*Base;
1023 break;
1024 }
1025 }
1026
1027 // Check for a virtual base class.
1028 // FIXME: We might be able to short-circuit this if we know in advance that
1029 // there are no virtual bases.
1030 VirtualBaseSpec = 0;
1031 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1032 // We haven't found a base yet; search the class hierarchy for a
1033 // virtual base class.
1034 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1035 /*DetectVirtual=*/false);
1036 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1037 BaseType, Paths)) {
1038 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1039 Path != Paths.end(); ++Path) {
1040 if (Path->back().Base->isVirtual()) {
1041 VirtualBaseSpec = Path->back().Base;
1042 break;
1043 }
1044 }
1045 }
1046 }
1047
1048 return DirectBaseSpec || VirtualBaseSpec;
1049}
1050
Douglas Gregore8381c02008-11-05 04:29:56 +00001051/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001052MemInitResult
John McCall48871652010-08-21 09:40:31 +00001053Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001054 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001055 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001056 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001057 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001058 SourceLocation IdLoc,
1059 SourceLocation LParenLoc,
1060 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001061 SourceLocation RParenLoc,
1062 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001063 if (!ConstructorD)
1064 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001065
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001066 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001067
1068 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001069 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001070 if (!Constructor) {
1071 // The user wrote a constructor initializer on a function that is
1072 // not a C++ constructor. Ignore the error for now, because we may
1073 // have more member initializers coming; we'll diagnose it just
1074 // once in ActOnMemInitializers.
1075 return true;
1076 }
1077
1078 CXXRecordDecl *ClassDecl = Constructor->getParent();
1079
1080 // C++ [class.base.init]p2:
1081 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001082 // constructor's class and, if not found in that scope, are looked
1083 // up in the scope containing the constructor's definition.
1084 // [Note: if the constructor's class contains a member with the
1085 // same name as a direct or virtual base class of the class, a
1086 // mem-initializer-id naming the member or base class and composed
1087 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001088 // mem-initializer-id for the hidden base class may be specified
1089 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001090 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001091 // Look for a member, first.
1092 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001093 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001094 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001095 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001096 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001097
Douglas Gregor44e7df62011-01-04 00:32:56 +00001098 if (Member) {
1099 if (EllipsisLoc.isValid())
1100 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1101 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1102
Francois Pichetd583da02010-12-04 09:14:42 +00001103 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001104 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001105 }
1106
Francois Pichetd583da02010-12-04 09:14:42 +00001107 // Handle anonymous union case.
1108 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001109 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1110 if (EllipsisLoc.isValid())
1111 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1112 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1113
Francois Pichetd583da02010-12-04 09:14:42 +00001114 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1115 NumArgs, IdLoc,
1116 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001117 }
Francois Pichetd583da02010-12-04 09:14:42 +00001118 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001119 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001120 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001121 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001122 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001123
1124 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001125 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001126 } else {
1127 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1128 LookupParsedName(R, S, &SS);
1129
1130 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1131 if (!TyD) {
1132 if (R.isAmbiguous()) return true;
1133
John McCallda6841b2010-04-09 19:01:14 +00001134 // We don't want access-control diagnostics here.
1135 R.suppressDiagnostics();
1136
Douglas Gregora3b624a2010-01-19 06:46:48 +00001137 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1138 bool NotUnknownSpecialization = false;
1139 DeclContext *DC = computeDeclContext(SS, false);
1140 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1141 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1142
1143 if (!NotUnknownSpecialization) {
1144 // When the scope specifier can refer to a member of an unknown
1145 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001146 BaseType = CheckTypenameType(ETK_None,
1147 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001148 *MemberOrBase, SourceLocation(),
1149 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001150 if (BaseType.isNull())
1151 return true;
1152
Douglas Gregora3b624a2010-01-19 06:46:48 +00001153 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001154 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001155 }
1156 }
1157
Douglas Gregor15e77a22009-12-31 09:10:24 +00001158 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001159 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001160 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1161 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001162 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001163 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001164 // We have found a non-static data member with a similar
1165 // name to what was typed; complain and initialize that
1166 // member.
1167 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1168 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001169 << FixItHint::CreateReplacement(R.getNameLoc(),
1170 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001171 Diag(Member->getLocation(), diag::note_previous_decl)
1172 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001173
1174 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1175 LParenLoc, RParenLoc);
1176 }
1177 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1178 const CXXBaseSpecifier *DirectBaseSpec;
1179 const CXXBaseSpecifier *VirtualBaseSpec;
1180 if (FindBaseInitializer(*this, ClassDecl,
1181 Context.getTypeDeclType(Type),
1182 DirectBaseSpec, VirtualBaseSpec)) {
1183 // We have found a direct or virtual base class with a
1184 // similar name to what was typed; complain and initialize
1185 // that base class.
1186 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1187 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001188 << FixItHint::CreateReplacement(R.getNameLoc(),
1189 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001190
1191 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1192 : VirtualBaseSpec;
1193 Diag(BaseSpec->getSourceRange().getBegin(),
1194 diag::note_base_class_specified_here)
1195 << BaseSpec->getType()
1196 << BaseSpec->getSourceRange();
1197
Douglas Gregor15e77a22009-12-31 09:10:24 +00001198 TyD = Type;
1199 }
1200 }
1201 }
1202
Douglas Gregora3b624a2010-01-19 06:46:48 +00001203 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001204 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1205 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1206 return true;
1207 }
John McCallb5a0d312009-12-21 10:41:20 +00001208 }
1209
Douglas Gregora3b624a2010-01-19 06:46:48 +00001210 if (BaseType.isNull()) {
1211 BaseType = Context.getTypeDeclType(TyD);
1212 if (SS.isSet()) {
1213 NestedNameSpecifier *Qualifier =
1214 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001215
Douglas Gregora3b624a2010-01-19 06:46:48 +00001216 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001217 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001218 }
John McCallb5a0d312009-12-21 10:41:20 +00001219 }
1220 }
Mike Stump11289f42009-09-09 15:08:12 +00001221
John McCallbcd03502009-12-07 02:54:59 +00001222 if (!TInfo)
1223 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001224
John McCallbcd03502009-12-07 02:54:59 +00001225 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001226 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001227}
1228
John McCalle22a04a2009-11-04 23:02:40 +00001229/// Checks an initializer expression for use of uninitialized fields, such as
1230/// containing the field that is being initialized. Returns true if there is an
1231/// uninitialized field was used an updates the SourceLocation parameter; false
1232/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001233static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001234 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001235 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001236 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1237
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001238 if (isa<CallExpr>(S)) {
1239 // Do not descend into function calls or constructors, as the use
1240 // of an uninitialized field may be valid. One would have to inspect
1241 // the contents of the function/ctor to determine if it is safe or not.
1242 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1243 // may be safe, depending on what the function/ctor does.
1244 return false;
1245 }
1246 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1247 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001248
1249 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1250 // The member expression points to a static data member.
1251 assert(VD->isStaticDataMember() &&
1252 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001253 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001254 return false;
1255 }
1256
1257 if (isa<EnumConstantDecl>(RhsField)) {
1258 // The member expression points to an enum.
1259 return false;
1260 }
1261
John McCalle22a04a2009-11-04 23:02:40 +00001262 if (RhsField == LhsField) {
1263 // Initializing a field with itself. Throw a warning.
1264 // But wait; there are exceptions!
1265 // Exception #1: The field may not belong to this record.
1266 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001267 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001268 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1269 // Even though the field matches, it does not belong to this record.
1270 return false;
1271 }
1272 // None of the exceptions triggered; return true to indicate an
1273 // uninitialized field was used.
1274 *L = ME->getMemberLoc();
1275 return true;
1276 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001277 } else if (isa<SizeOfAlignOfExpr>(S)) {
1278 // sizeof/alignof doesn't reference contents, do not warn.
1279 return false;
1280 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1281 // address-of doesn't reference contents (the pointer may be dereferenced
1282 // in the same expression but it would be rare; and weird).
1283 if (UOE->getOpcode() == UO_AddrOf)
1284 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001285 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001286 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1287 it != e; ++it) {
1288 if (!*it) {
1289 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001290 continue;
1291 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001292 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1293 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001294 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001295 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001296}
1297
John McCallfaf5fb42010-08-26 23:41:50 +00001298MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001299Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001300 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001301 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001302 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001303 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1304 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1305 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001306 "Member must be a FieldDecl or IndirectFieldDecl");
1307
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001308 if (Member->isInvalidDecl())
1309 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001310
John McCalle22a04a2009-11-04 23:02:40 +00001311 // Diagnose value-uses of fields to initialize themselves, e.g.
1312 // foo(foo)
1313 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001314 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001315 for (unsigned i = 0; i < NumArgs; ++i) {
1316 SourceLocation L;
1317 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1318 // FIXME: Return true in the case when other fields are used before being
1319 // uninitialized. For example, let this field be the i'th field. When
1320 // initializing the i'th field, throw a warning if any of the >= i'th
1321 // fields are used, as they are not yet initialized.
1322 // Right now we are only handling the case where the i'th field uses
1323 // itself in its initializer.
1324 Diag(L, diag::warn_field_is_uninit);
1325 }
1326 }
1327
Eli Friedman8e1433b2009-07-29 19:44:27 +00001328 bool HasDependentArg = false;
1329 for (unsigned i = 0; i < NumArgs; i++)
1330 HasDependentArg |= Args[i]->isTypeDependent();
1331
Chandler Carruthd44c3102010-12-06 09:23:57 +00001332 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001333 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001334 // Can't check initialization for a member of dependent type or when
1335 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001336 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1337 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001338
1339 // Erase any temporaries within this evaluation context; we're not
1340 // going to track them in the AST, since we'll be rebuilding the
1341 // ASTs during template instantiation.
1342 ExprTemporaries.erase(
1343 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1344 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001345 } else {
1346 // Initialize the member.
1347 InitializedEntity MemberEntity =
1348 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1349 : InitializedEntity::InitializeMember(IndirectMember, 0);
1350 InitializationKind Kind =
1351 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001352
Chandler Carruthd44c3102010-12-06 09:23:57 +00001353 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1354
1355 ExprResult MemberInit =
1356 InitSeq.Perform(*this, MemberEntity, Kind,
1357 MultiExprArg(*this, Args, NumArgs), 0);
1358 if (MemberInit.isInvalid())
1359 return true;
1360
1361 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1362
1363 // C++0x [class.base.init]p7:
1364 // The initialization of each base and member constitutes a
1365 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001366 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001367 if (MemberInit.isInvalid())
1368 return true;
1369
1370 // If we are in a dependent context, template instantiation will
1371 // perform this type-checking again. Just save the arguments that we
1372 // received in a ParenListExpr.
1373 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1374 // of the information that we have about the member
1375 // initializer. However, deconstructing the ASTs is a dicey process,
1376 // and this approach is far more likely to get the corner cases right.
1377 if (CurContext->isDependentContext())
1378 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1379 RParenLoc);
1380 else
1381 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001382 }
1383
Chandler Carruthd44c3102010-12-06 09:23:57 +00001384 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001385 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001386 IdLoc, LParenLoc, Init,
1387 RParenLoc);
1388 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001389 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001390 IdLoc, LParenLoc, Init,
1391 RParenLoc);
1392 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001393}
1394
John McCallfaf5fb42010-08-26 23:41:50 +00001395MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001396Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1397 Expr **Args, unsigned NumArgs,
1398 SourceLocation LParenLoc,
1399 SourceLocation RParenLoc,
1400 CXXRecordDecl *ClassDecl,
1401 SourceLocation EllipsisLoc) {
1402 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1403 if (!LangOpts.CPlusPlus0x)
1404 return Diag(Loc, diag::err_delegation_0x_only)
1405 << TInfo->getTypeLoc().getLocalSourceRange();
1406
1407 return Diag(Loc, diag::err_delegation_unimplemented)
1408 << TInfo->getTypeLoc().getLocalSourceRange();
1409}
1410
1411MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001412Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001413 Expr **Args, unsigned NumArgs,
1414 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001415 CXXRecordDecl *ClassDecl,
1416 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001417 bool HasDependentArg = false;
1418 for (unsigned i = 0; i < NumArgs; i++)
1419 HasDependentArg |= Args[i]->isTypeDependent();
1420
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001421 SourceLocation BaseLoc
1422 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1423
1424 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1425 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1426 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1427
1428 // C++ [class.base.init]p2:
1429 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001430 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001431 // of that class, the mem-initializer is ill-formed. A
1432 // mem-initializer-list can initialize a base class using any
1433 // name that denotes that base class type.
1434 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1435
Douglas Gregor44e7df62011-01-04 00:32:56 +00001436 if (EllipsisLoc.isValid()) {
1437 // This is a pack expansion.
1438 if (!BaseType->containsUnexpandedParameterPack()) {
1439 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1440 << SourceRange(BaseLoc, RParenLoc);
1441
1442 EllipsisLoc = SourceLocation();
1443 }
1444 } else {
1445 // Check for any unexpanded parameter packs.
1446 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1447 return true;
1448
1449 for (unsigned I = 0; I != NumArgs; ++I)
1450 if (DiagnoseUnexpandedParameterPack(Args[I]))
1451 return true;
1452 }
1453
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001454 // Check for direct and virtual base classes.
1455 const CXXBaseSpecifier *DirectBaseSpec = 0;
1456 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1457 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001458 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1459 BaseType))
1460 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1461 LParenLoc, RParenLoc, ClassDecl,
1462 EllipsisLoc);
1463
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001464 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1465 VirtualBaseSpec);
1466
1467 // C++ [base.class.init]p2:
1468 // Unless the mem-initializer-id names a nonstatic data member of the
1469 // constructor's class or a direct or virtual base of that class, the
1470 // mem-initializer is ill-formed.
1471 if (!DirectBaseSpec && !VirtualBaseSpec) {
1472 // If the class has any dependent bases, then it's possible that
1473 // one of those types will resolve to the same type as
1474 // BaseType. Therefore, just treat this as a dependent base
1475 // class initialization. FIXME: Should we try to check the
1476 // initialization anyway? It seems odd.
1477 if (ClassDecl->hasAnyDependentBases())
1478 Dependent = true;
1479 else
1480 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1481 << BaseType << Context.getTypeDeclType(ClassDecl)
1482 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1483 }
1484 }
1485
1486 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001487 // Can't check initialization for a base of dependent type or when
1488 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001489 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001490 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1491 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001492
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001493 // Erase any temporaries within this evaluation context; we're not
1494 // going to track them in the AST, since we'll be rebuilding the
1495 // ASTs during template instantiation.
1496 ExprTemporaries.erase(
1497 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1498 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001499
Alexis Hunt1d792652011-01-08 20:30:50 +00001500 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001501 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001502 LParenLoc,
1503 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001504 RParenLoc,
1505 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001506 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001507
1508 // C++ [base.class.init]p2:
1509 // If a mem-initializer-id is ambiguous because it designates both
1510 // a direct non-virtual base class and an inherited virtual base
1511 // class, the mem-initializer is ill-formed.
1512 if (DirectBaseSpec && VirtualBaseSpec)
1513 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001514 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001515
1516 CXXBaseSpecifier *BaseSpec
1517 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1518 if (!BaseSpec)
1519 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1520
1521 // Initialize the base.
1522 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001523 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001524 InitializationKind Kind =
1525 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1526
1527 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1528
John McCalldadc5752010-08-24 06:29:42 +00001529 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001530 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001531 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001532 if (BaseInit.isInvalid())
1533 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001534
1535 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001536
1537 // C++0x [class.base.init]p7:
1538 // The initialization of each base and member constitutes a
1539 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001540 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001541 if (BaseInit.isInvalid())
1542 return true;
1543
1544 // If we are in a dependent context, template instantiation will
1545 // perform this type-checking again. Just save the arguments that we
1546 // received in a ParenListExpr.
1547 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1548 // of the information that we have about the base
1549 // initializer. However, deconstructing the ASTs is a dicey process,
1550 // and this approach is far more likely to get the corner cases right.
1551 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001552 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001553 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1554 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001555 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001556 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001557 LParenLoc,
1558 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001559 RParenLoc,
1560 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001561 }
1562
Alexis Hunt1d792652011-01-08 20:30:50 +00001563 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001564 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001565 LParenLoc,
1566 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001567 RParenLoc,
1568 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001569}
1570
Anders Carlsson1b00e242010-04-23 03:10:23 +00001571/// ImplicitInitializerKind - How an implicit base or member initializer should
1572/// initialize its base or member.
1573enum ImplicitInitializerKind {
1574 IIK_Default,
1575 IIK_Copy,
1576 IIK_Move
1577};
1578
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001579static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001580BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001581 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001582 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001583 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001584 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001585 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001586 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1587 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001588
John McCalldadc5752010-08-24 06:29:42 +00001589 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001590
1591 switch (ImplicitInitKind) {
1592 case IIK_Default: {
1593 InitializationKind InitKind
1594 = InitializationKind::CreateDefault(Constructor->getLocation());
1595 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1596 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001597 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001598 break;
1599 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001600
Anders Carlsson1b00e242010-04-23 03:10:23 +00001601 case IIK_Copy: {
1602 ParmVarDecl *Param = Constructor->getParamDecl(0);
1603 QualType ParamType = Param->getType().getNonReferenceType();
1604
1605 Expr *CopyCtorArg =
1606 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001607 Constructor->getLocation(), ParamType,
1608 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001609
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001610 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001611 QualType ArgTy =
1612 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1613 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001614
1615 CXXCastPath BasePath;
1616 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001617 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001618 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001619 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001620
Anders Carlsson1b00e242010-04-23 03:10:23 +00001621 InitializationKind InitKind
1622 = InitializationKind::CreateDirect(Constructor->getLocation(),
1623 SourceLocation(), SourceLocation());
1624 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1625 &CopyCtorArg, 1);
1626 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001627 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001628 break;
1629 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001630
Anders Carlsson1b00e242010-04-23 03:10:23 +00001631 case IIK_Move:
1632 assert(false && "Unhandled initializer kind!");
1633 }
John McCallb268a282010-08-23 23:25:46 +00001634
Douglas Gregora40433a2010-12-07 00:41:46 +00001635 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001636 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001637 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001638
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001639 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001640 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001641 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1642 SourceLocation()),
1643 BaseSpec->isVirtual(),
1644 SourceLocation(),
1645 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001646 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001647 SourceLocation());
1648
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001649 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001650}
1651
Anders Carlsson3c1db572010-04-23 02:15:47 +00001652static bool
1653BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001654 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001655 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001656 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001657 if (Field->isInvalidDecl())
1658 return true;
1659
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001660 SourceLocation Loc = Constructor->getLocation();
1661
Anders Carlsson423f5d82010-04-23 16:04:08 +00001662 if (ImplicitInitKind == IIK_Copy) {
1663 ParmVarDecl *Param = Constructor->getParamDecl(0);
1664 QualType ParamType = Param->getType().getNonReferenceType();
1665
1666 Expr *MemberExprBase =
1667 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001668 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001669
1670 // Build a reference to this field within the parameter.
1671 CXXScopeSpec SS;
1672 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1673 Sema::LookupMemberName);
1674 MemberLookup.addDecl(Field, AS_public);
1675 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001676 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001677 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001678 ParamType, Loc,
1679 /*IsArrow=*/false,
1680 SS,
1681 /*FirstQualifierInScope=*/0,
1682 MemberLookup,
1683 /*TemplateArgs=*/0);
1684 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001685 return true;
1686
Douglas Gregor94f9a482010-05-05 05:51:00 +00001687 // When the field we are copying is an array, create index variables for
1688 // each dimension of the array. We use these index variables to subscript
1689 // the source array, and other clients (e.g., CodeGen) will perform the
1690 // necessary iteration with these index variables.
1691 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1692 QualType BaseType = Field->getType();
1693 QualType SizeType = SemaRef.Context.getSizeType();
1694 while (const ConstantArrayType *Array
1695 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1696 // Create the iteration variable for this array index.
1697 IdentifierInfo *IterationVarName = 0;
1698 {
1699 llvm::SmallString<8> Str;
1700 llvm::raw_svector_ostream OS(Str);
1701 OS << "__i" << IndexVariables.size();
1702 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1703 }
1704 VarDecl *IterationVar
1705 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1706 IterationVarName, SizeType,
1707 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001708 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001709 IndexVariables.push_back(IterationVar);
1710
1711 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001712 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001713 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001714 assert(!IterationVarRef.isInvalid() &&
1715 "Reference to invented variable cannot fail!");
1716
1717 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001718 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001719 Loc,
John McCallb268a282010-08-23 23:25:46 +00001720 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001721 Loc);
1722 if (CopyCtorArg.isInvalid())
1723 return true;
1724
1725 BaseType = Array->getElementType();
1726 }
1727
1728 // Construct the entity that we will be initializing. For an array, this
1729 // will be first element in the array, which may require several levels
1730 // of array-subscript entities.
1731 llvm::SmallVector<InitializedEntity, 4> Entities;
1732 Entities.reserve(1 + IndexVariables.size());
1733 Entities.push_back(InitializedEntity::InitializeMember(Field));
1734 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1735 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1736 0,
1737 Entities.back()));
1738
1739 // Direct-initialize to use the copy constructor.
1740 InitializationKind InitKind =
1741 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1742
1743 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1744 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1745 &CopyCtorArgE, 1);
1746
John McCalldadc5752010-08-24 06:29:42 +00001747 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001748 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001749 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001750 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001751 if (MemberInit.isInvalid())
1752 return true;
1753
1754 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001755 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001756 MemberInit.takeAs<Expr>(), Loc,
1757 IndexVariables.data(),
1758 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001759 return false;
1760 }
1761
Anders Carlsson423f5d82010-04-23 16:04:08 +00001762 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1763
Anders Carlsson3c1db572010-04-23 02:15:47 +00001764 QualType FieldBaseElementType =
1765 SemaRef.Context.getBaseElementType(Field->getType());
1766
Anders Carlsson3c1db572010-04-23 02:15:47 +00001767 if (FieldBaseElementType->isRecordType()) {
1768 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001769 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001770 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001771
1772 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001773 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001774 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001775
Douglas Gregora40433a2010-12-07 00:41:46 +00001776 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001777 if (MemberInit.isInvalid())
1778 return true;
1779
1780 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001781 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001782 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001783 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001784 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001785 return false;
1786 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001787
1788 if (FieldBaseElementType->isReferenceType()) {
1789 SemaRef.Diag(Constructor->getLocation(),
1790 diag::err_uninitialized_member_in_ctor)
1791 << (int)Constructor->isImplicit()
1792 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1793 << 0 << Field->getDeclName();
1794 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1795 return true;
1796 }
1797
1798 if (FieldBaseElementType.isConstQualified()) {
1799 SemaRef.Diag(Constructor->getLocation(),
1800 diag::err_uninitialized_member_in_ctor)
1801 << (int)Constructor->isImplicit()
1802 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1803 << 1 << Field->getDeclName();
1804 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1805 return true;
1806 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001807
1808 // Nothing to initialize.
1809 CXXMemberInit = 0;
1810 return false;
1811}
John McCallbc83b3f2010-05-20 23:23:51 +00001812
1813namespace {
1814struct BaseAndFieldInfo {
1815 Sema &S;
1816 CXXConstructorDecl *Ctor;
1817 bool AnyErrorsInInits;
1818 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001819 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1820 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001821
1822 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1823 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1824 // FIXME: Handle implicit move constructors.
1825 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1826 IIK = IIK_Copy;
1827 else
1828 IIK = IIK_Default;
1829 }
1830};
1831}
1832
1833static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1834 FieldDecl *Top, FieldDecl *Field) {
1835
Chandler Carruth139e9622010-06-30 02:59:29 +00001836 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001837 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001838 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001839 return false;
1840 }
1841
1842 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1843 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1844 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001845 CXXRecordDecl *FieldClassDecl
1846 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001847
1848 // Even though union members never have non-trivial default
1849 // constructions in C++03, we still build member initializers for aggregate
1850 // record types which can be union members, and C++0x allows non-trivial
1851 // default constructors for union members, so we ensure that only one
1852 // member is initialized for these.
1853 if (FieldClassDecl->isUnion()) {
1854 // First check for an explicit initializer for one field.
1855 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1856 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001857 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001858 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001859
1860 // Once we've initialized a field of an anonymous union, the union
1861 // field in the class is also initialized, so exit immediately.
1862 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001863 } else if ((*FA)->isAnonymousStructOrUnion()) {
1864 if (CollectFieldInitializer(Info, Top, *FA))
1865 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001866 }
1867 }
1868
1869 // Fallthrough and construct a default initializer for the union as
1870 // a whole, which can call its default constructor if such a thing exists
1871 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1872 // behavior going forward with C++0x, when anonymous unions there are
1873 // finalized, we should revisit this.
1874 } else {
1875 // For structs, we simply descend through to initialize all members where
1876 // necessary.
1877 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1878 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1879 if (CollectFieldInitializer(Info, Top, *FA))
1880 return true;
1881 }
1882 }
John McCallbc83b3f2010-05-20 23:23:51 +00001883 }
1884
1885 // Don't try to build an implicit initializer if there were semantic
1886 // errors in any of the initializers (and therefore we might be
1887 // missing some that the user actually wrote).
1888 if (Info.AnyErrorsInInits)
1889 return false;
1890
Alexis Hunt1d792652011-01-08 20:30:50 +00001891 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001892 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1893 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001894
Francois Pichetd583da02010-12-04 09:14:42 +00001895 if (Init)
1896 Info.AllToInit.push_back(Init);
1897
John McCallbc83b3f2010-05-20 23:23:51 +00001898 return false;
1899}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001900
Eli Friedman9cf6b592009-11-09 19:20:36 +00001901bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001902Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1903 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001904 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001905 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001906 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001907 // Just store the initializers as written, they will be checked during
1908 // instantiation.
1909 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001910 Constructor->setNumCtorInitializers(NumInitializers);
1911 CXXCtorInitializer **baseOrMemberInitializers =
1912 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001913 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001914 NumInitializers * sizeof(CXXCtorInitializer*));
1915 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001916 }
1917
1918 return false;
1919 }
1920
John McCallbc83b3f2010-05-20 23:23:51 +00001921 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001922
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001923 // We need to build the initializer AST according to order of construction
1924 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001925 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001926 if (!ClassDecl)
1927 return true;
1928
Eli Friedman9cf6b592009-11-09 19:20:36 +00001929 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001931 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001932 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001933
1934 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001935 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001936 else
Francois Pichetd583da02010-12-04 09:14:42 +00001937 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001938 }
1939
Anders Carlsson43c64af2010-04-21 19:52:01 +00001940 // Keep track of the direct virtual bases.
1941 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1942 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1943 E = ClassDecl->bases_end(); I != E; ++I) {
1944 if (I->isVirtual())
1945 DirectVBases.insert(I);
1946 }
1947
Anders Carlssondb0a9652010-04-02 06:26:44 +00001948 // Push virtual bases before others.
1949 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1950 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1951
Alexis Hunt1d792652011-01-08 20:30:50 +00001952 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001953 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1954 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001955 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001956 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00001957 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001958 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001959 VBase, IsInheritedVirtualBase,
1960 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001961 HadError = true;
1962 continue;
1963 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001964
John McCallbc83b3f2010-05-20 23:23:51 +00001965 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001966 }
1967 }
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCallbc83b3f2010-05-20 23:23:51 +00001969 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001970 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1971 E = ClassDecl->bases_end(); Base != E; ++Base) {
1972 // Virtuals are in the virtual base list and already constructed.
1973 if (Base->isVirtual())
1974 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001975
Alexis Hunt1d792652011-01-08 20:30:50 +00001976 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001977 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1978 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001979 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001980 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001981 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001982 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001983 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001984 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001985 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001986 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001987
John McCallbc83b3f2010-05-20 23:23:51 +00001988 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001989 }
1990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
John McCallbc83b3f2010-05-20 23:23:51 +00001992 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001993 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001994 E = ClassDecl->field_end(); Field != E; ++Field) {
1995 if ((*Field)->getType()->isIncompleteArrayType()) {
1996 assert(ClassDecl->hasFlexibleArrayMember() &&
1997 "Incomplete array type is not valid");
1998 continue;
1999 }
John McCallbc83b3f2010-05-20 23:23:51 +00002000 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002001 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
John McCallbc83b3f2010-05-20 23:23:51 +00002004 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002005 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002006 Constructor->setNumCtorInitializers(NumInitializers);
2007 CXXCtorInitializer **baseOrMemberInitializers =
2008 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002009 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002010 NumInitializers * sizeof(CXXCtorInitializer*));
2011 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002012
John McCalla6309952010-03-16 21:39:52 +00002013 // Constructors implicitly reference the base and member
2014 // destructors.
2015 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2016 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002017 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002018
2019 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002020}
2021
Eli Friedman952c15d2009-07-21 19:28:10 +00002022static void *GetKeyForTopLevelField(FieldDecl *Field) {
2023 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002025 if (RT->getDecl()->isAnonymousStructOrUnion())
2026 return static_cast<void *>(RT->getDecl());
2027 }
2028 return static_cast<void *>(Field);
2029}
2030
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002031static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002032 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002033}
2034
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002035static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002036 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002037 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002038 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002039
Eli Friedman952c15d2009-07-21 19:28:10 +00002040 // For fields injected into the class via declaration of an anonymous union,
2041 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002042 FieldDecl *Field = Member->getAnyMember();
2043
John McCall23eebd92010-04-10 09:28:51 +00002044 // If the field is a member of an anonymous struct or union, our key
2045 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002046 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002047 if (RD->isAnonymousStructOrUnion()) {
2048 while (true) {
2049 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2050 if (Parent->isAnonymousStructOrUnion())
2051 RD = Parent;
2052 else
2053 break;
2054 }
2055
Anders Carlsson83ac3122010-03-30 16:19:37 +00002056 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Anders Carlssona942dcd2010-03-30 15:39:27 +00002059 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002060}
2061
Anders Carlssone857b292010-04-02 03:37:03 +00002062static void
2063DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002064 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002065 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002066 unsigned NumInits) {
2067 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002068 return;
Mike Stump11289f42009-09-09 15:08:12 +00002069
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002070 // Don't check initializers order unless the warning is enabled at the
2071 // location of at least one initializer.
2072 bool ShouldCheckOrder = false;
2073 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002074 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002075 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2076 Init->getSourceLocation())
2077 != Diagnostic::Ignored) {
2078 ShouldCheckOrder = true;
2079 break;
2080 }
2081 }
2082 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002083 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002084
John McCallbb7b6582010-04-10 07:37:23 +00002085 // Build the list of bases and members in the order that they'll
2086 // actually be initialized. The explicit initializers should be in
2087 // this same order but may be missing things.
2088 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002089
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002090 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2091
John McCallbb7b6582010-04-10 07:37:23 +00002092 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002093 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002094 ClassDecl->vbases_begin(),
2095 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002096 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002097
John McCallbb7b6582010-04-10 07:37:23 +00002098 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002099 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002100 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002101 if (Base->isVirtual())
2102 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002103 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002104 }
Mike Stump11289f42009-09-09 15:08:12 +00002105
John McCallbb7b6582010-04-10 07:37:23 +00002106 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002107 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2108 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002109 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002110
John McCallbb7b6582010-04-10 07:37:23 +00002111 unsigned NumIdealInits = IdealInitKeys.size();
2112 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002113
Alexis Hunt1d792652011-01-08 20:30:50 +00002114 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002115 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002116 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002117 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002118
2119 // Scan forward to try to find this initializer in the idealized
2120 // initializers list.
2121 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2122 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002123 break;
John McCallbb7b6582010-04-10 07:37:23 +00002124
2125 // If we didn't find this initializer, it must be because we
2126 // scanned past it on a previous iteration. That can only
2127 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002128 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002129 Sema::SemaDiagnosticBuilder D =
2130 SemaRef.Diag(PrevInit->getSourceLocation(),
2131 diag::warn_initializer_out_of_order);
2132
Francois Pichetd583da02010-12-04 09:14:42 +00002133 if (PrevInit->isAnyMemberInitializer())
2134 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002135 else
2136 D << 1 << PrevInit->getBaseClassInfo()->getType();
2137
Francois Pichetd583da02010-12-04 09:14:42 +00002138 if (Init->isAnyMemberInitializer())
2139 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002140 else
2141 D << 1 << Init->getBaseClassInfo()->getType();
2142
2143 // Move back to the initializer's location in the ideal list.
2144 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2145 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002146 break;
John McCallbb7b6582010-04-10 07:37:23 +00002147
2148 assert(IdealIndex != NumIdealInits &&
2149 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002150 }
John McCallbb7b6582010-04-10 07:37:23 +00002151
2152 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002153 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002154}
2155
John McCall23eebd92010-04-10 09:28:51 +00002156namespace {
2157bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002158 CXXCtorInitializer *Init,
2159 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002160 if (!PrevInit) {
2161 PrevInit = Init;
2162 return false;
2163 }
2164
2165 if (FieldDecl *Field = Init->getMember())
2166 S.Diag(Init->getSourceLocation(),
2167 diag::err_multiple_mem_initialization)
2168 << Field->getDeclName()
2169 << Init->getSourceRange();
2170 else {
John McCall424cec92011-01-19 06:33:43 +00002171 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002172 assert(BaseClass && "neither field nor base");
2173 S.Diag(Init->getSourceLocation(),
2174 diag::err_multiple_base_initialization)
2175 << QualType(BaseClass, 0)
2176 << Init->getSourceRange();
2177 }
2178 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2179 << 0 << PrevInit->getSourceRange();
2180
2181 return true;
2182}
2183
Alexis Hunt1d792652011-01-08 20:30:50 +00002184typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002185typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2186
2187bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002188 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002189 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002190 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002191 RecordDecl *Parent = Field->getParent();
2192 if (!Parent->isAnonymousStructOrUnion())
2193 return false;
2194
2195 NamedDecl *Child = Field;
2196 do {
2197 if (Parent->isUnion()) {
2198 UnionEntry &En = Unions[Parent];
2199 if (En.first && En.first != Child) {
2200 S.Diag(Init->getSourceLocation(),
2201 diag::err_multiple_mem_union_initialization)
2202 << Field->getDeclName()
2203 << Init->getSourceRange();
2204 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2205 << 0 << En.second->getSourceRange();
2206 return true;
2207 } else if (!En.first) {
2208 En.first = Child;
2209 En.second = Init;
2210 }
2211 }
2212
2213 Child = Parent;
2214 Parent = cast<RecordDecl>(Parent->getDeclContext());
2215 } while (Parent->isAnonymousStructOrUnion());
2216
2217 return false;
2218}
2219}
2220
Anders Carlssone857b292010-04-02 03:37:03 +00002221/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002222void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002223 SourceLocation ColonLoc,
2224 MemInitTy **meminits, unsigned NumMemInits,
2225 bool AnyErrors) {
2226 if (!ConstructorDecl)
2227 return;
2228
2229 AdjustDeclIfTemplate(ConstructorDecl);
2230
2231 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002232 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002233
2234 if (!Constructor) {
2235 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2236 return;
2237 }
2238
Alexis Hunt1d792652011-01-08 20:30:50 +00002239 CXXCtorInitializer **MemInits =
2240 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002241
2242 // Mapping for the duplicate initializers check.
2243 // For member initializers, this is keyed with a FieldDecl*.
2244 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002245 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002246
2247 // Mapping for the inconsistent anonymous-union initializers check.
2248 RedundantUnionMap MemberUnions;
2249
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002250 bool HadError = false;
2251 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002252 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002253
Abramo Bagnara341d7832010-05-26 18:09:23 +00002254 // Set the source order index.
2255 Init->setSourceOrder(i);
2256
Francois Pichetd583da02010-12-04 09:14:42 +00002257 if (Init->isAnyMemberInitializer()) {
2258 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002259 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2260 CheckRedundantUnionInit(*this, Init, MemberUnions))
2261 HadError = true;
2262 } else {
2263 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2264 if (CheckRedundantInit(*this, Init, Members[Key]))
2265 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002266 }
Anders Carlssone857b292010-04-02 03:37:03 +00002267 }
2268
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002269 if (HadError)
2270 return;
2271
Anders Carlssone857b292010-04-02 03:37:03 +00002272 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002273
Alexis Hunt1d792652011-01-08 20:30:50 +00002274 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002275}
2276
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002277void
John McCalla6309952010-03-16 21:39:52 +00002278Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2279 CXXRecordDecl *ClassDecl) {
2280 // Ignore dependent contexts.
2281 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002282 return;
John McCall1064d7e2010-03-16 05:22:47 +00002283
2284 // FIXME: all the access-control diagnostics are positioned on the
2285 // field/base declaration. That's probably good; that said, the
2286 // user might reasonably want to know why the destructor is being
2287 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002288
Anders Carlssondee9a302009-11-17 04:44:12 +00002289 // Non-static data members.
2290 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2291 E = ClassDecl->field_end(); I != E; ++I) {
2292 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002293 if (Field->isInvalidDecl())
2294 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002295 QualType FieldType = Context.getBaseElementType(Field->getType());
2296
2297 const RecordType* RT = FieldType->getAs<RecordType>();
2298 if (!RT)
2299 continue;
2300
2301 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2302 if (FieldClassDecl->hasTrivialDestructor())
2303 continue;
2304
Douglas Gregore71edda2010-07-01 22:47:18 +00002305 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002306 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002307 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002308 << Field->getDeclName()
2309 << FieldType);
2310
John McCalla6309952010-03-16 21:39:52 +00002311 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002312 }
2313
John McCall1064d7e2010-03-16 05:22:47 +00002314 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2315
Anders Carlssondee9a302009-11-17 04:44:12 +00002316 // Bases.
2317 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2318 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002319 // Bases are always records in a well-formed non-dependent class.
2320 const RecordType *RT = Base->getType()->getAs<RecordType>();
2321
2322 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002323 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002324 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002325
2326 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002327 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002328 if (BaseClassDecl->hasTrivialDestructor())
2329 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002330
Douglas Gregore71edda2010-07-01 22:47:18 +00002331 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002332
2333 // FIXME: caret should be on the start of the class name
2334 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002335 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002336 << Base->getType()
2337 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002338
John McCalla6309952010-03-16 21:39:52 +00002339 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002340 }
2341
2342 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002343 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2344 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002345
2346 // Bases are always records in a well-formed non-dependent class.
2347 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2348
2349 // Ignore direct virtual bases.
2350 if (DirectVirtualBases.count(RT))
2351 continue;
2352
Anders Carlssondee9a302009-11-17 04:44:12 +00002353 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002354 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002355 if (BaseClassDecl->hasTrivialDestructor())
2356 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002357
Douglas Gregore71edda2010-07-01 22:47:18 +00002358 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002359 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002360 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002361 << VBase->getType());
2362
John McCalla6309952010-03-16 21:39:52 +00002363 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002364 }
2365}
2366
John McCall48871652010-08-21 09:40:31 +00002367void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002368 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002369 return;
Mike Stump11289f42009-09-09 15:08:12 +00002370
Mike Stump11289f42009-09-09 15:08:12 +00002371 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002372 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002373 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002374}
2375
Mike Stump11289f42009-09-09 15:08:12 +00002376bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002377 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002378 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002379 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002380 else
John McCall02db245d2010-08-18 09:41:07 +00002381 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002382}
2383
Anders Carlssoneabf7702009-08-27 00:13:57 +00002384bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002385 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002386 if (!getLangOptions().CPlusPlus)
2387 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002388
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002389 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002390 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002391
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002392 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002393 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002394 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002395 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002396
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002397 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002398 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002399 }
Mike Stump11289f42009-09-09 15:08:12 +00002400
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002401 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002402 if (!RT)
2403 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002404
John McCall67da35c2010-02-04 22:26:26 +00002405 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002406
John McCall02db245d2010-08-18 09:41:07 +00002407 // We can't answer whether something is abstract until it has a
2408 // definition. If it's currently being defined, we'll walk back
2409 // over all the declarations when we have a full definition.
2410 const CXXRecordDecl *Def = RD->getDefinition();
2411 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002412 return false;
2413
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002414 if (!RD->isAbstract())
2415 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002416
Anders Carlssoneabf7702009-08-27 00:13:57 +00002417 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002418 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002419
John McCall02db245d2010-08-18 09:41:07 +00002420 return true;
2421}
2422
2423void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2424 // Check if we've already emitted the list of pure virtual functions
2425 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002426 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002427 return;
Mike Stump11289f42009-09-09 15:08:12 +00002428
Douglas Gregor4165bd62010-03-23 23:47:56 +00002429 CXXFinalOverriderMap FinalOverriders;
2430 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002431
Anders Carlssona2f74f32010-06-03 01:00:02 +00002432 // Keep a set of seen pure methods so we won't diagnose the same method
2433 // more than once.
2434 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2435
Douglas Gregor4165bd62010-03-23 23:47:56 +00002436 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2437 MEnd = FinalOverriders.end();
2438 M != MEnd;
2439 ++M) {
2440 for (OverridingMethods::iterator SO = M->second.begin(),
2441 SOEnd = M->second.end();
2442 SO != SOEnd; ++SO) {
2443 // C++ [class.abstract]p4:
2444 // A class is abstract if it contains or inherits at least one
2445 // pure virtual function for which the final overrider is pure
2446 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002447
Douglas Gregor4165bd62010-03-23 23:47:56 +00002448 //
2449 if (SO->second.size() != 1)
2450 continue;
2451
2452 if (!SO->second.front().Method->isPure())
2453 continue;
2454
Anders Carlssona2f74f32010-06-03 01:00:02 +00002455 if (!SeenPureMethods.insert(SO->second.front().Method))
2456 continue;
2457
Douglas Gregor4165bd62010-03-23 23:47:56 +00002458 Diag(SO->second.front().Method->getLocation(),
2459 diag::note_pure_virtual_function)
2460 << SO->second.front().Method->getDeclName();
2461 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002462 }
2463
2464 if (!PureVirtualClassDiagSet)
2465 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2466 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002467}
2468
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002469namespace {
John McCall02db245d2010-08-18 09:41:07 +00002470struct AbstractUsageInfo {
2471 Sema &S;
2472 CXXRecordDecl *Record;
2473 CanQualType AbstractType;
2474 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002475
John McCall02db245d2010-08-18 09:41:07 +00002476 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2477 : S(S), Record(Record),
2478 AbstractType(S.Context.getCanonicalType(
2479 S.Context.getTypeDeclType(Record))),
2480 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002481
John McCall02db245d2010-08-18 09:41:07 +00002482 void DiagnoseAbstractType() {
2483 if (Invalid) return;
2484 S.DiagnoseAbstractType(Record);
2485 Invalid = true;
2486 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002487
John McCall02db245d2010-08-18 09:41:07 +00002488 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2489};
2490
2491struct CheckAbstractUsage {
2492 AbstractUsageInfo &Info;
2493 const NamedDecl *Ctx;
2494
2495 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2496 : Info(Info), Ctx(Ctx) {}
2497
2498 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2499 switch (TL.getTypeLocClass()) {
2500#define ABSTRACT_TYPELOC(CLASS, PARENT)
2501#define TYPELOC(CLASS, PARENT) \
2502 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2503#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002504 }
John McCall02db245d2010-08-18 09:41:07 +00002505 }
Mike Stump11289f42009-09-09 15:08:12 +00002506
John McCall02db245d2010-08-18 09:41:07 +00002507 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2508 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2509 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2510 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2511 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002512 }
John McCall02db245d2010-08-18 09:41:07 +00002513 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002514
John McCall02db245d2010-08-18 09:41:07 +00002515 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2516 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2517 }
Mike Stump11289f42009-09-09 15:08:12 +00002518
John McCall02db245d2010-08-18 09:41:07 +00002519 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2520 // Visit the type parameters from a permissive context.
2521 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2522 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2523 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2524 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2525 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2526 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002527 }
John McCall02db245d2010-08-18 09:41:07 +00002528 }
Mike Stump11289f42009-09-09 15:08:12 +00002529
John McCall02db245d2010-08-18 09:41:07 +00002530 // Visit pointee types from a permissive context.
2531#define CheckPolymorphic(Type) \
2532 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2533 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2534 }
2535 CheckPolymorphic(PointerTypeLoc)
2536 CheckPolymorphic(ReferenceTypeLoc)
2537 CheckPolymorphic(MemberPointerTypeLoc)
2538 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002539
John McCall02db245d2010-08-18 09:41:07 +00002540 /// Handle all the types we haven't given a more specific
2541 /// implementation for above.
2542 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2543 // Every other kind of type that we haven't called out already
2544 // that has an inner type is either (1) sugar or (2) contains that
2545 // inner type in some way as a subobject.
2546 if (TypeLoc Next = TL.getNextTypeLoc())
2547 return Visit(Next, Sel);
2548
2549 // If there's no inner type and we're in a permissive context,
2550 // don't diagnose.
2551 if (Sel == Sema::AbstractNone) return;
2552
2553 // Check whether the type matches the abstract type.
2554 QualType T = TL.getType();
2555 if (T->isArrayType()) {
2556 Sel = Sema::AbstractArrayType;
2557 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002558 }
John McCall02db245d2010-08-18 09:41:07 +00002559 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2560 if (CT != Info.AbstractType) return;
2561
2562 // It matched; do some magic.
2563 if (Sel == Sema::AbstractArrayType) {
2564 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2565 << T << TL.getSourceRange();
2566 } else {
2567 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2568 << Sel << T << TL.getSourceRange();
2569 }
2570 Info.DiagnoseAbstractType();
2571 }
2572};
2573
2574void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2575 Sema::AbstractDiagSelID Sel) {
2576 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2577}
2578
2579}
2580
2581/// Check for invalid uses of an abstract type in a method declaration.
2582static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2583 CXXMethodDecl *MD) {
2584 // No need to do the check on definitions, which require that
2585 // the return/param types be complete.
2586 if (MD->isThisDeclarationADefinition())
2587 return;
2588
2589 // For safety's sake, just ignore it if we don't have type source
2590 // information. This should never happen for non-implicit methods,
2591 // but...
2592 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2593 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2594}
2595
2596/// Check for invalid uses of an abstract type within a class definition.
2597static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2598 CXXRecordDecl *RD) {
2599 for (CXXRecordDecl::decl_iterator
2600 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2601 Decl *D = *I;
2602 if (D->isImplicit()) continue;
2603
2604 // Methods and method templates.
2605 if (isa<CXXMethodDecl>(D)) {
2606 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2607 } else if (isa<FunctionTemplateDecl>(D)) {
2608 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2609 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2610
2611 // Fields and static variables.
2612 } else if (isa<FieldDecl>(D)) {
2613 FieldDecl *FD = cast<FieldDecl>(D);
2614 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2615 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2616 } else if (isa<VarDecl>(D)) {
2617 VarDecl *VD = cast<VarDecl>(D);
2618 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2619 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2620
2621 // Nested classes and class templates.
2622 } else if (isa<CXXRecordDecl>(D)) {
2623 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2624 } else if (isa<ClassTemplateDecl>(D)) {
2625 CheckAbstractClassUsage(Info,
2626 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2627 }
2628 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002629}
2630
Douglas Gregorc99f1552009-12-03 18:33:45 +00002631/// \brief Perform semantic checks on a class definition that has been
2632/// completing, introducing implicitly-declared members, checking for
2633/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002634void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002635 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002636 return;
2637
John McCall02db245d2010-08-18 09:41:07 +00002638 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2639 AbstractUsageInfo Info(*this, Record);
2640 CheckAbstractClassUsage(Info, Record);
2641 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002642
2643 // If this is not an aggregate type and has no user-declared constructor,
2644 // complain about any non-static data members of reference or const scalar
2645 // type, since they will never get initializers.
2646 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2647 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2648 bool Complained = false;
2649 for (RecordDecl::field_iterator F = Record->field_begin(),
2650 FEnd = Record->field_end();
2651 F != FEnd; ++F) {
2652 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002653 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002654 if (!Complained) {
2655 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2656 << Record->getTagKind() << Record;
2657 Complained = true;
2658 }
2659
2660 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2661 << F->getType()->isReferenceType()
2662 << F->getDeclName();
2663 }
2664 }
2665 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002666
2667 if (Record->isDynamicClass())
2668 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002669
2670 if (Record->getIdentifier()) {
2671 // C++ [class.mem]p13:
2672 // If T is the name of a class, then each of the following shall have a
2673 // name different from T:
2674 // - every member of every anonymous union that is a member of class T.
2675 //
2676 // C++ [class.mem]p14:
2677 // In addition, if class T has a user-declared constructor (12.1), every
2678 // non-static data member of class T shall have a name different from T.
2679 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002680 R.first != R.second; ++R.first) {
2681 NamedDecl *D = *R.first;
2682 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2683 isa<IndirectFieldDecl>(D)) {
2684 Diag(D->getLocation(), diag::err_member_name_of_class)
2685 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002686 break;
2687 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002688 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002689 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002690}
2691
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002692void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002693 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002694 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002695 SourceLocation RBrac,
2696 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002697 if (!TagDecl)
2698 return;
Mike Stump11289f42009-09-09 15:08:12 +00002699
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002700 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002701
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002702 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002703 // strict aliasing violation!
2704 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002705 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002706
Douglas Gregor0be31a22010-07-02 17:43:08 +00002707 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002708 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002709}
2710
Douglas Gregor95755162010-07-01 05:10:53 +00002711namespace {
2712 /// \brief Helper class that collects exception specifications for
2713 /// implicitly-declared special member functions.
2714 class ImplicitExceptionSpecification {
2715 ASTContext &Context;
2716 bool AllowsAllExceptions;
2717 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2718 llvm::SmallVector<QualType, 4> Exceptions;
2719
2720 public:
2721 explicit ImplicitExceptionSpecification(ASTContext &Context)
2722 : Context(Context), AllowsAllExceptions(false) { }
2723
2724 /// \brief Whether the special member function should have any
2725 /// exception specification at all.
2726 bool hasExceptionSpecification() const {
2727 return !AllowsAllExceptions;
2728 }
2729
2730 /// \brief Whether the special member function should have a
2731 /// throw(...) exception specification (a Microsoft extension).
2732 bool hasAnyExceptionSpecification() const {
2733 return false;
2734 }
2735
2736 /// \brief The number of exceptions in the exception specification.
2737 unsigned size() const { return Exceptions.size(); }
2738
2739 /// \brief The set of exceptions in the exception specification.
2740 const QualType *data() const { return Exceptions.data(); }
2741
2742 /// \brief Note that
2743 void CalledDecl(CXXMethodDecl *Method) {
2744 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002745 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002746 return;
2747
2748 const FunctionProtoType *Proto
2749 = Method->getType()->getAs<FunctionProtoType>();
2750
2751 // If this function can throw any exceptions, make a note of that.
2752 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2753 AllowsAllExceptions = true;
2754 ExceptionsSeen.clear();
2755 Exceptions.clear();
2756 return;
2757 }
2758
2759 // Record the exceptions in this function's exception specification.
2760 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2761 EEnd = Proto->exception_end();
2762 E != EEnd; ++E)
2763 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2764 Exceptions.push_back(*E);
2765 }
2766 };
2767}
2768
2769
Douglas Gregor05379422008-11-03 17:51:48 +00002770/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2771/// special functions, such as the default constructor, copy
2772/// constructor, or destructor, to the given C++ class (C++
2773/// [special]p1). This routine can only be executed just before the
2774/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002775void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002776 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002777 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002778
Douglas Gregor54be3392010-07-01 17:57:27 +00002779 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002780 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002781
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002782 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2783 ++ASTContext::NumImplicitCopyAssignmentOperators;
2784
2785 // If we have a dynamic class, then the copy assignment operator may be
2786 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2787 // it shows up in the right place in the vtable and that we diagnose
2788 // problems with the implicit exception specification.
2789 if (ClassDecl->isDynamicClass())
2790 DeclareImplicitCopyAssignment(ClassDecl);
2791 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002792
Douglas Gregor7454c562010-07-02 20:37:36 +00002793 if (!ClassDecl->hasUserDeclaredDestructor()) {
2794 ++ASTContext::NumImplicitDestructors;
2795
2796 // If we have a dynamic class, then the destructor may be virtual, so we
2797 // have to declare the destructor immediately. This ensures that, e.g., it
2798 // shows up in the right place in the vtable and that we diagnose problems
2799 // with the implicit exception specification.
2800 if (ClassDecl->isDynamicClass())
2801 DeclareImplicitDestructor(ClassDecl);
2802 }
Douglas Gregor05379422008-11-03 17:51:48 +00002803}
2804
John McCall48871652010-08-21 09:40:31 +00002805void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002806 if (!D)
2807 return;
2808
2809 TemplateParameterList *Params = 0;
2810 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2811 Params = Template->getTemplateParameters();
2812 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2813 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2814 Params = PartialSpec->getTemplateParameters();
2815 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002816 return;
2817
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002818 for (TemplateParameterList::iterator Param = Params->begin(),
2819 ParamEnd = Params->end();
2820 Param != ParamEnd; ++Param) {
2821 NamedDecl *Named = cast<NamedDecl>(*Param);
2822 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002823 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002824 IdResolver.AddDecl(Named);
2825 }
2826 }
2827}
2828
John McCall48871652010-08-21 09:40:31 +00002829void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002830 if (!RecordD) return;
2831 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002832 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002833 PushDeclContext(S, Record);
2834}
2835
John McCall48871652010-08-21 09:40:31 +00002836void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002837 if (!RecordD) return;
2838 PopDeclContext();
2839}
2840
Douglas Gregor4d87df52008-12-16 21:30:33 +00002841/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2842/// parsing a top-level (non-nested) C++ class, and we are now
2843/// parsing those parts of the given Method declaration that could
2844/// not be parsed earlier (C++ [class.mem]p2), such as default
2845/// arguments. This action should enter the scope of the given
2846/// Method declaration as if we had just parsed the qualified method
2847/// name. However, it should not bring the parameters into scope;
2848/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002849void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002850}
2851
2852/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2853/// C++ method declaration. We're (re-)introducing the given
2854/// function parameter into scope for use in parsing later parts of
2855/// the method declaration. For example, we could see an
2856/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002857void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002858 if (!ParamD)
2859 return;
Mike Stump11289f42009-09-09 15:08:12 +00002860
John McCall48871652010-08-21 09:40:31 +00002861 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002862
2863 // If this parameter has an unparsed default argument, clear it out
2864 // to make way for the parsed default argument.
2865 if (Param->hasUnparsedDefaultArg())
2866 Param->setDefaultArg(0);
2867
John McCall48871652010-08-21 09:40:31 +00002868 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002869 if (Param->getDeclName())
2870 IdResolver.AddDecl(Param);
2871}
2872
2873/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2874/// processing the delayed method declaration for Method. The method
2875/// declaration is now considered finished. There may be a separate
2876/// ActOnStartOfFunctionDef action later (not necessarily
2877/// immediately!) for this method, if it was also defined inside the
2878/// class body.
John McCall48871652010-08-21 09:40:31 +00002879void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002880 if (!MethodD)
2881 return;
Mike Stump11289f42009-09-09 15:08:12 +00002882
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002883 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002884
John McCall48871652010-08-21 09:40:31 +00002885 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002886
2887 // Now that we have our default arguments, check the constructor
2888 // again. It could produce additional diagnostics or affect whether
2889 // the class has implicitly-declared destructors, among other
2890 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002891 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2892 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002893
2894 // Check the default arguments, which we may have added.
2895 if (!Method->isInvalidDecl())
2896 CheckCXXDefaultArguments(Method);
2897}
2898
Douglas Gregor831c93f2008-11-05 20:51:48 +00002899/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002900/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002901/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002902/// emit diagnostics and set the invalid bit to true. In any case, the type
2903/// will be updated to reflect a well-formed type for the constructor and
2904/// returned.
2905QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002906 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002907 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002908
2909 // C++ [class.ctor]p3:
2910 // A constructor shall not be virtual (10.3) or static (9.4). A
2911 // constructor can be invoked for a const, volatile or const
2912 // volatile object. A constructor shall not be declared const,
2913 // volatile, or const volatile (9.3.2).
2914 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002915 if (!D.isInvalidType())
2916 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2917 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2918 << SourceRange(D.getIdentifierLoc());
2919 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002920 }
John McCall8e7d6562010-08-26 03:08:43 +00002921 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002922 if (!D.isInvalidType())
2923 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2924 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2925 << SourceRange(D.getIdentifierLoc());
2926 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002927 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002930 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002931 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002932 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002933 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2934 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002935 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002936 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2937 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002938 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002939 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2940 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002941 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Douglas Gregor831c93f2008-11-05 20:51:48 +00002944 // Rebuild the function type "R" without any type qualifiers (in
2945 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002946 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002947 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002948 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2949 return R;
2950
2951 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2952 EPI.TypeQuals = 0;
2953
Chris Lattner38378bf2009-04-25 08:28:21 +00002954 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002955 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002956}
2957
Douglas Gregor4d87df52008-12-16 21:30:33 +00002958/// CheckConstructor - Checks a fully-formed constructor for
2959/// well-formedness, issuing any diagnostics required. Returns true if
2960/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002961void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002962 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002963 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2964 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002965 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002966
2967 // C++ [class.copy]p3:
2968 // A declaration of a constructor for a class X is ill-formed if
2969 // its first parameter is of type (optionally cv-qualified) X and
2970 // either there are no other parameters or else all other
2971 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002972 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002973 ((Constructor->getNumParams() == 1) ||
2974 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002975 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2976 Constructor->getTemplateSpecializationKind()
2977 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002978 QualType ParamType = Constructor->getParamDecl(0)->getType();
2979 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2980 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002981 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002982 const char *ConstRef
2983 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2984 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002985 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002986 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002987
2988 // FIXME: Rather that making the constructor invalid, we should endeavor
2989 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002990 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002991 }
2992 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002993}
2994
John McCalldeb646e2010-08-04 01:04:25 +00002995/// CheckDestructor - Checks a fully-formed destructor definition for
2996/// well-formedness, issuing any diagnostics required. Returns true
2997/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002998bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002999 CXXRecordDecl *RD = Destructor->getParent();
3000
3001 if (Destructor->isVirtual()) {
3002 SourceLocation Loc;
3003
3004 if (!Destructor->isImplicit())
3005 Loc = Destructor->getLocation();
3006 else
3007 Loc = RD->getLocation();
3008
3009 // If we have a virtual destructor, look up the deallocation function
3010 FunctionDecl *OperatorDelete = 0;
3011 DeclarationName Name =
3012 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003013 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003014 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003015
3016 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003017
3018 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003019 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003020
3021 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003022}
3023
Mike Stump11289f42009-09-09 15:08:12 +00003024static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003025FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3026 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3027 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003028 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003029}
3030
Douglas Gregor831c93f2008-11-05 20:51:48 +00003031/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3032/// the well-formednes of the destructor declarator @p D with type @p
3033/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003034/// emit diagnostics and set the declarator to invalid. Even if this happens,
3035/// will be updated to reflect a well-formed type for the destructor and
3036/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003037QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003038 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003039 // C++ [class.dtor]p1:
3040 // [...] A typedef-name that names a class is a class-name
3041 // (7.1.3); however, a typedef-name that names a class shall not
3042 // be used as the identifier in the declarator for a destructor
3043 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003044 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003045 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003046 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003047 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003048
3049 // C++ [class.dtor]p2:
3050 // A destructor is used to destroy objects of its class type. A
3051 // destructor takes no parameters, and no return type can be
3052 // specified for it (not even void). The address of a destructor
3053 // shall not be taken. A destructor shall not be static. A
3054 // destructor can be invoked for a const, volatile or const
3055 // volatile object. A destructor shall not be declared const,
3056 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003057 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003058 if (!D.isInvalidType())
3059 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3060 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003061 << SourceRange(D.getIdentifierLoc())
3062 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3063
John McCall8e7d6562010-08-26 03:08:43 +00003064 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003065 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003066 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003067 // Destructors don't have return types, but the parser will
3068 // happily parse something like:
3069 //
3070 // class X {
3071 // float ~X();
3072 // };
3073 //
3074 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003075 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3076 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3077 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003078 }
Mike Stump11289f42009-09-09 15:08:12 +00003079
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003080 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003081 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003082 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3084 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003085 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3087 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003088 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003089 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3090 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003091 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003092 }
3093
3094 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003095 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003096 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3097
3098 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003099 FTI.freeArgs();
3100 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003101 }
3102
Mike Stump11289f42009-09-09 15:08:12 +00003103 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003104 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003105 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003106 D.setInvalidType();
3107 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003108
3109 // Rebuild the function type "R" without any type qualifiers or
3110 // parameters (in case any of the errors above fired) and with
3111 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003112 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003113 if (!D.isInvalidType())
3114 return R;
3115
Douglas Gregor95755162010-07-01 05:10:53 +00003116 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003117 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3118 EPI.Variadic = false;
3119 EPI.TypeQuals = 0;
3120 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003121}
3122
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003123/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3124/// well-formednes of the conversion function declarator @p D with
3125/// type @p R. If there are any errors in the declarator, this routine
3126/// will emit diagnostics and return true. Otherwise, it will return
3127/// false. Either way, the type @p R will be updated to reflect a
3128/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003129void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003130 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003131 // C++ [class.conv.fct]p1:
3132 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003133 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003134 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003135 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003136 if (!D.isInvalidType())
3137 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3138 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3139 << SourceRange(D.getIdentifierLoc());
3140 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003141 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003142 }
John McCall212fa2e2010-04-13 00:04:31 +00003143
3144 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3145
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003146 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003147 // Conversion functions don't have return types, but the parser will
3148 // happily parse something like:
3149 //
3150 // class X {
3151 // float operator bool();
3152 // };
3153 //
3154 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003155 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3156 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3157 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003158 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003159 }
3160
John McCall212fa2e2010-04-13 00:04:31 +00003161 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3162
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003163 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003164 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003165 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3166
3167 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003168 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003169 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003170 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003171 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003172 D.setInvalidType();
3173 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003174
John McCall212fa2e2010-04-13 00:04:31 +00003175 // Diagnose "&operator bool()" and other such nonsense. This
3176 // is actually a gcc extension which we don't support.
3177 if (Proto->getResultType() != ConvType) {
3178 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3179 << Proto->getResultType();
3180 D.setInvalidType();
3181 ConvType = Proto->getResultType();
3182 }
3183
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003184 // C++ [class.conv.fct]p4:
3185 // The conversion-type-id shall not represent a function type nor
3186 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003187 if (ConvType->isArrayType()) {
3188 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3189 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003190 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003191 } else if (ConvType->isFunctionType()) {
3192 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3193 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003194 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003195 }
3196
3197 // Rebuild the function type "R" without any parameters (in case any
3198 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003199 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003200 if (D.isInvalidType())
3201 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003202
Douglas Gregor5fb53972009-01-14 15:45:31 +00003203 // C++0x explicit conversion operators.
3204 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003205 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003206 diag::warn_explicit_conversion_functions)
3207 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003208}
3209
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003210/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3211/// the declaration of the given C++ conversion function. This routine
3212/// is responsible for recording the conversion function in the C++
3213/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003214Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003215 assert(Conversion && "Expected to receive a conversion function declaration");
3216
Douglas Gregor4287b372008-12-12 08:25:50 +00003217 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003218
3219 // Make sure we aren't redeclaring the conversion function.
3220 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003221
3222 // C++ [class.conv.fct]p1:
3223 // [...] A conversion function is never used to convert a
3224 // (possibly cv-qualified) object to the (possibly cv-qualified)
3225 // same object type (or a reference to it), to a (possibly
3226 // cv-qualified) base class of that type (or a reference to it),
3227 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003228 // FIXME: Suppress this warning if the conversion function ends up being a
3229 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003230 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003231 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003232 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003233 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003234 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3235 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003236 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003237 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003238 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3239 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003240 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003241 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003242 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003243 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003244 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003245 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003246 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003247 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003248 }
3249
Douglas Gregor457104e2010-09-29 04:25:11 +00003250 if (FunctionTemplateDecl *ConversionTemplate
3251 = Conversion->getDescribedFunctionTemplate())
3252 return ConversionTemplate;
3253
John McCall48871652010-08-21 09:40:31 +00003254 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003255}
3256
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003257//===----------------------------------------------------------------------===//
3258// Namespace Handling
3259//===----------------------------------------------------------------------===//
3260
John McCallb1be5232010-08-26 09:15:37 +00003261
3262
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003263/// ActOnStartNamespaceDef - This is called at the start of a namespace
3264/// definition.
John McCall48871652010-08-21 09:40:31 +00003265Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003266 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003267 SourceLocation IdentLoc,
3268 IdentifierInfo *II,
3269 SourceLocation LBrace,
3270 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003271 // anonymous namespace starts at its left brace
3272 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3273 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003274 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003275 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003276
3277 Scope *DeclRegionScope = NamespcScope->getParent();
3278
Anders Carlssona7bcade2010-02-07 01:09:23 +00003279 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3280
John McCall2faf32c2010-12-10 02:59:44 +00003281 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3282 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003283
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003284 if (II) {
3285 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003286 // The identifier in an original-namespace-definition shall not
3287 // have been previously defined in the declarative region in
3288 // which the original-namespace-definition appears. The
3289 // identifier in an original-namespace-definition is the name of
3290 // the namespace. Subsequently in that declarative region, it is
3291 // treated as an original-namespace-name.
3292 //
3293 // Since namespace names are unique in their scope, and we don't
3294 // look through using directives, just
3295 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3296 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003297
Douglas Gregor91f84212008-12-11 16:49:14 +00003298 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3299 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003300 if (Namespc->isInline() != OrigNS->isInline()) {
3301 // inline-ness must match
3302 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3303 << Namespc->isInline();
3304 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3305 Namespc->setInvalidDecl();
3306 // Recover by ignoring the new namespace's inline status.
3307 Namespc->setInline(OrigNS->isInline());
3308 }
3309
Douglas Gregor91f84212008-12-11 16:49:14 +00003310 // Attach this namespace decl to the chain of extended namespace
3311 // definitions.
3312 OrigNS->setNextNamespace(Namespc);
3313 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003314
Mike Stump11289f42009-09-09 15:08:12 +00003315 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003316 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003317 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003318 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003319 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003320 } else if (PrevDecl) {
3321 // This is an invalid name redefinition.
3322 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3323 << Namespc->getDeclName();
3324 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3325 Namespc->setInvalidDecl();
3326 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003327 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003328 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003329 // This is the first "real" definition of the namespace "std", so update
3330 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003331 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003332 // We had already defined a dummy namespace "std". Link this new
3333 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003334 StdNS->setNextNamespace(Namespc);
3335 StdNS->setLocation(IdentLoc);
3336 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003337 }
3338
3339 // Make our StdNamespace cache point at the first real definition of the
3340 // "std" namespace.
3341 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003342 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003343
3344 PushOnScopeChains(Namespc, DeclRegionScope);
3345 } else {
John McCall4fa53422009-10-01 00:25:31 +00003346 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003347 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003348
3349 // Link the anonymous namespace into its parent.
3350 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003351 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003352 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3353 PrevDecl = TU->getAnonymousNamespace();
3354 TU->setAnonymousNamespace(Namespc);
3355 } else {
3356 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3357 PrevDecl = ND->getAnonymousNamespace();
3358 ND->setAnonymousNamespace(Namespc);
3359 }
3360
3361 // Link the anonymous namespace with its previous declaration.
3362 if (PrevDecl) {
3363 assert(PrevDecl->isAnonymousNamespace());
3364 assert(!PrevDecl->getNextNamespace());
3365 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3366 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003367
3368 if (Namespc->isInline() != PrevDecl->isInline()) {
3369 // inline-ness must match
3370 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3371 << Namespc->isInline();
3372 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3373 Namespc->setInvalidDecl();
3374 // Recover by ignoring the new namespace's inline status.
3375 Namespc->setInline(PrevDecl->isInline());
3376 }
John McCall0db42252009-12-16 02:06:49 +00003377 }
John McCall4fa53422009-10-01 00:25:31 +00003378
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003379 CurContext->addDecl(Namespc);
3380
John McCall4fa53422009-10-01 00:25:31 +00003381 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3382 // behaves as if it were replaced by
3383 // namespace unique { /* empty body */ }
3384 // using namespace unique;
3385 // namespace unique { namespace-body }
3386 // where all occurrences of 'unique' in a translation unit are
3387 // replaced by the same identifier and this identifier differs
3388 // from all other identifiers in the entire program.
3389
3390 // We just create the namespace with an empty name and then add an
3391 // implicit using declaration, just like the standard suggests.
3392 //
3393 // CodeGen enforces the "universally unique" aspect by giving all
3394 // declarations semantically contained within an anonymous
3395 // namespace internal linkage.
3396
John McCall0db42252009-12-16 02:06:49 +00003397 if (!PrevDecl) {
3398 UsingDirectiveDecl* UD
3399 = UsingDirectiveDecl::Create(Context, CurContext,
3400 /* 'using' */ LBrace,
3401 /* 'namespace' */ SourceLocation(),
3402 /* qualifier */ SourceRange(),
3403 /* NNS */ NULL,
3404 /* identifier */ SourceLocation(),
3405 Namespc,
3406 /* Ancestor */ CurContext);
3407 UD->setImplicit();
3408 CurContext->addDecl(UD);
3409 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003410 }
3411
3412 // Although we could have an invalid decl (i.e. the namespace name is a
3413 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003414 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3415 // for the namespace has the declarations that showed up in that particular
3416 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003417 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003418 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003419}
3420
Sebastian Redla6602e92009-11-23 15:34:23 +00003421/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3422/// is a namespace alias, returns the namespace it points to.
3423static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3424 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3425 return AD->getNamespace();
3426 return dyn_cast_or_null<NamespaceDecl>(D);
3427}
3428
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003429/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3430/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003431void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003432 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3433 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3434 Namespc->setRBracLoc(RBrace);
3435 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003436 if (Namespc->hasAttr<VisibilityAttr>())
3437 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003438}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003439
John McCall28a0cf72010-08-25 07:42:41 +00003440CXXRecordDecl *Sema::getStdBadAlloc() const {
3441 return cast_or_null<CXXRecordDecl>(
3442 StdBadAlloc.get(Context.getExternalSource()));
3443}
3444
3445NamespaceDecl *Sema::getStdNamespace() const {
3446 return cast_or_null<NamespaceDecl>(
3447 StdNamespace.get(Context.getExternalSource()));
3448}
3449
Douglas Gregorcdf87022010-06-29 17:53:46 +00003450/// \brief Retrieve the special "std" namespace, which may require us to
3451/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003452NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003453 if (!StdNamespace) {
3454 // The "std" namespace has not yet been defined, so build one implicitly.
3455 StdNamespace = NamespaceDecl::Create(Context,
3456 Context.getTranslationUnitDecl(),
3457 SourceLocation(),
3458 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003459 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003460 }
3461
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003462 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003463}
3464
John McCall48871652010-08-21 09:40:31 +00003465Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003466 SourceLocation UsingLoc,
3467 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003468 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003469 SourceLocation IdentLoc,
3470 IdentifierInfo *NamespcName,
3471 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003472 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3473 assert(NamespcName && "Invalid NamespcName.");
3474 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003475
3476 // This can only happen along a recovery path.
3477 while (S->getFlags() & Scope::TemplateParamScope)
3478 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003479 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003480
Douglas Gregor889ceb72009-02-03 19:21:40 +00003481 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003482 NestedNameSpecifier *Qualifier = 0;
3483 if (SS.isSet())
3484 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3485
Douglas Gregor34074322009-01-14 22:20:51 +00003486 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003487 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3488 LookupParsedName(R, S, &SS);
3489 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003490 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003491
Douglas Gregorcdf87022010-06-29 17:53:46 +00003492 if (R.empty()) {
3493 // Allow "using namespace std;" or "using namespace ::std;" even if
3494 // "std" hasn't been defined yet, for GCC compatibility.
3495 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3496 NamespcName->isStr("std")) {
3497 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003498 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003499 R.resolveKind();
3500 }
3501 // Otherwise, attempt typo correction.
3502 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3503 CTC_NoKeywords, 0)) {
3504 if (R.getAsSingle<NamespaceDecl>() ||
3505 R.getAsSingle<NamespaceAliasDecl>()) {
3506 if (DeclContext *DC = computeDeclContext(SS, false))
3507 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3508 << NamespcName << DC << Corrected << SS.getRange()
3509 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3510 else
3511 Diag(IdentLoc, diag::err_using_directive_suggest)
3512 << NamespcName << Corrected
3513 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3514 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3515 << Corrected;
3516
3517 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003518 } else {
3519 R.clear();
3520 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003521 }
3522 }
3523 }
3524
John McCall9f3059a2009-10-09 21:13:30 +00003525 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003526 NamedDecl *Named = R.getFoundDecl();
3527 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3528 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003529 // C++ [namespace.udir]p1:
3530 // A using-directive specifies that the names in the nominated
3531 // namespace can be used in the scope in which the
3532 // using-directive appears after the using-directive. During
3533 // unqualified name lookup (3.4.1), the names appear as if they
3534 // were declared in the nearest enclosing namespace which
3535 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003536 // namespace. [Note: in this context, "contains" means "contains
3537 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003538
3539 // Find enclosing context containing both using-directive and
3540 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003541 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003542 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3543 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3544 CommonAncestor = CommonAncestor->getParent();
3545
Sebastian Redla6602e92009-11-23 15:34:23 +00003546 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003547 SS.getRange(),
3548 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003549 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003550 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003551 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003552 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003553 }
3554
Douglas Gregor889ceb72009-02-03 19:21:40 +00003555 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003556 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003557}
3558
3559void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3560 // If scope has associated entity, then using directive is at namespace
3561 // or translation unit scope. We add UsingDirectiveDecls, into
3562 // it's lookup structure.
3563 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003564 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003565 else
3566 // Otherwise it is block-sope. using-directives will affect lookup
3567 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003568 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003569}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003570
Douglas Gregorfec52632009-06-20 00:51:54 +00003571
John McCall48871652010-08-21 09:40:31 +00003572Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003573 AccessSpecifier AS,
3574 bool HasUsingKeyword,
3575 SourceLocation UsingLoc,
3576 CXXScopeSpec &SS,
3577 UnqualifiedId &Name,
3578 AttributeList *AttrList,
3579 bool IsTypeName,
3580 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003581 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003582
Douglas Gregor220f4272009-11-04 16:30:06 +00003583 switch (Name.getKind()) {
3584 case UnqualifiedId::IK_Identifier:
3585 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003586 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003587 case UnqualifiedId::IK_ConversionFunctionId:
3588 break;
3589
3590 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003591 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003592 // C++0x inherited constructors.
3593 if (getLangOptions().CPlusPlus0x) break;
3594
Douglas Gregor220f4272009-11-04 16:30:06 +00003595 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3596 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003597 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003598
3599 case UnqualifiedId::IK_DestructorName:
3600 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3601 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003602 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003603
3604 case UnqualifiedId::IK_TemplateId:
3605 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3606 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003607 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003608 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003609
3610 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3611 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003612 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003613 return 0;
John McCall3969e302009-12-08 07:46:18 +00003614
John McCalla0097262009-12-11 02:10:03 +00003615 // Warn about using declarations.
3616 // TODO: store that the declaration was written without 'using' and
3617 // talk about access decls instead of using decls in the
3618 // diagnostics.
3619 if (!HasUsingKeyword) {
3620 UsingLoc = Name.getSourceRange().getBegin();
3621
3622 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003623 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003624 }
3625
Douglas Gregorc4356532010-12-16 00:46:58 +00003626 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3627 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3628 return 0;
3629
John McCall3f746822009-11-17 05:59:44 +00003630 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003631 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003632 /* IsInstantiation */ false,
3633 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003634 if (UD)
3635 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003636
John McCall48871652010-08-21 09:40:31 +00003637 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003638}
3639
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003640/// \brief Determine whether a using declaration considers the given
3641/// declarations as "equivalent", e.g., if they are redeclarations of
3642/// the same entity or are both typedefs of the same type.
3643static bool
3644IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3645 bool &SuppressRedeclaration) {
3646 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3647 SuppressRedeclaration = false;
3648 return true;
3649 }
3650
3651 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3652 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3653 SuppressRedeclaration = true;
3654 return Context.hasSameType(TD1->getUnderlyingType(),
3655 TD2->getUnderlyingType());
3656 }
3657
3658 return false;
3659}
3660
3661
John McCall84d87672009-12-10 09:41:52 +00003662/// Determines whether to create a using shadow decl for a particular
3663/// decl, given the set of decls existing prior to this using lookup.
3664bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3665 const LookupResult &Previous) {
3666 // Diagnose finding a decl which is not from a base class of the
3667 // current class. We do this now because there are cases where this
3668 // function will silently decide not to build a shadow decl, which
3669 // will pre-empt further diagnostics.
3670 //
3671 // We don't need to do this in C++0x because we do the check once on
3672 // the qualifier.
3673 //
3674 // FIXME: diagnose the following if we care enough:
3675 // struct A { int foo; };
3676 // struct B : A { using A::foo; };
3677 // template <class T> struct C : A {};
3678 // template <class T> struct D : C<T> { using B::foo; } // <---
3679 // This is invalid (during instantiation) in C++03 because B::foo
3680 // resolves to the using decl in B, which is not a base class of D<T>.
3681 // We can't diagnose it immediately because C<T> is an unknown
3682 // specialization. The UsingShadowDecl in D<T> then points directly
3683 // to A::foo, which will look well-formed when we instantiate.
3684 // The right solution is to not collapse the shadow-decl chain.
3685 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3686 DeclContext *OrigDC = Orig->getDeclContext();
3687
3688 // Handle enums and anonymous structs.
3689 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3690 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3691 while (OrigRec->isAnonymousStructOrUnion())
3692 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3693
3694 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3695 if (OrigDC == CurContext) {
3696 Diag(Using->getLocation(),
3697 diag::err_using_decl_nested_name_specifier_is_current_class)
3698 << Using->getNestedNameRange();
3699 Diag(Orig->getLocation(), diag::note_using_decl_target);
3700 return true;
3701 }
3702
3703 Diag(Using->getNestedNameRange().getBegin(),
3704 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3705 << Using->getTargetNestedNameDecl()
3706 << cast<CXXRecordDecl>(CurContext)
3707 << Using->getNestedNameRange();
3708 Diag(Orig->getLocation(), diag::note_using_decl_target);
3709 return true;
3710 }
3711 }
3712
3713 if (Previous.empty()) return false;
3714
3715 NamedDecl *Target = Orig;
3716 if (isa<UsingShadowDecl>(Target))
3717 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3718
John McCalla17e83e2009-12-11 02:33:26 +00003719 // If the target happens to be one of the previous declarations, we
3720 // don't have a conflict.
3721 //
3722 // FIXME: but we might be increasing its access, in which case we
3723 // should redeclare it.
3724 NamedDecl *NonTag = 0, *Tag = 0;
3725 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3726 I != E; ++I) {
3727 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003728 bool Result;
3729 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3730 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003731
3732 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3733 }
3734
John McCall84d87672009-12-10 09:41:52 +00003735 if (Target->isFunctionOrFunctionTemplate()) {
3736 FunctionDecl *FD;
3737 if (isa<FunctionTemplateDecl>(Target))
3738 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3739 else
3740 FD = cast<FunctionDecl>(Target);
3741
3742 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003743 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003744 case Ovl_Overload:
3745 return false;
3746
3747 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003748 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003749 break;
3750
3751 // We found a decl with the exact signature.
3752 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003753 // If we're in a record, we want to hide the target, so we
3754 // return true (without a diagnostic) to tell the caller not to
3755 // build a shadow decl.
3756 if (CurContext->isRecord())
3757 return true;
3758
3759 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003760 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003761 break;
3762 }
3763
3764 Diag(Target->getLocation(), diag::note_using_decl_target);
3765 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3766 return true;
3767 }
3768
3769 // Target is not a function.
3770
John McCall84d87672009-12-10 09:41:52 +00003771 if (isa<TagDecl>(Target)) {
3772 // No conflict between a tag and a non-tag.
3773 if (!Tag) return false;
3774
John McCalle29c5cd2009-12-10 19:51:03 +00003775 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003776 Diag(Target->getLocation(), diag::note_using_decl_target);
3777 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3778 return true;
3779 }
3780
3781 // No conflict between a tag and a non-tag.
3782 if (!NonTag) return false;
3783
John McCalle29c5cd2009-12-10 19:51:03 +00003784 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003785 Diag(Target->getLocation(), diag::note_using_decl_target);
3786 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3787 return true;
3788}
3789
John McCall3f746822009-11-17 05:59:44 +00003790/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003791UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003792 UsingDecl *UD,
3793 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003794
3795 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003796 NamedDecl *Target = Orig;
3797 if (isa<UsingShadowDecl>(Target)) {
3798 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3799 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003800 }
3801
3802 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003803 = UsingShadowDecl::Create(Context, CurContext,
3804 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003805 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003806
3807 Shadow->setAccess(UD->getAccess());
3808 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3809 Shadow->setInvalidDecl();
3810
John McCall3f746822009-11-17 05:59:44 +00003811 if (S)
John McCall3969e302009-12-08 07:46:18 +00003812 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003813 else
John McCall3969e302009-12-08 07:46:18 +00003814 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003815
John McCall3969e302009-12-08 07:46:18 +00003816
John McCall84d87672009-12-10 09:41:52 +00003817 return Shadow;
3818}
John McCall3969e302009-12-08 07:46:18 +00003819
John McCall84d87672009-12-10 09:41:52 +00003820/// Hides a using shadow declaration. This is required by the current
3821/// using-decl implementation when a resolvable using declaration in a
3822/// class is followed by a declaration which would hide or override
3823/// one or more of the using decl's targets; for example:
3824///
3825/// struct Base { void foo(int); };
3826/// struct Derived : Base {
3827/// using Base::foo;
3828/// void foo(int);
3829/// };
3830///
3831/// The governing language is C++03 [namespace.udecl]p12:
3832///
3833/// When a using-declaration brings names from a base class into a
3834/// derived class scope, member functions in the derived class
3835/// override and/or hide member functions with the same name and
3836/// parameter types in a base class (rather than conflicting).
3837///
3838/// There are two ways to implement this:
3839/// (1) optimistically create shadow decls when they're not hidden
3840/// by existing declarations, or
3841/// (2) don't create any shadow decls (or at least don't make them
3842/// visible) until we've fully parsed/instantiated the class.
3843/// The problem with (1) is that we might have to retroactively remove
3844/// a shadow decl, which requires several O(n) operations because the
3845/// decl structures are (very reasonably) not designed for removal.
3846/// (2) avoids this but is very fiddly and phase-dependent.
3847void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003848 if (Shadow->getDeclName().getNameKind() ==
3849 DeclarationName::CXXConversionFunctionName)
3850 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3851
John McCall84d87672009-12-10 09:41:52 +00003852 // Remove it from the DeclContext...
3853 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003854
John McCall84d87672009-12-10 09:41:52 +00003855 // ...and the scope, if applicable...
3856 if (S) {
John McCall48871652010-08-21 09:40:31 +00003857 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003858 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003859 }
3860
John McCall84d87672009-12-10 09:41:52 +00003861 // ...and the using decl.
3862 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3863
3864 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003865 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003866}
3867
John McCalle61f2ba2009-11-18 02:36:19 +00003868/// Builds a using declaration.
3869///
3870/// \param IsInstantiation - Whether this call arises from an
3871/// instantiation of an unresolved using declaration. We treat
3872/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003873NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3874 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003875 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003876 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003877 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003878 bool IsInstantiation,
3879 bool IsTypeName,
3880 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003881 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003882 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003883 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003884
Anders Carlssonf038fc22009-08-28 05:49:21 +00003885 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003886
Anders Carlsson59140b32009-08-28 03:16:11 +00003887 if (SS.isEmpty()) {
3888 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003889 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003890 }
Mike Stump11289f42009-09-09 15:08:12 +00003891
John McCall84d87672009-12-10 09:41:52 +00003892 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003893 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003894 ForRedeclaration);
3895 Previous.setHideTags(false);
3896 if (S) {
3897 LookupName(Previous, S);
3898
3899 // It is really dumb that we have to do this.
3900 LookupResult::Filter F = Previous.makeFilter();
3901 while (F.hasNext()) {
3902 NamedDecl *D = F.next();
3903 if (!isDeclInScope(D, CurContext, S))
3904 F.erase();
3905 }
3906 F.done();
3907 } else {
3908 assert(IsInstantiation && "no scope in non-instantiation");
3909 assert(CurContext->isRecord() && "scope not record in instantiation");
3910 LookupQualifiedName(Previous, CurContext);
3911 }
3912
Mike Stump11289f42009-09-09 15:08:12 +00003913 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003914 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3915
John McCall84d87672009-12-10 09:41:52 +00003916 // Check for invalid redeclarations.
3917 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3918 return 0;
3919
3920 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003921 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3922 return 0;
3923
John McCall84c16cf2009-11-12 03:15:40 +00003924 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003925 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003926 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003927 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003928 // FIXME: not all declaration name kinds are legal here
3929 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3930 UsingLoc, TypenameLoc,
3931 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003932 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003933 } else {
3934 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003935 UsingLoc, SS.getRange(),
3936 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003937 }
John McCallb96ec562009-12-04 22:46:56 +00003938 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003939 D = UsingDecl::Create(Context, CurContext,
3940 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003941 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003942 }
John McCallb96ec562009-12-04 22:46:56 +00003943 D->setAccess(AS);
3944 CurContext->addDecl(D);
3945
3946 if (!LookupContext) return D;
3947 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003948
John McCall0b66eb32010-05-01 00:40:08 +00003949 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003950 UD->setInvalidDecl();
3951 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003952 }
3953
John McCall3969e302009-12-08 07:46:18 +00003954 // Look up the target name.
3955
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003956 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003957
John McCall3969e302009-12-08 07:46:18 +00003958 // Unlike most lookups, we don't always want to hide tag
3959 // declarations: tag names are visible through the using declaration
3960 // even if hidden by ordinary names, *except* in a dependent context
3961 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003962 if (!IsInstantiation)
3963 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003964
John McCall27b18f82009-11-17 02:14:36 +00003965 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003966
John McCall9f3059a2009-10-09 21:13:30 +00003967 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003968 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003969 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003970 UD->setInvalidDecl();
3971 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003972 }
3973
John McCallb96ec562009-12-04 22:46:56 +00003974 if (R.isAmbiguous()) {
3975 UD->setInvalidDecl();
3976 return UD;
3977 }
Mike Stump11289f42009-09-09 15:08:12 +00003978
John McCalle61f2ba2009-11-18 02:36:19 +00003979 if (IsTypeName) {
3980 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003981 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003982 Diag(IdentLoc, diag::err_using_typename_non_type);
3983 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3984 Diag((*I)->getUnderlyingDecl()->getLocation(),
3985 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003986 UD->setInvalidDecl();
3987 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003988 }
3989 } else {
3990 // If we asked for a non-typename and we got a type, error out,
3991 // but only if this is an instantiation of an unresolved using
3992 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003993 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003994 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3995 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003996 UD->setInvalidDecl();
3997 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003998 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003999 }
4000
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004001 // C++0x N2914 [namespace.udecl]p6:
4002 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004003 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004004 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4005 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004006 UD->setInvalidDecl();
4007 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004008 }
Mike Stump11289f42009-09-09 15:08:12 +00004009
John McCall84d87672009-12-10 09:41:52 +00004010 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4011 if (!CheckUsingShadowDecl(UD, *I, Previous))
4012 BuildUsingShadowDecl(S, UD, *I);
4013 }
John McCall3f746822009-11-17 05:59:44 +00004014
4015 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004016}
4017
John McCall84d87672009-12-10 09:41:52 +00004018/// Checks that the given using declaration is not an invalid
4019/// redeclaration. Note that this is checking only for the using decl
4020/// itself, not for any ill-formedness among the UsingShadowDecls.
4021bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4022 bool isTypeName,
4023 const CXXScopeSpec &SS,
4024 SourceLocation NameLoc,
4025 const LookupResult &Prev) {
4026 // C++03 [namespace.udecl]p8:
4027 // C++0x [namespace.udecl]p10:
4028 // A using-declaration is a declaration and can therefore be used
4029 // repeatedly where (and only where) multiple declarations are
4030 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004031 //
John McCall032092f2010-11-29 18:01:58 +00004032 // That's in non-member contexts.
4033 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004034 return false;
4035
4036 NestedNameSpecifier *Qual
4037 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4038
4039 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4040 NamedDecl *D = *I;
4041
4042 bool DTypename;
4043 NestedNameSpecifier *DQual;
4044 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4045 DTypename = UD->isTypeName();
4046 DQual = UD->getTargetNestedNameDecl();
4047 } else if (UnresolvedUsingValueDecl *UD
4048 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4049 DTypename = false;
4050 DQual = UD->getTargetNestedNameSpecifier();
4051 } else if (UnresolvedUsingTypenameDecl *UD
4052 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4053 DTypename = true;
4054 DQual = UD->getTargetNestedNameSpecifier();
4055 } else continue;
4056
4057 // using decls differ if one says 'typename' and the other doesn't.
4058 // FIXME: non-dependent using decls?
4059 if (isTypeName != DTypename) continue;
4060
4061 // using decls differ if they name different scopes (but note that
4062 // template instantiation can cause this check to trigger when it
4063 // didn't before instantiation).
4064 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4065 Context.getCanonicalNestedNameSpecifier(DQual))
4066 continue;
4067
4068 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004069 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004070 return true;
4071 }
4072
4073 return false;
4074}
4075
John McCall3969e302009-12-08 07:46:18 +00004076
John McCallb96ec562009-12-04 22:46:56 +00004077/// Checks that the given nested-name qualifier used in a using decl
4078/// in the current context is appropriately related to the current
4079/// scope. If an error is found, diagnoses it and returns true.
4080bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4081 const CXXScopeSpec &SS,
4082 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004083 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004084
John McCall3969e302009-12-08 07:46:18 +00004085 if (!CurContext->isRecord()) {
4086 // C++03 [namespace.udecl]p3:
4087 // C++0x [namespace.udecl]p8:
4088 // A using-declaration for a class member shall be a member-declaration.
4089
4090 // If we weren't able to compute a valid scope, it must be a
4091 // dependent class scope.
4092 if (!NamedContext || NamedContext->isRecord()) {
4093 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4094 << SS.getRange();
4095 return true;
4096 }
4097
4098 // Otherwise, everything is known to be fine.
4099 return false;
4100 }
4101
4102 // The current scope is a record.
4103
4104 // If the named context is dependent, we can't decide much.
4105 if (!NamedContext) {
4106 // FIXME: in C++0x, we can diagnose if we can prove that the
4107 // nested-name-specifier does not refer to a base class, which is
4108 // still possible in some cases.
4109
4110 // Otherwise we have to conservatively report that things might be
4111 // okay.
4112 return false;
4113 }
4114
4115 if (!NamedContext->isRecord()) {
4116 // Ideally this would point at the last name in the specifier,
4117 // but we don't have that level of source info.
4118 Diag(SS.getRange().getBegin(),
4119 diag::err_using_decl_nested_name_specifier_is_not_class)
4120 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4121 return true;
4122 }
4123
Douglas Gregor7c842292010-12-21 07:41:49 +00004124 if (!NamedContext->isDependentContext() &&
4125 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4126 return true;
4127
John McCall3969e302009-12-08 07:46:18 +00004128 if (getLangOptions().CPlusPlus0x) {
4129 // C++0x [namespace.udecl]p3:
4130 // In a using-declaration used as a member-declaration, the
4131 // nested-name-specifier shall name a base class of the class
4132 // being defined.
4133
4134 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4135 cast<CXXRecordDecl>(NamedContext))) {
4136 if (CurContext == NamedContext) {
4137 Diag(NameLoc,
4138 diag::err_using_decl_nested_name_specifier_is_current_class)
4139 << SS.getRange();
4140 return true;
4141 }
4142
4143 Diag(SS.getRange().getBegin(),
4144 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4145 << (NestedNameSpecifier*) SS.getScopeRep()
4146 << cast<CXXRecordDecl>(CurContext)
4147 << SS.getRange();
4148 return true;
4149 }
4150
4151 return false;
4152 }
4153
4154 // C++03 [namespace.udecl]p4:
4155 // A using-declaration used as a member-declaration shall refer
4156 // to a member of a base class of the class being defined [etc.].
4157
4158 // Salient point: SS doesn't have to name a base class as long as
4159 // lookup only finds members from base classes. Therefore we can
4160 // diagnose here only if we can prove that that can't happen,
4161 // i.e. if the class hierarchies provably don't intersect.
4162
4163 // TODO: it would be nice if "definitely valid" results were cached
4164 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4165 // need to be repeated.
4166
4167 struct UserData {
4168 llvm::DenseSet<const CXXRecordDecl*> Bases;
4169
4170 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4171 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4172 Data->Bases.insert(Base);
4173 return true;
4174 }
4175
4176 bool hasDependentBases(const CXXRecordDecl *Class) {
4177 return !Class->forallBases(collect, this);
4178 }
4179
4180 /// Returns true if the base is dependent or is one of the
4181 /// accumulated base classes.
4182 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4183 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4184 return !Data->Bases.count(Base);
4185 }
4186
4187 bool mightShareBases(const CXXRecordDecl *Class) {
4188 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4189 }
4190 };
4191
4192 UserData Data;
4193
4194 // Returns false if we find a dependent base.
4195 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4196 return false;
4197
4198 // Returns false if the class has a dependent base or if it or one
4199 // of its bases is present in the base set of the current context.
4200 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4201 return false;
4202
4203 Diag(SS.getRange().getBegin(),
4204 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4205 << (NestedNameSpecifier*) SS.getScopeRep()
4206 << cast<CXXRecordDecl>(CurContext)
4207 << SS.getRange();
4208
4209 return true;
John McCallb96ec562009-12-04 22:46:56 +00004210}
4211
John McCall48871652010-08-21 09:40:31 +00004212Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004213 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004214 SourceLocation AliasLoc,
4215 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004216 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004217 SourceLocation IdentLoc,
4218 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004219
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004220 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004221 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4222 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004223
Anders Carlssondca83c42009-03-28 06:23:46 +00004224 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004225 NamedDecl *PrevDecl
4226 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4227 ForRedeclaration);
4228 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4229 PrevDecl = 0;
4230
4231 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004232 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004233 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004234 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004235 // FIXME: At some point, we'll want to create the (redundant)
4236 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004237 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004238 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004239 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004240 }
Mike Stump11289f42009-09-09 15:08:12 +00004241
Anders Carlssondca83c42009-03-28 06:23:46 +00004242 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4243 diag::err_redefinition_different_kind;
4244 Diag(AliasLoc, DiagID) << Alias;
4245 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004246 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004247 }
4248
John McCall27b18f82009-11-17 02:14:36 +00004249 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004250 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004251
John McCall9f3059a2009-10-09 21:13:30 +00004252 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004253 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4254 CTC_NoKeywords, 0)) {
4255 if (R.getAsSingle<NamespaceDecl>() ||
4256 R.getAsSingle<NamespaceAliasDecl>()) {
4257 if (DeclContext *DC = computeDeclContext(SS, false))
4258 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4259 << Ident << DC << Corrected << SS.getRange()
4260 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4261 else
4262 Diag(IdentLoc, diag::err_using_directive_suggest)
4263 << Ident << Corrected
4264 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4265
4266 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4267 << Corrected;
4268
4269 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004270 } else {
4271 R.clear();
4272 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004273 }
4274 }
4275
4276 if (R.empty()) {
4277 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004278 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004279 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004280 }
Mike Stump11289f42009-09-09 15:08:12 +00004281
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004282 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004283 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4284 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004285 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004286 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004287
John McCalld8d0d432010-02-16 06:53:13 +00004288 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004289 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004290}
4291
Douglas Gregora57478e2010-05-01 15:04:51 +00004292namespace {
4293 /// \brief Scoped object used to handle the state changes required in Sema
4294 /// to implicitly define the body of a C++ member function;
4295 class ImplicitlyDefinedFunctionScope {
4296 Sema &S;
4297 DeclContext *PreviousContext;
4298
4299 public:
4300 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4301 : S(S), PreviousContext(S.CurContext)
4302 {
4303 S.CurContext = Method;
4304 S.PushFunctionScope();
4305 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4306 }
4307
4308 ~ImplicitlyDefinedFunctionScope() {
4309 S.PopExpressionEvaluationContext();
4310 S.PopFunctionOrBlockScope();
4311 S.CurContext = PreviousContext;
4312 }
4313 };
4314}
4315
Sebastian Redlc15c3262010-09-13 22:02:47 +00004316static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4317 CXXRecordDecl *D) {
4318 ASTContext &Context = Self.Context;
4319 QualType ClassType = Context.getTypeDeclType(D);
4320 DeclarationName ConstructorName
4321 = Context.DeclarationNames.getCXXConstructorName(
4322 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4323
4324 DeclContext::lookup_const_iterator Con, ConEnd;
4325 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4326 Con != ConEnd; ++Con) {
4327 // FIXME: In C++0x, a constructor template can be a default constructor.
4328 if (isa<FunctionTemplateDecl>(*Con))
4329 continue;
4330
4331 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4332 if (Constructor->isDefaultConstructor())
4333 return Constructor;
4334 }
4335 return 0;
4336}
4337
Douglas Gregor0be31a22010-07-02 17:43:08 +00004338CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4339 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004340 // C++ [class.ctor]p5:
4341 // A default constructor for a class X is a constructor of class X
4342 // that can be called without an argument. If there is no
4343 // user-declared constructor for class X, a default constructor is
4344 // implicitly declared. An implicitly-declared default constructor
4345 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004346 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4347 "Should not build implicit default constructor!");
4348
Douglas Gregor6d880b12010-07-01 22:31:05 +00004349 // C++ [except.spec]p14:
4350 // An implicitly declared special member function (Clause 12) shall have an
4351 // exception-specification. [...]
4352 ImplicitExceptionSpecification ExceptSpec(Context);
4353
4354 // Direct base-class destructors.
4355 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4356 BEnd = ClassDecl->bases_end();
4357 B != BEnd; ++B) {
4358 if (B->isVirtual()) // Handled below.
4359 continue;
4360
Douglas Gregor9672f922010-07-03 00:47:00 +00004361 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4362 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4363 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4364 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004365 else if (CXXConstructorDecl *Constructor
4366 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004367 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004368 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004369 }
4370
4371 // Virtual base-class destructors.
4372 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4373 BEnd = ClassDecl->vbases_end();
4374 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004375 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4376 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4377 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4378 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4379 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004380 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004381 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004382 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004383 }
4384
4385 // Field destructors.
4386 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4387 FEnd = ClassDecl->field_end();
4388 F != FEnd; ++F) {
4389 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004390 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4391 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4392 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4393 ExceptSpec.CalledDecl(
4394 DeclareImplicitDefaultConstructor(FieldClassDecl));
4395 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004396 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004397 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004398 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004399 }
John McCalldb40c7f2010-12-14 08:05:40 +00004400
4401 FunctionProtoType::ExtProtoInfo EPI;
4402 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4403 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4404 EPI.NumExceptions = ExceptSpec.size();
4405 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004406
4407 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004408 CanQualType ClassType
4409 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4410 DeclarationName Name
4411 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004412 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004413 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004414 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004415 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004416 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004417 /*TInfo=*/0,
4418 /*isExplicit=*/false,
4419 /*isInline=*/true,
4420 /*isImplicitlyDeclared=*/true);
4421 DefaultCon->setAccess(AS_public);
4422 DefaultCon->setImplicit();
4423 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004424
4425 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004426 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4427
Douglas Gregor0be31a22010-07-02 17:43:08 +00004428 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004429 PushOnScopeChains(DefaultCon, S, false);
4430 ClassDecl->addDecl(DefaultCon);
4431
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004432 return DefaultCon;
4433}
4434
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004435void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4436 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004437 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004438 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004439 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004440
Anders Carlsson423f5d82010-04-23 16:04:08 +00004441 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004442 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004443
Douglas Gregora57478e2010-05-01 15:04:51 +00004444 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004445 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004446 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004447 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004448 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004449 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004450 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004451 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004452 }
Douglas Gregor73193272010-09-20 16:48:21 +00004453
4454 SourceLocation Loc = Constructor->getLocation();
4455 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4456
4457 Constructor->setUsed();
4458 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004459}
4460
Douglas Gregor0be31a22010-07-02 17:43:08 +00004461CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004462 // C++ [class.dtor]p2:
4463 // If a class has no user-declared destructor, a destructor is
4464 // declared implicitly. An implicitly-declared destructor is an
4465 // inline public member of its class.
4466
4467 // C++ [except.spec]p14:
4468 // An implicitly declared special member function (Clause 12) shall have
4469 // an exception-specification.
4470 ImplicitExceptionSpecification ExceptSpec(Context);
4471
4472 // Direct base-class destructors.
4473 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4474 BEnd = ClassDecl->bases_end();
4475 B != BEnd; ++B) {
4476 if (B->isVirtual()) // Handled below.
4477 continue;
4478
4479 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4480 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004481 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004482 }
4483
4484 // Virtual base-class destructors.
4485 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4486 BEnd = ClassDecl->vbases_end();
4487 B != BEnd; ++B) {
4488 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4489 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004490 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004491 }
4492
4493 // Field destructors.
4494 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4495 FEnd = ClassDecl->field_end();
4496 F != FEnd; ++F) {
4497 if (const RecordType *RecordTy
4498 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4499 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004500 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004501 }
4502
Douglas Gregor7454c562010-07-02 20:37:36 +00004503 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004504 FunctionProtoType::ExtProtoInfo EPI;
4505 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4506 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4507 EPI.NumExceptions = ExceptSpec.size();
4508 EPI.Exceptions = ExceptSpec.data();
4509 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004510
4511 CanQualType ClassType
4512 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4513 DeclarationName Name
4514 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004515 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004516 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004517 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004518 /*isInline=*/true,
4519 /*isImplicitlyDeclared=*/true);
4520 Destructor->setAccess(AS_public);
4521 Destructor->setImplicit();
4522 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004523
4524 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004525 ++ASTContext::NumImplicitDestructorsDeclared;
4526
4527 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004528 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004529 PushOnScopeChains(Destructor, S, false);
4530 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004531
4532 // This could be uniqued if it ever proves significant.
4533 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4534
4535 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004536
Douglas Gregorf1203042010-07-01 19:09:28 +00004537 return Destructor;
4538}
4539
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004540void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004541 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004542 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004543 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004544 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004545 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004546
Douglas Gregor54818f02010-05-12 16:39:35 +00004547 if (Destructor->isInvalidDecl())
4548 return;
4549
Douglas Gregora57478e2010-05-01 15:04:51 +00004550 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004551
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004552 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004553 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4554 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004555
Douglas Gregor54818f02010-05-12 16:39:35 +00004556 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004557 Diag(CurrentLocation, diag::note_member_synthesized_at)
4558 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4559
4560 Destructor->setInvalidDecl();
4561 return;
4562 }
4563
Douglas Gregor73193272010-09-20 16:48:21 +00004564 SourceLocation Loc = Destructor->getLocation();
4565 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4566
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004567 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004568 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004569}
4570
Douglas Gregorb139cd52010-05-01 20:49:11 +00004571/// \brief Builds a statement that copies the given entity from \p From to
4572/// \c To.
4573///
4574/// This routine is used to copy the members of a class with an
4575/// implicitly-declared copy assignment operator. When the entities being
4576/// copied are arrays, this routine builds for loops to copy them.
4577///
4578/// \param S The Sema object used for type-checking.
4579///
4580/// \param Loc The location where the implicit copy is being generated.
4581///
4582/// \param T The type of the expressions being copied. Both expressions must
4583/// have this type.
4584///
4585/// \param To The expression we are copying to.
4586///
4587/// \param From The expression we are copying from.
4588///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004589/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4590/// Otherwise, it's a non-static member subobject.
4591///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004592/// \param Depth Internal parameter recording the depth of the recursion.
4593///
4594/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004595static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004596BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004597 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004598 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004599 // C++0x [class.copy]p30:
4600 // Each subobject is assigned in the manner appropriate to its type:
4601 //
4602 // - if the subobject is of class type, the copy assignment operator
4603 // for the class is used (as if by explicit qualification; that is,
4604 // ignoring any possible virtual overriding functions in more derived
4605 // classes);
4606 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4607 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4608
4609 // Look for operator=.
4610 DeclarationName Name
4611 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4612 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4613 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4614
4615 // Filter out any result that isn't a copy-assignment operator.
4616 LookupResult::Filter F = OpLookup.makeFilter();
4617 while (F.hasNext()) {
4618 NamedDecl *D = F.next();
4619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4620 if (Method->isCopyAssignmentOperator())
4621 continue;
4622
4623 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004624 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004625 F.done();
4626
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004627 // Suppress the protected check (C++ [class.protected]) for each of the
4628 // assignment operators we found. This strange dance is required when
4629 // we're assigning via a base classes's copy-assignment operator. To
4630 // ensure that we're getting the right base class subobject (without
4631 // ambiguities), we need to cast "this" to that subobject type; to
4632 // ensure that we don't go through the virtual call mechanism, we need
4633 // to qualify the operator= name with the base class (see below). However,
4634 // this means that if the base class has a protected copy assignment
4635 // operator, the protected member access check will fail. So, we
4636 // rewrite "protected" access to "public" access in this case, since we
4637 // know by construction that we're calling from a derived class.
4638 if (CopyingBaseSubobject) {
4639 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4640 L != LEnd; ++L) {
4641 if (L.getAccess() == AS_protected)
4642 L.setAccess(AS_public);
4643 }
4644 }
4645
Douglas Gregorb139cd52010-05-01 20:49:11 +00004646 // Create the nested-name-specifier that will be used to qualify the
4647 // reference to operator=; this is required to suppress the virtual
4648 // call mechanism.
4649 CXXScopeSpec SS;
4650 SS.setRange(Loc);
4651 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4652 T.getTypePtr()));
4653
4654 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004655 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004656 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004657 /*FirstQualifierInScope=*/0, OpLookup,
4658 /*TemplateArgs=*/0,
4659 /*SuppressQualifierCheck=*/true);
4660 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004661 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004662
4663 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004664
John McCalldadc5752010-08-24 06:29:42 +00004665 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004666 OpEqualRef.takeAs<Expr>(),
4667 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004668 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004669 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004670
4671 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004672 }
John McCallab8c2732010-03-16 06:11:48 +00004673
Douglas Gregorb139cd52010-05-01 20:49:11 +00004674 // - if the subobject is of scalar type, the built-in assignment
4675 // operator is used.
4676 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4677 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004678 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004679 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004680 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004681
4682 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004683 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004684
4685 // - if the subobject is an array, each element is assigned, in the
4686 // manner appropriate to the element type;
4687
4688 // Construct a loop over the array bounds, e.g.,
4689 //
4690 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4691 //
4692 // that will copy each of the array elements.
4693 QualType SizeType = S.Context.getSizeType();
4694
4695 // Create the iteration variable.
4696 IdentifierInfo *IterationVarName = 0;
4697 {
4698 llvm::SmallString<8> Str;
4699 llvm::raw_svector_ostream OS(Str);
4700 OS << "__i" << Depth;
4701 IterationVarName = &S.Context.Idents.get(OS.str());
4702 }
4703 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4704 IterationVarName, SizeType,
4705 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004706 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004707
4708 // Initialize the iteration variable to zero.
4709 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004710 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004711
4712 // Create a reference to the iteration variable; we'll use this several
4713 // times throughout.
4714 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004715 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004716 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4717
4718 // Create the DeclStmt that holds the iteration variable.
4719 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4720
4721 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004722 llvm::APInt Upper
4723 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004724 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004725 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004726 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4727 BO_NE, S.Context.BoolTy,
4728 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004729
4730 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004731 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004732 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4733 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004734
4735 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004736 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4737 IterationVarRef, Loc));
4738 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4739 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004740
4741 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004742 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4743 To, From, CopyingBaseSubobject,
4744 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004745 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004746 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004747
4748 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004749 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004750 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004751 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004752 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004753}
4754
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004755/// \brief Determine whether the given class has a copy assignment operator
4756/// that accepts a const-qualified argument.
4757static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4758 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4759
4760 if (!Class->hasDeclaredCopyAssignment())
4761 S.DeclareImplicitCopyAssignment(Class);
4762
4763 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4764 DeclarationName OpName
4765 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4766
4767 DeclContext::lookup_const_iterator Op, OpEnd;
4768 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4769 // C++ [class.copy]p9:
4770 // A user-declared copy assignment operator is a non-static non-template
4771 // member function of class X with exactly one parameter of type X, X&,
4772 // const X&, volatile X& or const volatile X&.
4773 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4774 if (!Method)
4775 continue;
4776
4777 if (Method->isStatic())
4778 continue;
4779 if (Method->getPrimaryTemplate())
4780 continue;
4781 const FunctionProtoType *FnType =
4782 Method->getType()->getAs<FunctionProtoType>();
4783 assert(FnType && "Overloaded operator has no prototype.");
4784 // Don't assert on this; an invalid decl might have been left in the AST.
4785 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4786 continue;
4787 bool AcceptsConst = true;
4788 QualType ArgType = FnType->getArgType(0);
4789 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4790 ArgType = Ref->getPointeeType();
4791 // Is it a non-const lvalue reference?
4792 if (!ArgType.isConstQualified())
4793 AcceptsConst = false;
4794 }
4795 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4796 continue;
4797
4798 // We have a single argument of type cv X or cv X&, i.e. we've found the
4799 // copy assignment operator. Return whether it accepts const arguments.
4800 return AcceptsConst;
4801 }
4802 assert(Class->isInvalidDecl() &&
4803 "No copy assignment operator declared in valid code.");
4804 return false;
4805}
4806
Douglas Gregor0be31a22010-07-02 17:43:08 +00004807CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004808 // Note: The following rules are largely analoguous to the copy
4809 // constructor rules. Note that virtual bases are not taken into account
4810 // for determining the argument type of the operator. Note also that
4811 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004812
4813
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004814 // C++ [class.copy]p10:
4815 // If the class definition does not explicitly declare a copy
4816 // assignment operator, one is declared implicitly.
4817 // The implicitly-defined copy assignment operator for a class X
4818 // will have the form
4819 //
4820 // X& X::operator=(const X&)
4821 //
4822 // if
4823 bool HasConstCopyAssignment = true;
4824
4825 // -- each direct base class B of X has a copy assignment operator
4826 // whose parameter is of type const B&, const volatile B& or B,
4827 // and
4828 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4829 BaseEnd = ClassDecl->bases_end();
4830 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4831 assert(!Base->getType()->isDependentType() &&
4832 "Cannot generate implicit members for class with dependent bases.");
4833 const CXXRecordDecl *BaseClassDecl
4834 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004835 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004836 }
4837
4838 // -- for all the nonstatic data members of X that are of a class
4839 // type M (or array thereof), each such class type has a copy
4840 // assignment operator whose parameter is of type const M&,
4841 // const volatile M& or M.
4842 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4843 FieldEnd = ClassDecl->field_end();
4844 HasConstCopyAssignment && Field != FieldEnd;
4845 ++Field) {
4846 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4847 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4848 const CXXRecordDecl *FieldClassDecl
4849 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004850 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004851 }
4852 }
4853
4854 // Otherwise, the implicitly declared copy assignment operator will
4855 // have the form
4856 //
4857 // X& X::operator=(X&)
4858 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4859 QualType RetType = Context.getLValueReferenceType(ArgType);
4860 if (HasConstCopyAssignment)
4861 ArgType = ArgType.withConst();
4862 ArgType = Context.getLValueReferenceType(ArgType);
4863
Douglas Gregor68e11362010-07-01 17:48:08 +00004864 // C++ [except.spec]p14:
4865 // An implicitly declared special member function (Clause 12) shall have an
4866 // exception-specification. [...]
4867 ImplicitExceptionSpecification ExceptSpec(Context);
4868 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4869 BaseEnd = ClassDecl->bases_end();
4870 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004871 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004872 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004873
4874 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4875 DeclareImplicitCopyAssignment(BaseClassDecl);
4876
Douglas Gregor68e11362010-07-01 17:48:08 +00004877 if (CXXMethodDecl *CopyAssign
4878 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4879 ExceptSpec.CalledDecl(CopyAssign);
4880 }
4881 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4882 FieldEnd = ClassDecl->field_end();
4883 Field != FieldEnd;
4884 ++Field) {
4885 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4886 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004887 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004888 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004889
4890 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4891 DeclareImplicitCopyAssignment(FieldClassDecl);
4892
Douglas Gregor68e11362010-07-01 17:48:08 +00004893 if (CXXMethodDecl *CopyAssign
4894 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4895 ExceptSpec.CalledDecl(CopyAssign);
4896 }
4897 }
4898
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004899 // An implicitly-declared copy assignment operator is an inline public
4900 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004901 FunctionProtoType::ExtProtoInfo EPI;
4902 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4903 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4904 EPI.NumExceptions = ExceptSpec.size();
4905 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004906 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004907 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004908 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004909 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004910 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004911 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004912 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004913 /*isInline=*/true);
4914 CopyAssignment->setAccess(AS_public);
4915 CopyAssignment->setImplicit();
4916 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004917
4918 // Add the parameter to the operator.
4919 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4920 ClassDecl->getLocation(),
4921 /*Id=*/0,
4922 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004923 SC_None,
4924 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004925 CopyAssignment->setParams(&FromParam, 1);
4926
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004927 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004928 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4929
Douglas Gregor0be31a22010-07-02 17:43:08 +00004930 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004931 PushOnScopeChains(CopyAssignment, S, false);
4932 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004933
4934 AddOverriddenMethods(ClassDecl, CopyAssignment);
4935 return CopyAssignment;
4936}
4937
Douglas Gregorb139cd52010-05-01 20:49:11 +00004938void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4939 CXXMethodDecl *CopyAssignOperator) {
4940 assert((CopyAssignOperator->isImplicit() &&
4941 CopyAssignOperator->isOverloadedOperator() &&
4942 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004943 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004944 "DefineImplicitCopyAssignment called for wrong function");
4945
4946 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4947
4948 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4949 CopyAssignOperator->setInvalidDecl();
4950 return;
4951 }
4952
4953 CopyAssignOperator->setUsed();
4954
4955 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004956 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004957
4958 // C++0x [class.copy]p30:
4959 // The implicitly-defined or explicitly-defaulted copy assignment operator
4960 // for a non-union class X performs memberwise copy assignment of its
4961 // subobjects. The direct base classes of X are assigned first, in the
4962 // order of their declaration in the base-specifier-list, and then the
4963 // immediate non-static data members of X are assigned, in the order in
4964 // which they were declared in the class definition.
4965
4966 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004967 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004968
4969 // The parameter for the "other" object, which we are copying from.
4970 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4971 Qualifiers OtherQuals = Other->getType().getQualifiers();
4972 QualType OtherRefType = Other->getType();
4973 if (const LValueReferenceType *OtherRef
4974 = OtherRefType->getAs<LValueReferenceType>()) {
4975 OtherRefType = OtherRef->getPointeeType();
4976 OtherQuals = OtherRefType.getQualifiers();
4977 }
4978
4979 // Our location for everything implicitly-generated.
4980 SourceLocation Loc = CopyAssignOperator->getLocation();
4981
4982 // Construct a reference to the "other" object. We'll be using this
4983 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00004984 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004985 assert(OtherRef && "Reference to parameter cannot fail!");
4986
4987 // Construct the "this" pointer. We'll be using this throughout the generated
4988 // ASTs.
4989 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4990 assert(This && "Reference to this cannot fail!");
4991
4992 // Assign base classes.
4993 bool Invalid = false;
4994 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4995 E = ClassDecl->bases_end(); Base != E; ++Base) {
4996 // Form the assignment:
4997 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4998 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00004999 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005000 Invalid = true;
5001 continue;
5002 }
5003
John McCallcf142162010-08-07 06:22:56 +00005004 CXXCastPath BasePath;
5005 BasePath.push_back(Base);
5006
Douglas Gregorb139cd52010-05-01 20:49:11 +00005007 // Construct the "from" expression, which is an implicit cast to the
5008 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005009 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005010 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005011 CK_UncheckedDerivedToBase,
5012 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005013
5014 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005015 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005016
5017 // Implicitly cast "this" to the appropriately-qualified base type.
5018 Expr *ToE = To.takeAs<Expr>();
5019 ImpCastExprToType(ToE,
5020 Context.getCVRQualifiedType(BaseType,
5021 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005022 CK_UncheckedDerivedToBase,
5023 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005024 To = Owned(ToE);
5025
5026 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005027 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005028 To.get(), From,
5029 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005030 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005031 Diag(CurrentLocation, diag::note_member_synthesized_at)
5032 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5033 CopyAssignOperator->setInvalidDecl();
5034 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005035 }
5036
5037 // Success! Record the copy.
5038 Statements.push_back(Copy.takeAs<Expr>());
5039 }
5040
5041 // \brief Reference to the __builtin_memcpy function.
5042 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005043 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005044 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005045
5046 // Assign non-static members.
5047 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5048 FieldEnd = ClassDecl->field_end();
5049 Field != FieldEnd; ++Field) {
5050 // Check for members of reference type; we can't copy those.
5051 if (Field->getType()->isReferenceType()) {
5052 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5053 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5054 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005055 Diag(CurrentLocation, diag::note_member_synthesized_at)
5056 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005057 Invalid = true;
5058 continue;
5059 }
5060
5061 // Check for members of const-qualified, non-class type.
5062 QualType BaseType = Context.getBaseElementType(Field->getType());
5063 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5064 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5065 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5066 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005067 Diag(CurrentLocation, diag::note_member_synthesized_at)
5068 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005069 Invalid = true;
5070 continue;
5071 }
5072
5073 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005074 if (FieldType->isIncompleteArrayType()) {
5075 assert(ClassDecl->hasFlexibleArrayMember() &&
5076 "Incomplete array type is not valid");
5077 continue;
5078 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005079
5080 // Build references to the field in the object we're copying from and to.
5081 CXXScopeSpec SS; // Intentionally empty
5082 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5083 LookupMemberName);
5084 MemberLookup.addDecl(*Field);
5085 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005086 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005087 Loc, /*IsArrow=*/false,
5088 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005089 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005090 Loc, /*IsArrow=*/true,
5091 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005092 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5093 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5094
5095 // If the field should be copied with __builtin_memcpy rather than via
5096 // explicit assignments, do so. This optimization only applies for arrays
5097 // of scalars and arrays of class type with trivial copy-assignment
5098 // operators.
5099 if (FieldType->isArrayType() &&
5100 (!BaseType->isRecordType() ||
5101 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5102 ->hasTrivialCopyAssignment())) {
5103 // Compute the size of the memory buffer to be copied.
5104 QualType SizeType = Context.getSizeType();
5105 llvm::APInt Size(Context.getTypeSize(SizeType),
5106 Context.getTypeSizeInChars(BaseType).getQuantity());
5107 for (const ConstantArrayType *Array
5108 = Context.getAsConstantArrayType(FieldType);
5109 Array;
5110 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005111 llvm::APInt ArraySize
5112 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005113 Size *= ArraySize;
5114 }
5115
5116 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005117 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5118 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005119
5120 bool NeedsCollectableMemCpy =
5121 (BaseType->isRecordType() &&
5122 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5123
5124 if (NeedsCollectableMemCpy) {
5125 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005126 // Create a reference to the __builtin_objc_memmove_collectable function.
5127 LookupResult R(*this,
5128 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005129 Loc, LookupOrdinaryName);
5130 LookupName(R, TUScope, true);
5131
5132 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5133 if (!CollectableMemCpy) {
5134 // Something went horribly wrong earlier, and we will have
5135 // complained about it.
5136 Invalid = true;
5137 continue;
5138 }
5139
5140 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5141 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005142 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005143 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5144 }
5145 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005146 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005147 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005148 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5149 LookupOrdinaryName);
5150 LookupName(R, TUScope, true);
5151
5152 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5153 if (!BuiltinMemCpy) {
5154 // Something went horribly wrong earlier, and we will have complained
5155 // about it.
5156 Invalid = true;
5157 continue;
5158 }
5159
5160 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5161 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005162 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005163 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5164 }
5165
John McCall37ad5512010-08-23 06:44:23 +00005166 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005167 CallArgs.push_back(To.takeAs<Expr>());
5168 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005169 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005170 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005171 if (NeedsCollectableMemCpy)
5172 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005173 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005174 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005175 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005176 else
5177 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005178 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005179 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005180 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005181
Douglas Gregorb139cd52010-05-01 20:49:11 +00005182 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5183 Statements.push_back(Call.takeAs<Expr>());
5184 continue;
5185 }
5186
5187 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005188 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005189 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005190 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005191 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005192 Diag(CurrentLocation, diag::note_member_synthesized_at)
5193 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5194 CopyAssignOperator->setInvalidDecl();
5195 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005196 }
5197
5198 // Success! Record the copy.
5199 Statements.push_back(Copy.takeAs<Stmt>());
5200 }
5201
5202 if (!Invalid) {
5203 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005204 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005205
John McCalldadc5752010-08-24 06:29:42 +00005206 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005207 if (Return.isInvalid())
5208 Invalid = true;
5209 else {
5210 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005211
5212 if (Trap.hasErrorOccurred()) {
5213 Diag(CurrentLocation, diag::note_member_synthesized_at)
5214 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5215 Invalid = true;
5216 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005217 }
5218 }
5219
5220 if (Invalid) {
5221 CopyAssignOperator->setInvalidDecl();
5222 return;
5223 }
5224
John McCalldadc5752010-08-24 06:29:42 +00005225 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005226 /*isStmtExpr=*/false);
5227 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5228 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005229}
5230
Douglas Gregor0be31a22010-07-02 17:43:08 +00005231CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5232 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005233 // C++ [class.copy]p4:
5234 // If the class definition does not explicitly declare a copy
5235 // constructor, one is declared implicitly.
5236
Douglas Gregor54be3392010-07-01 17:57:27 +00005237 // C++ [class.copy]p5:
5238 // The implicitly-declared copy constructor for a class X will
5239 // have the form
5240 //
5241 // X::X(const X&)
5242 //
5243 // if
5244 bool HasConstCopyConstructor = true;
5245
5246 // -- each direct or virtual base class B of X has a copy
5247 // constructor whose first parameter is of type const B& or
5248 // const volatile B&, and
5249 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5250 BaseEnd = ClassDecl->bases_end();
5251 HasConstCopyConstructor && Base != BaseEnd;
5252 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005253 // Virtual bases are handled below.
5254 if (Base->isVirtual())
5255 continue;
5256
Douglas Gregora6d69502010-07-02 23:41:54 +00005257 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005258 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005259 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5260 DeclareImplicitCopyConstructor(BaseClassDecl);
5261
Douglas Gregorcfe68222010-07-01 18:27:03 +00005262 HasConstCopyConstructor
5263 = BaseClassDecl->hasConstCopyConstructor(Context);
5264 }
5265
5266 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5267 BaseEnd = ClassDecl->vbases_end();
5268 HasConstCopyConstructor && Base != BaseEnd;
5269 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005270 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005271 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005272 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5273 DeclareImplicitCopyConstructor(BaseClassDecl);
5274
Douglas Gregor54be3392010-07-01 17:57:27 +00005275 HasConstCopyConstructor
5276 = BaseClassDecl->hasConstCopyConstructor(Context);
5277 }
5278
5279 // -- for all the nonstatic data members of X that are of a
5280 // class type M (or array thereof), each such class type
5281 // has a copy constructor whose first parameter is of type
5282 // const M& or const volatile M&.
5283 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5284 FieldEnd = ClassDecl->field_end();
5285 HasConstCopyConstructor && Field != FieldEnd;
5286 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005287 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005288 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005289 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005290 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005291 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5292 DeclareImplicitCopyConstructor(FieldClassDecl);
5293
Douglas Gregor54be3392010-07-01 17:57:27 +00005294 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005295 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005296 }
5297 }
5298
5299 // Otherwise, the implicitly declared copy constructor will have
5300 // the form
5301 //
5302 // X::X(X&)
5303 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5304 QualType ArgType = ClassType;
5305 if (HasConstCopyConstructor)
5306 ArgType = ArgType.withConst();
5307 ArgType = Context.getLValueReferenceType(ArgType);
5308
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005309 // C++ [except.spec]p14:
5310 // An implicitly declared special member function (Clause 12) shall have an
5311 // exception-specification. [...]
5312 ImplicitExceptionSpecification ExceptSpec(Context);
5313 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5314 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5315 BaseEnd = ClassDecl->bases_end();
5316 Base != BaseEnd;
5317 ++Base) {
5318 // Virtual bases are handled below.
5319 if (Base->isVirtual())
5320 continue;
5321
Douglas Gregora6d69502010-07-02 23:41:54 +00005322 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005323 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005324 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5325 DeclareImplicitCopyConstructor(BaseClassDecl);
5326
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005327 if (CXXConstructorDecl *CopyConstructor
5328 = BaseClassDecl->getCopyConstructor(Context, Quals))
5329 ExceptSpec.CalledDecl(CopyConstructor);
5330 }
5331 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5332 BaseEnd = ClassDecl->vbases_end();
5333 Base != BaseEnd;
5334 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005335 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005336 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005337 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5338 DeclareImplicitCopyConstructor(BaseClassDecl);
5339
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005340 if (CXXConstructorDecl *CopyConstructor
5341 = BaseClassDecl->getCopyConstructor(Context, Quals))
5342 ExceptSpec.CalledDecl(CopyConstructor);
5343 }
5344 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5345 FieldEnd = ClassDecl->field_end();
5346 Field != FieldEnd;
5347 ++Field) {
5348 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5349 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005350 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005351 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005352 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5353 DeclareImplicitCopyConstructor(FieldClassDecl);
5354
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005355 if (CXXConstructorDecl *CopyConstructor
5356 = FieldClassDecl->getCopyConstructor(Context, Quals))
5357 ExceptSpec.CalledDecl(CopyConstructor);
5358 }
5359 }
5360
Douglas Gregor54be3392010-07-01 17:57:27 +00005361 // An implicitly-declared copy constructor is an inline public
5362 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005363 FunctionProtoType::ExtProtoInfo EPI;
5364 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5365 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5366 EPI.NumExceptions = ExceptSpec.size();
5367 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005368 DeclarationName Name
5369 = Context.DeclarationNames.getCXXConstructorName(
5370 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005371 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005372 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005373 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005374 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005375 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005376 /*TInfo=*/0,
5377 /*isExplicit=*/false,
5378 /*isInline=*/true,
5379 /*isImplicitlyDeclared=*/true);
5380 CopyConstructor->setAccess(AS_public);
5381 CopyConstructor->setImplicit();
5382 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5383
Douglas Gregora6d69502010-07-02 23:41:54 +00005384 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005385 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5386
Douglas Gregor54be3392010-07-01 17:57:27 +00005387 // Add the parameter to the constructor.
5388 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5389 ClassDecl->getLocation(),
5390 /*IdentifierInfo=*/0,
5391 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005392 SC_None,
5393 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005394 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005395 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005396 PushOnScopeChains(CopyConstructor, S, false);
5397 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005398
5399 return CopyConstructor;
5400}
5401
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005402void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5403 CXXConstructorDecl *CopyConstructor,
5404 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005405 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005406 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005407 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005408 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005409
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005410 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005411 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005412
Douglas Gregora57478e2010-05-01 15:04:51 +00005413 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005414 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005415
Alexis Hunt1d792652011-01-08 20:30:50 +00005416 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005417 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005418 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005419 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005420 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005421 } else {
5422 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5423 CopyConstructor->getLocation(),
5424 MultiStmtArg(*this, 0, 0),
5425 /*isStmtExpr=*/false)
5426 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005427 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005428
5429 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005430}
5431
John McCalldadc5752010-08-24 06:29:42 +00005432ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005433Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005434 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005435 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005436 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005437 unsigned ConstructKind,
5438 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005439 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005440
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005441 // C++0x [class.copy]p34:
5442 // When certain criteria are met, an implementation is allowed to
5443 // omit the copy/move construction of a class object, even if the
5444 // copy/move constructor and/or destructor for the object have
5445 // side effects. [...]
5446 // - when a temporary class object that has not been bound to a
5447 // reference (12.2) would be copied/moved to a class object
5448 // with the same cv-unqualified type, the copy/move operation
5449 // can be omitted by constructing the temporary object
5450 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005451 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5452 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005453 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005454 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005455 }
Mike Stump11289f42009-09-09 15:08:12 +00005456
5457 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005458 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005459 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005460}
5461
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005462/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5463/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005464ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005465Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5466 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005467 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005468 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005469 unsigned ConstructKind,
5470 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005471 unsigned NumExprs = ExprArgs.size();
5472 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005473
Douglas Gregor27381f32009-11-23 12:27:39 +00005474 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005475 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005476 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005477 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005478 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5479 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005480}
5481
Mike Stump11289f42009-09-09 15:08:12 +00005482bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005483 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005484 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005485 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005486 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005487 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005488 move(Exprs), false, CXXConstructExpr::CK_Complete,
5489 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005490 if (TempResult.isInvalid())
5491 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005492
Anders Carlsson6eb55572009-08-25 05:12:04 +00005493 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005494 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005495 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005496 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005497 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005498
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005499 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005500}
5501
John McCall03c48482010-02-02 09:10:11 +00005502void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5503 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005504 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005505 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005506 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005507 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005508 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005509 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005510 << VD->getDeclName()
5511 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005512
John McCall386dfc72010-09-18 05:25:11 +00005513 // TODO: this should be re-enabled for static locals by !CXAAtExit
5514 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005515 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005516 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005517}
5518
Mike Stump11289f42009-09-09 15:08:12 +00005519/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005520/// ActOnDeclarator, when a C++ direct initializer is present.
5521/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005522void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005523 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005524 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005525 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005526 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005527
5528 // If there is no declaration, there was an error parsing it. Just ignore
5529 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005530 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005531 return;
Mike Stump11289f42009-09-09 15:08:12 +00005532
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005533 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5534 if (!VDecl) {
5535 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5536 RealDecl->setInvalidDecl();
5537 return;
5538 }
5539
Douglas Gregor402250f2009-08-26 21:14:46 +00005540 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005541 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005542 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5543 //
5544 // Clients that want to distinguish between the two forms, can check for
5545 // direct initializer using VarDecl::hasCXXDirectInitializer().
5546 // A major benefit is that clients that don't particularly care about which
5547 // exactly form was it (like the CodeGen) can handle both cases without
5548 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005549
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005550 // C++ 8.5p11:
5551 // The form of initialization (using parentheses or '=') is generally
5552 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005553 // class type.
5554
Douglas Gregor50dc2192010-02-11 22:55:30 +00005555 if (!VDecl->getType()->isDependentType() &&
5556 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005557 diag::err_typecheck_decl_incomplete_type)) {
5558 VDecl->setInvalidDecl();
5559 return;
5560 }
5561
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005562 // The variable can not have an abstract class type.
5563 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5564 diag::err_abstract_type_in_decl,
5565 AbstractVariableType))
5566 VDecl->setInvalidDecl();
5567
Sebastian Redl5ca79842010-02-01 20:16:42 +00005568 const VarDecl *Def;
5569 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005570 Diag(VDecl->getLocation(), diag::err_redefinition)
5571 << VDecl->getDeclName();
5572 Diag(Def->getLocation(), diag::note_previous_definition);
5573 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005574 return;
5575 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005576
Douglas Gregorf0f83692010-08-24 05:27:49 +00005577 // C++ [class.static.data]p4
5578 // If a static data member is of const integral or const
5579 // enumeration type, its declaration in the class definition can
5580 // specify a constant-initializer which shall be an integral
5581 // constant expression (5.19). In that case, the member can appear
5582 // in integral constant expressions. The member shall still be
5583 // defined in a namespace scope if it is used in the program and the
5584 // namespace scope definition shall not contain an initializer.
5585 //
5586 // We already performed a redefinition check above, but for static
5587 // data members we also need to check whether there was an in-class
5588 // declaration with an initializer.
5589 const VarDecl* PrevInit = 0;
5590 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5591 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5592 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5593 return;
5594 }
5595
Douglas Gregor71f39c92010-12-16 01:31:22 +00005596 bool IsDependent = false;
5597 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5598 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5599 VDecl->setInvalidDecl();
5600 return;
5601 }
5602
5603 if (Exprs.get()[I]->isTypeDependent())
5604 IsDependent = true;
5605 }
5606
Douglas Gregor50dc2192010-02-11 22:55:30 +00005607 // If either the declaration has a dependent type or if any of the
5608 // expressions is type-dependent, we represent the initialization
5609 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005610 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005611 // Let clients know that initialization was done with a direct initializer.
5612 VDecl->setCXXDirectInitializer(true);
5613
5614 // Store the initialization expressions as a ParenListExpr.
5615 unsigned NumExprs = Exprs.size();
5616 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5617 (Expr **)Exprs.release(),
5618 NumExprs, RParenLoc));
5619 return;
5620 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005621
5622 // Capture the variable that is being initialized and the style of
5623 // initialization.
5624 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5625
5626 // FIXME: Poor source location information.
5627 InitializationKind Kind
5628 = InitializationKind::CreateDirect(VDecl->getLocation(),
5629 LParenLoc, RParenLoc);
5630
5631 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005632 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005633 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005634 if (Result.isInvalid()) {
5635 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005636 return;
5637 }
John McCallacf0ee52010-10-08 02:01:28 +00005638
5639 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005640
Douglas Gregora40433a2010-12-07 00:41:46 +00005641 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005642 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005643 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005644
John McCall8b7fd8f12011-01-19 11:48:09 +00005645 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005646}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005647
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005648/// \brief Given a constructor and the set of arguments provided for the
5649/// constructor, convert the arguments and add any required default arguments
5650/// to form a proper call to this constructor.
5651///
5652/// \returns true if an error occurred, false otherwise.
5653bool
5654Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5655 MultiExprArg ArgsPtr,
5656 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005657 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005658 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5659 unsigned NumArgs = ArgsPtr.size();
5660 Expr **Args = (Expr **)ArgsPtr.get();
5661
5662 const FunctionProtoType *Proto
5663 = Constructor->getType()->getAs<FunctionProtoType>();
5664 assert(Proto && "Constructor without a prototype?");
5665 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005666
5667 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005668 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005669 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005670 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005671 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005672
5673 VariadicCallType CallType =
5674 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5675 llvm::SmallVector<Expr *, 8> AllArgs;
5676 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5677 Proto, 0, Args, NumArgs, AllArgs,
5678 CallType);
5679 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5680 ConvertedArgs.push_back(AllArgs[i]);
5681 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005682}
5683
Anders Carlssone363c8e2009-12-12 00:32:00 +00005684static inline bool
5685CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5686 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005687 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005688 if (isa<NamespaceDecl>(DC)) {
5689 return SemaRef.Diag(FnDecl->getLocation(),
5690 diag::err_operator_new_delete_declared_in_namespace)
5691 << FnDecl->getDeclName();
5692 }
5693
5694 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005695 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005696 return SemaRef.Diag(FnDecl->getLocation(),
5697 diag::err_operator_new_delete_declared_static)
5698 << FnDecl->getDeclName();
5699 }
5700
Anders Carlsson60659a82009-12-12 02:43:16 +00005701 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005702}
5703
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005704static inline bool
5705CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5706 CanQualType ExpectedResultType,
5707 CanQualType ExpectedFirstParamType,
5708 unsigned DependentParamTypeDiag,
5709 unsigned InvalidParamTypeDiag) {
5710 QualType ResultType =
5711 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5712
5713 // Check that the result type is not dependent.
5714 if (ResultType->isDependentType())
5715 return SemaRef.Diag(FnDecl->getLocation(),
5716 diag::err_operator_new_delete_dependent_result_type)
5717 << FnDecl->getDeclName() << ExpectedResultType;
5718
5719 // Check that the result type is what we expect.
5720 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5721 return SemaRef.Diag(FnDecl->getLocation(),
5722 diag::err_operator_new_delete_invalid_result_type)
5723 << FnDecl->getDeclName() << ExpectedResultType;
5724
5725 // A function template must have at least 2 parameters.
5726 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5727 return SemaRef.Diag(FnDecl->getLocation(),
5728 diag::err_operator_new_delete_template_too_few_parameters)
5729 << FnDecl->getDeclName();
5730
5731 // The function decl must have at least 1 parameter.
5732 if (FnDecl->getNumParams() == 0)
5733 return SemaRef.Diag(FnDecl->getLocation(),
5734 diag::err_operator_new_delete_too_few_parameters)
5735 << FnDecl->getDeclName();
5736
5737 // Check the the first parameter type is not dependent.
5738 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5739 if (FirstParamType->isDependentType())
5740 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5741 << FnDecl->getDeclName() << ExpectedFirstParamType;
5742
5743 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005744 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005745 ExpectedFirstParamType)
5746 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5747 << FnDecl->getDeclName() << ExpectedFirstParamType;
5748
5749 return false;
5750}
5751
Anders Carlsson12308f42009-12-11 23:23:22 +00005752static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005753CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005754 // C++ [basic.stc.dynamic.allocation]p1:
5755 // A program is ill-formed if an allocation function is declared in a
5756 // namespace scope other than global scope or declared static in global
5757 // scope.
5758 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5759 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005760
5761 CanQualType SizeTy =
5762 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5763
5764 // C++ [basic.stc.dynamic.allocation]p1:
5765 // The return type shall be void*. The first parameter shall have type
5766 // std::size_t.
5767 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5768 SizeTy,
5769 diag::err_operator_new_dependent_param_type,
5770 diag::err_operator_new_param_type))
5771 return true;
5772
5773 // C++ [basic.stc.dynamic.allocation]p1:
5774 // The first parameter shall not have an associated default argument.
5775 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005776 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005777 diag::err_operator_new_default_arg)
5778 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5779
5780 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005781}
5782
5783static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005784CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5785 // C++ [basic.stc.dynamic.deallocation]p1:
5786 // A program is ill-formed if deallocation functions are declared in a
5787 // namespace scope other than global scope or declared static in global
5788 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005789 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5790 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005791
5792 // C++ [basic.stc.dynamic.deallocation]p2:
5793 // Each deallocation function shall return void and its first parameter
5794 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005795 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5796 SemaRef.Context.VoidPtrTy,
5797 diag::err_operator_delete_dependent_param_type,
5798 diag::err_operator_delete_param_type))
5799 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005800
Anders Carlsson12308f42009-12-11 23:23:22 +00005801 return false;
5802}
5803
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005804/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5805/// of this overloaded operator is well-formed. If so, returns false;
5806/// otherwise, emits appropriate diagnostics and returns true.
5807bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005808 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005809 "Expected an overloaded operator declaration");
5810
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005811 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5812
Mike Stump11289f42009-09-09 15:08:12 +00005813 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005814 // The allocation and deallocation functions, operator new,
5815 // operator new[], operator delete and operator delete[], are
5816 // described completely in 3.7.3. The attributes and restrictions
5817 // found in the rest of this subclause do not apply to them unless
5818 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005819 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005820 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005821
Anders Carlsson22f443f2009-12-12 00:26:23 +00005822 if (Op == OO_New || Op == OO_Array_New)
5823 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005824
5825 // C++ [over.oper]p6:
5826 // An operator function shall either be a non-static member
5827 // function or be a non-member function and have at least one
5828 // parameter whose type is a class, a reference to a class, an
5829 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005830 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5831 if (MethodDecl->isStatic())
5832 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005833 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005834 } else {
5835 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005836 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5837 ParamEnd = FnDecl->param_end();
5838 Param != ParamEnd; ++Param) {
5839 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005840 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5841 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005842 ClassOrEnumParam = true;
5843 break;
5844 }
5845 }
5846
Douglas Gregord69246b2008-11-17 16:14:12 +00005847 if (!ClassOrEnumParam)
5848 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005849 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005850 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005851 }
5852
5853 // C++ [over.oper]p8:
5854 // An operator function cannot have default arguments (8.3.6),
5855 // except where explicitly stated below.
5856 //
Mike Stump11289f42009-09-09 15:08:12 +00005857 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005858 // (C++ [over.call]p1).
5859 if (Op != OO_Call) {
5860 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5861 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005862 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005863 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005864 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005865 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005866 }
5867 }
5868
Douglas Gregor6cf08062008-11-10 13:38:07 +00005869 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5870 { false, false, false }
5871#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5872 , { Unary, Binary, MemberOnly }
5873#include "clang/Basic/OperatorKinds.def"
5874 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005875
Douglas Gregor6cf08062008-11-10 13:38:07 +00005876 bool CanBeUnaryOperator = OperatorUses[Op][0];
5877 bool CanBeBinaryOperator = OperatorUses[Op][1];
5878 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005879
5880 // C++ [over.oper]p8:
5881 // [...] Operator functions cannot have more or fewer parameters
5882 // than the number required for the corresponding operator, as
5883 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005884 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005885 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005886 if (Op != OO_Call &&
5887 ((NumParams == 1 && !CanBeUnaryOperator) ||
5888 (NumParams == 2 && !CanBeBinaryOperator) ||
5889 (NumParams < 1) || (NumParams > 2))) {
5890 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005891 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005892 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005893 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005894 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005895 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005896 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005897 assert(CanBeBinaryOperator &&
5898 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005899 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005900 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005901
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005902 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005903 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005904 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005905
Douglas Gregord69246b2008-11-17 16:14:12 +00005906 // Overloaded operators other than operator() cannot be variadic.
5907 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005908 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005909 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005910 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005911 }
5912
5913 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005914 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5915 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005916 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005917 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005918 }
5919
5920 // C++ [over.inc]p1:
5921 // The user-defined function called operator++ implements the
5922 // prefix and postfix ++ operator. If this function is a member
5923 // function with no parameters, or a non-member function with one
5924 // parameter of class or enumeration type, it defines the prefix
5925 // increment operator ++ for objects of that type. If the function
5926 // is a member function with one parameter (which shall be of type
5927 // int) or a non-member function with two parameters (the second
5928 // of which shall be of type int), it defines the postfix
5929 // increment operator ++ for objects of that type.
5930 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5931 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5932 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005933 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005934 ParamIsInt = BT->getKind() == BuiltinType::Int;
5935
Chris Lattner2b786902008-11-21 07:50:02 +00005936 if (!ParamIsInt)
5937 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005938 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005939 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005940 }
5941
Douglas Gregord69246b2008-11-17 16:14:12 +00005942 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005943}
Chris Lattner3b024a32008-12-17 07:09:26 +00005944
Alexis Huntc88db062010-01-13 09:01:02 +00005945/// CheckLiteralOperatorDeclaration - Check whether the declaration
5946/// of this literal operator function is well-formed. If so, returns
5947/// false; otherwise, emits appropriate diagnostics and returns true.
5948bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5949 DeclContext *DC = FnDecl->getDeclContext();
5950 Decl::Kind Kind = DC->getDeclKind();
5951 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5952 Kind != Decl::LinkageSpec) {
5953 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5954 << FnDecl->getDeclName();
5955 return true;
5956 }
5957
5958 bool Valid = false;
5959
Alexis Hunt7dd26172010-04-07 23:11:06 +00005960 // template <char...> type operator "" name() is the only valid template
5961 // signature, and the only valid signature with no parameters.
5962 if (FnDecl->param_size() == 0) {
5963 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5964 // Must have only one template parameter
5965 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5966 if (Params->size() == 1) {
5967 NonTypeTemplateParmDecl *PmDecl =
5968 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005969
Alexis Hunt7dd26172010-04-07 23:11:06 +00005970 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00005971 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5972 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5973 Valid = true;
5974 }
5975 }
5976 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005977 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005978 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5979
Alexis Huntc88db062010-01-13 09:01:02 +00005980 QualType T = (*Param)->getType();
5981
Alexis Hunt079a6f72010-04-07 22:57:35 +00005982 // unsigned long long int, long double, and any character type are allowed
5983 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005984 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5985 Context.hasSameType(T, Context.LongDoubleTy) ||
5986 Context.hasSameType(T, Context.CharTy) ||
5987 Context.hasSameType(T, Context.WCharTy) ||
5988 Context.hasSameType(T, Context.Char16Ty) ||
5989 Context.hasSameType(T, Context.Char32Ty)) {
5990 if (++Param == FnDecl->param_end())
5991 Valid = true;
5992 goto FinishedParams;
5993 }
5994
Alexis Hunt079a6f72010-04-07 22:57:35 +00005995 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005996 const PointerType *PT = T->getAs<PointerType>();
5997 if (!PT)
5998 goto FinishedParams;
5999 T = PT->getPointeeType();
6000 if (!T.isConstQualified())
6001 goto FinishedParams;
6002 T = T.getUnqualifiedType();
6003
6004 // Move on to the second parameter;
6005 ++Param;
6006
6007 // If there is no second parameter, the first must be a const char *
6008 if (Param == FnDecl->param_end()) {
6009 if (Context.hasSameType(T, Context.CharTy))
6010 Valid = true;
6011 goto FinishedParams;
6012 }
6013
6014 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6015 // are allowed as the first parameter to a two-parameter function
6016 if (!(Context.hasSameType(T, Context.CharTy) ||
6017 Context.hasSameType(T, Context.WCharTy) ||
6018 Context.hasSameType(T, Context.Char16Ty) ||
6019 Context.hasSameType(T, Context.Char32Ty)))
6020 goto FinishedParams;
6021
6022 // The second and final parameter must be an std::size_t
6023 T = (*Param)->getType().getUnqualifiedType();
6024 if (Context.hasSameType(T, Context.getSizeType()) &&
6025 ++Param == FnDecl->param_end())
6026 Valid = true;
6027 }
6028
6029 // FIXME: This diagnostic is absolutely terrible.
6030FinishedParams:
6031 if (!Valid) {
6032 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6033 << FnDecl->getDeclName();
6034 return true;
6035 }
6036
6037 return false;
6038}
6039
Douglas Gregor07665a62009-01-05 19:45:36 +00006040/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6041/// linkage specification, including the language and (if present)
6042/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6043/// the location of the language string literal, which is provided
6044/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6045/// the '{' brace. Otherwise, this linkage specification does not
6046/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006047Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6048 SourceLocation LangLoc,
6049 llvm::StringRef Lang,
6050 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006051 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006052 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006053 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006054 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006055 Language = LinkageSpecDecl::lang_cxx;
6056 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006057 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006058 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006059 }
Mike Stump11289f42009-09-09 15:08:12 +00006060
Chris Lattner438e5012008-12-17 07:13:27 +00006061 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006062
Douglas Gregor07665a62009-01-05 19:45:36 +00006063 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006064 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006065 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006066 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006067 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006068 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006069}
6070
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006071/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006072/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6073/// valid, it's the position of the closing '}' brace in a linkage
6074/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006075Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6076 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006077 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006078 if (LinkageSpec)
6079 PopDeclContext();
6080 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006081}
6082
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006083/// \brief Perform semantic analysis for the variable declaration that
6084/// occurs within a C++ catch clause, returning the newly-created
6085/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006086VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006087 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006088 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006089 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006090 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006091 QualType ExDeclType = TInfo->getType();
6092
Sebastian Redl54c04d42008-12-22 19:15:10 +00006093 // Arrays and functions decay.
6094 if (ExDeclType->isArrayType())
6095 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6096 else if (ExDeclType->isFunctionType())
6097 ExDeclType = Context.getPointerType(ExDeclType);
6098
6099 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6100 // The exception-declaration shall not denote a pointer or reference to an
6101 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006102 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006103 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006104 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006105 Invalid = true;
6106 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006107
Douglas Gregor104ee002010-03-08 01:47:36 +00006108 // GCC allows catching pointers and references to incomplete types
6109 // as an extension; so do we, but we warn by default.
6110
Sebastian Redl54c04d42008-12-22 19:15:10 +00006111 QualType BaseType = ExDeclType;
6112 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006113 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006114 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006115 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006116 BaseType = Ptr->getPointeeType();
6117 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006118 DK = diag::ext_catch_incomplete_ptr;
6119 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006120 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006121 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006122 BaseType = Ref->getPointeeType();
6123 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006124 DK = diag::ext_catch_incomplete_ref;
6125 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006126 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006127 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006128 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6129 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006130 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006131
Mike Stump11289f42009-09-09 15:08:12 +00006132 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006133 RequireNonAbstractType(Loc, ExDeclType,
6134 diag::err_abstract_type_in_decl,
6135 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006136 Invalid = true;
6137
John McCall2ca705e2010-07-24 00:37:23 +00006138 // Only the non-fragile NeXT runtime currently supports C++ catches
6139 // of ObjC types, and no runtime supports catching ObjC types by value.
6140 if (!Invalid && getLangOptions().ObjC1) {
6141 QualType T = ExDeclType;
6142 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6143 T = RT->getPointeeType();
6144
6145 if (T->isObjCObjectType()) {
6146 Diag(Loc, diag::err_objc_object_catch);
6147 Invalid = true;
6148 } else if (T->isObjCObjectPointerType()) {
6149 if (!getLangOptions().NeXTRuntime) {
6150 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6151 Invalid = true;
6152 } else if (!getLangOptions().ObjCNonFragileABI) {
6153 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6154 Invalid = true;
6155 }
6156 }
6157 }
6158
Mike Stump11289f42009-09-09 15:08:12 +00006159 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006160 Name, ExDeclType, TInfo, SC_None,
6161 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006162 ExDecl->setExceptionVariable(true);
6163
Douglas Gregor6de584c2010-03-05 23:38:39 +00006164 if (!Invalid) {
6165 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6166 // C++ [except.handle]p16:
6167 // The object declared in an exception-declaration or, if the
6168 // exception-declaration does not specify a name, a temporary (12.2) is
6169 // copy-initialized (8.5) from the exception object. [...]
6170 // The object is destroyed when the handler exits, after the destruction
6171 // of any automatic objects initialized within the handler.
6172 //
6173 // We just pretend to initialize the object with itself, then make sure
6174 // it can be destroyed later.
6175 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6176 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006177 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006178 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6179 SourceLocation());
6180 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006181 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006182 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006183 if (Result.isInvalid())
6184 Invalid = true;
6185 else
6186 FinalizeVarWithDestructor(ExDecl, RecordTy);
6187 }
6188 }
6189
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006190 if (Invalid)
6191 ExDecl->setInvalidDecl();
6192
6193 return ExDecl;
6194}
6195
6196/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6197/// handler.
John McCall48871652010-08-21 09:40:31 +00006198Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006199 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006200 bool Invalid = D.isInvalidType();
6201
6202 // Check for unexpanded parameter packs.
6203 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6204 UPPC_ExceptionType)) {
6205 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6206 D.getIdentifierLoc());
6207 Invalid = true;
6208 }
6209
Sebastian Redl54c04d42008-12-22 19:15:10 +00006210 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006211 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006212 LookupOrdinaryName,
6213 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006214 // The scope should be freshly made just for us. There is just no way
6215 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006216 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006217 if (PrevDecl->isTemplateParameter()) {
6218 // Maybe we will complain about the shadowed template parameter.
6219 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006220 }
6221 }
6222
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006223 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006224 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6225 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006226 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006227 }
6228
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006229 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006230 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006231 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006232
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006233 if (Invalid)
6234 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006235
Sebastian Redl54c04d42008-12-22 19:15:10 +00006236 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006237 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006238 PushOnScopeChains(ExDecl, S);
6239 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006240 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006241
Douglas Gregor758a8692009-06-17 21:51:59 +00006242 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006243 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006244}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006245
John McCall48871652010-08-21 09:40:31 +00006246Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006247 Expr *AssertExpr,
6248 Expr *AssertMessageExpr_) {
6249 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006250
Anders Carlsson54b26982009-03-14 00:33:21 +00006251 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6252 llvm::APSInt Value(32);
6253 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6254 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6255 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006256 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006257 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006258
Anders Carlsson54b26982009-03-14 00:33:21 +00006259 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006260 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006261 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006262 }
6263 }
Mike Stump11289f42009-09-09 15:08:12 +00006264
Douglas Gregoref68fee2010-12-15 23:55:21 +00006265 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6266 return 0;
6267
Mike Stump11289f42009-09-09 15:08:12 +00006268 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006269 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006270
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006271 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006272 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006273}
Sebastian Redlf769df52009-03-24 22:27:57 +00006274
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006275/// \brief Perform semantic analysis of the given friend type declaration.
6276///
6277/// \returns A friend declaration that.
6278FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6279 TypeSourceInfo *TSInfo) {
6280 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6281
6282 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006283 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006284
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006285 if (!getLangOptions().CPlusPlus0x) {
6286 // C++03 [class.friend]p2:
6287 // An elaborated-type-specifier shall be used in a friend declaration
6288 // for a class.*
6289 //
6290 // * The class-key of the elaborated-type-specifier is required.
6291 if (!ActiveTemplateInstantiations.empty()) {
6292 // Do not complain about the form of friend template types during
6293 // template instantiation; we will already have complained when the
6294 // template was declared.
6295 } else if (!T->isElaboratedTypeSpecifier()) {
6296 // If we evaluated the type to a record type, suggest putting
6297 // a tag in front.
6298 if (const RecordType *RT = T->getAs<RecordType>()) {
6299 RecordDecl *RD = RT->getDecl();
6300
6301 std::string InsertionText = std::string(" ") + RD->getKindName();
6302
6303 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6304 << (unsigned) RD->getTagKind()
6305 << T
6306 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6307 InsertionText);
6308 } else {
6309 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6310 << T
6311 << SourceRange(FriendLoc, TypeRange.getEnd());
6312 }
6313 } else if (T->getAs<EnumType>()) {
6314 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006315 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006316 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006317 }
6318 }
6319
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006320 // C++0x [class.friend]p3:
6321 // If the type specifier in a friend declaration designates a (possibly
6322 // cv-qualified) class type, that class is declared as a friend; otherwise,
6323 // the friend declaration is ignored.
6324
6325 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6326 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006327
6328 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6329}
6330
John McCallace48cd2010-10-19 01:40:49 +00006331/// Handle a friend tag declaration where the scope specifier was
6332/// templated.
6333Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6334 unsigned TagSpec, SourceLocation TagLoc,
6335 CXXScopeSpec &SS,
6336 IdentifierInfo *Name, SourceLocation NameLoc,
6337 AttributeList *Attr,
6338 MultiTemplateParamsArg TempParamLists) {
6339 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6340
6341 bool isExplicitSpecialization = false;
6342 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6343 bool Invalid = false;
6344
6345 if (TemplateParameterList *TemplateParams
6346 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6347 TempParamLists.get(),
6348 TempParamLists.size(),
6349 /*friend*/ true,
6350 isExplicitSpecialization,
6351 Invalid)) {
6352 --NumMatchedTemplateParamLists;
6353
6354 if (TemplateParams->size() > 0) {
6355 // This is a declaration of a class template.
6356 if (Invalid)
6357 return 0;
6358
6359 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6360 SS, Name, NameLoc, Attr,
6361 TemplateParams, AS_public).take();
6362 } else {
6363 // The "template<>" header is extraneous.
6364 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6365 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6366 isExplicitSpecialization = true;
6367 }
6368 }
6369
6370 if (Invalid) return 0;
6371
6372 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6373
6374 bool isAllExplicitSpecializations = true;
6375 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6376 if (TempParamLists.get()[I]->size()) {
6377 isAllExplicitSpecializations = false;
6378 break;
6379 }
6380 }
6381
6382 // FIXME: don't ignore attributes.
6383
6384 // If it's explicit specializations all the way down, just forget
6385 // about the template header and build an appropriate non-templated
6386 // friend. TODO: for source fidelity, remember the headers.
6387 if (isAllExplicitSpecializations) {
6388 ElaboratedTypeKeyword Keyword
6389 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6390 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6391 TagLoc, SS.getRange(), NameLoc);
6392 if (T.isNull())
6393 return 0;
6394
6395 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6396 if (isa<DependentNameType>(T)) {
6397 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6398 TL.setKeywordLoc(TagLoc);
6399 TL.setQualifierRange(SS.getRange());
6400 TL.setNameLoc(NameLoc);
6401 } else {
6402 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6403 TL.setKeywordLoc(TagLoc);
6404 TL.setQualifierRange(SS.getRange());
6405 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6406 }
6407
6408 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6409 TSI, FriendLoc);
6410 Friend->setAccess(AS_public);
6411 CurContext->addDecl(Friend);
6412 return Friend;
6413 }
6414
6415 // Handle the case of a templated-scope friend class. e.g.
6416 // template <class T> class A<T>::B;
6417 // FIXME: we don't support these right now.
6418 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6419 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6420 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6421 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6422 TL.setKeywordLoc(TagLoc);
6423 TL.setQualifierRange(SS.getRange());
6424 TL.setNameLoc(NameLoc);
6425
6426 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6427 TSI, FriendLoc);
6428 Friend->setAccess(AS_public);
6429 Friend->setUnsupportedFriend(true);
6430 CurContext->addDecl(Friend);
6431 return Friend;
6432}
6433
6434
John McCall11083da2009-09-16 22:47:08 +00006435/// Handle a friend type declaration. This works in tandem with
6436/// ActOnTag.
6437///
6438/// Notes on friend class templates:
6439///
6440/// We generally treat friend class declarations as if they were
6441/// declaring a class. So, for example, the elaborated type specifier
6442/// in a friend declaration is required to obey the restrictions of a
6443/// class-head (i.e. no typedefs in the scope chain), template
6444/// parameters are required to match up with simple template-ids, &c.
6445/// However, unlike when declaring a template specialization, it's
6446/// okay to refer to a template specialization without an empty
6447/// template parameter declaration, e.g.
6448/// friend class A<T>::B<unsigned>;
6449/// We permit this as a special case; if there are any template
6450/// parameters present at all, require proper matching, i.e.
6451/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006452Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006453 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006454 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006455
6456 assert(DS.isFriendSpecified());
6457 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6458
John McCall11083da2009-09-16 22:47:08 +00006459 // Try to convert the decl specifier to a type. This works for
6460 // friend templates because ActOnTag never produces a ClassTemplateDecl
6461 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006462 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006463 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6464 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006465 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006466 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006467
Douglas Gregor6c110f32010-12-16 01:14:37 +00006468 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6469 return 0;
6470
John McCall11083da2009-09-16 22:47:08 +00006471 // This is definitely an error in C++98. It's probably meant to
6472 // be forbidden in C++0x, too, but the specification is just
6473 // poorly written.
6474 //
6475 // The problem is with declarations like the following:
6476 // template <T> friend A<T>::foo;
6477 // where deciding whether a class C is a friend or not now hinges
6478 // on whether there exists an instantiation of A that causes
6479 // 'foo' to equal C. There are restrictions on class-heads
6480 // (which we declare (by fiat) elaborated friend declarations to
6481 // be) that makes this tractable.
6482 //
6483 // FIXME: handle "template <> friend class A<T>;", which
6484 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006485 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006486 Diag(Loc, diag::err_tagless_friend_type_template)
6487 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006488 return 0;
John McCall11083da2009-09-16 22:47:08 +00006489 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006490
John McCallaa74a0c2009-08-28 07:59:38 +00006491 // C++98 [class.friend]p1: A friend of a class is a function
6492 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006493 // This is fixed in DR77, which just barely didn't make the C++03
6494 // deadline. It's also a very silly restriction that seriously
6495 // affects inner classes and which nobody else seems to implement;
6496 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006497 //
6498 // But note that we could warn about it: it's always useless to
6499 // friend one of your own members (it's not, however, worthless to
6500 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006501
John McCall11083da2009-09-16 22:47:08 +00006502 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006503 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006504 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006505 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006506 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006507 TSI,
John McCall11083da2009-09-16 22:47:08 +00006508 DS.getFriendSpecLoc());
6509 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006510 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6511
6512 if (!D)
John McCall48871652010-08-21 09:40:31 +00006513 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006514
John McCall11083da2009-09-16 22:47:08 +00006515 D->setAccess(AS_public);
6516 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006517
John McCall48871652010-08-21 09:40:31 +00006518 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006519}
6520
John McCallde3fd222010-10-12 23:13:28 +00006521Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6522 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006523 const DeclSpec &DS = D.getDeclSpec();
6524
6525 assert(DS.isFriendSpecified());
6526 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6527
6528 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006529 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6530 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006531
6532 // C++ [class.friend]p1
6533 // A friend of a class is a function or class....
6534 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006535 // It *doesn't* see through dependent types, which is correct
6536 // according to [temp.arg.type]p3:
6537 // If a declaration acquires a function type through a
6538 // type dependent on a template-parameter and this causes
6539 // a declaration that does not use the syntactic form of a
6540 // function declarator to have a function type, the program
6541 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006542 if (!T->isFunctionType()) {
6543 Diag(Loc, diag::err_unexpected_friend);
6544
6545 // It might be worthwhile to try to recover by creating an
6546 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006547 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006548 }
6549
6550 // C++ [namespace.memdef]p3
6551 // - If a friend declaration in a non-local class first declares a
6552 // class or function, the friend class or function is a member
6553 // of the innermost enclosing namespace.
6554 // - The name of the friend is not found by simple name lookup
6555 // until a matching declaration is provided in that namespace
6556 // scope (either before or after the class declaration granting
6557 // friendship).
6558 // - If a friend function is called, its name may be found by the
6559 // name lookup that considers functions from namespaces and
6560 // classes associated with the types of the function arguments.
6561 // - When looking for a prior declaration of a class or a function
6562 // declared as a friend, scopes outside the innermost enclosing
6563 // namespace scope are not considered.
6564
John McCallde3fd222010-10-12 23:13:28 +00006565 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006566 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6567 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006568 assert(Name);
6569
Douglas Gregor6c110f32010-12-16 01:14:37 +00006570 // Check for unexpanded parameter packs.
6571 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6572 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6573 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6574 return 0;
6575
John McCall07e91c02009-08-06 02:15:43 +00006576 // The context we found the declaration in, or in which we should
6577 // create the declaration.
6578 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006579 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006580 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006581 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006582
John McCallde3fd222010-10-12 23:13:28 +00006583 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006584
John McCallde3fd222010-10-12 23:13:28 +00006585 // There are four cases here.
6586 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006587 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006588 // there as appropriate.
6589 // Recover from invalid scope qualifiers as if they just weren't there.
6590 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006591 // C++0x [namespace.memdef]p3:
6592 // If the name in a friend declaration is neither qualified nor
6593 // a template-id and the declaration is a function or an
6594 // elaborated-type-specifier, the lookup to determine whether
6595 // the entity has been previously declared shall not consider
6596 // any scopes outside the innermost enclosing namespace.
6597 // C++0x [class.friend]p11:
6598 // If a friend declaration appears in a local class and the name
6599 // specified is an unqualified name, a prior declaration is
6600 // looked up without considering scopes that are outside the
6601 // innermost enclosing non-class scope. For a friend function
6602 // declaration, if there is no prior declaration, the program is
6603 // ill-formed.
6604 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006605 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006606
John McCallf7cfb222010-10-13 05:45:15 +00006607 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006608 DC = CurContext;
6609 while (true) {
6610 // Skip class contexts. If someone can cite chapter and verse
6611 // for this behavior, that would be nice --- it's what GCC and
6612 // EDG do, and it seems like a reasonable intent, but the spec
6613 // really only says that checks for unqualified existing
6614 // declarations should stop at the nearest enclosing namespace,
6615 // not that they should only consider the nearest enclosing
6616 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006617 while (DC->isRecord())
6618 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006619
John McCall1f82f242009-11-18 22:49:29 +00006620 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006621
6622 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006623 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006624 break;
John McCallf7cfb222010-10-13 05:45:15 +00006625
John McCallf4776592010-10-14 22:22:28 +00006626 if (isTemplateId) {
6627 if (isa<TranslationUnitDecl>(DC)) break;
6628 } else {
6629 if (DC->isFileContext()) break;
6630 }
John McCall07e91c02009-08-06 02:15:43 +00006631 DC = DC->getParent();
6632 }
6633
6634 // C++ [class.friend]p1: A friend of a class is a function or
6635 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006636 // C++0x changes this for both friend types and functions.
6637 // Most C++ 98 compilers do seem to give an error here, so
6638 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006639 if (!Previous.empty() && DC->Equals(CurContext)
6640 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006641 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006642
John McCallccbc0322010-10-13 06:22:15 +00006643 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006644
John McCallde3fd222010-10-12 23:13:28 +00006645 // - There's a non-dependent scope specifier, in which case we
6646 // compute it and do a previous lookup there for a function
6647 // or function template.
6648 } else if (!SS.getScopeRep()->isDependent()) {
6649 DC = computeDeclContext(SS);
6650 if (!DC) return 0;
6651
6652 if (RequireCompleteDeclContext(SS, DC)) return 0;
6653
6654 LookupQualifiedName(Previous, DC);
6655
6656 // Ignore things found implicitly in the wrong scope.
6657 // TODO: better diagnostics for this case. Suggesting the right
6658 // qualified scope would be nice...
6659 LookupResult::Filter F = Previous.makeFilter();
6660 while (F.hasNext()) {
6661 NamedDecl *D = F.next();
6662 if (!DC->InEnclosingNamespaceSetOf(
6663 D->getDeclContext()->getRedeclContext()))
6664 F.erase();
6665 }
6666 F.done();
6667
6668 if (Previous.empty()) {
6669 D.setInvalidType();
6670 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6671 return 0;
6672 }
6673
6674 // C++ [class.friend]p1: A friend of a class is a function or
6675 // class that is not a member of the class . . .
6676 if (DC->Equals(CurContext))
6677 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6678
6679 // - There's a scope specifier that does not match any template
6680 // parameter lists, in which case we use some arbitrary context,
6681 // create a method or method template, and wait for instantiation.
6682 // - There's a scope specifier that does match some template
6683 // parameter lists, which we don't handle right now.
6684 } else {
6685 DC = CurContext;
6686 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006687 }
6688
John McCallf7cfb222010-10-13 05:45:15 +00006689 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006690 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006691 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6692 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6693 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006694 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006695 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6696 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006697 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006698 }
John McCall07e91c02009-08-06 02:15:43 +00006699 }
6700
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006701 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006702 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006703 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006704 IsDefinition,
6705 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006706 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006707
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006708 assert(ND->getDeclContext() == DC);
6709 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006710
John McCall759e32b2009-08-31 22:39:49 +00006711 // Add the function declaration to the appropriate lookup tables,
6712 // adjusting the redeclarations list as necessary. We don't
6713 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006714 //
John McCall759e32b2009-08-31 22:39:49 +00006715 // Also update the scope-based lookup if the target context's
6716 // lookup context is in lexical scope.
6717 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006718 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006719 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006720 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006721 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006722 }
John McCallaa74a0c2009-08-28 07:59:38 +00006723
6724 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006725 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006726 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006727 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006728 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006729
John McCallde3fd222010-10-12 23:13:28 +00006730 if (ND->isInvalidDecl())
6731 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006732 else {
6733 FunctionDecl *FD;
6734 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6735 FD = FTD->getTemplatedDecl();
6736 else
6737 FD = cast<FunctionDecl>(ND);
6738
6739 // Mark templated-scope function declarations as unsupported.
6740 if (FD->getNumTemplateParameterLists())
6741 FrD->setUnsupportedFriend(true);
6742 }
John McCallde3fd222010-10-12 23:13:28 +00006743
John McCall48871652010-08-21 09:40:31 +00006744 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006745}
6746
John McCall48871652010-08-21 09:40:31 +00006747void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6748 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006749
Sebastian Redlf769df52009-03-24 22:27:57 +00006750 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6751 if (!Fn) {
6752 Diag(DelLoc, diag::err_deleted_non_function);
6753 return;
6754 }
6755 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6756 Diag(DelLoc, diag::err_deleted_decl_not_first);
6757 Diag(Prev->getLocation(), diag::note_previous_declaration);
6758 // If the declaration wasn't the first, we delete the function anyway for
6759 // recovery.
6760 }
6761 Fn->setDeleted();
6762}
Sebastian Redl4c018662009-04-27 21:33:24 +00006763
6764static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6765 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6766 ++CI) {
6767 Stmt *SubStmt = *CI;
6768 if (!SubStmt)
6769 continue;
6770 if (isa<ReturnStmt>(SubStmt))
6771 Self.Diag(SubStmt->getSourceRange().getBegin(),
6772 diag::err_return_in_constructor_handler);
6773 if (!isa<Expr>(SubStmt))
6774 SearchForReturnInStmt(Self, SubStmt);
6775 }
6776}
6777
6778void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6779 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6780 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6781 SearchForReturnInStmt(*this, Handler);
6782 }
6783}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006784
Mike Stump11289f42009-09-09 15:08:12 +00006785bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006786 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006787 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6788 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006789
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006790 if (Context.hasSameType(NewTy, OldTy) ||
6791 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006792 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006793
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006794 // Check if the return types are covariant
6795 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006796
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006797 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006798 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6799 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006800 NewClassTy = NewPT->getPointeeType();
6801 OldClassTy = OldPT->getPointeeType();
6802 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006803 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6804 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6805 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6806 NewClassTy = NewRT->getPointeeType();
6807 OldClassTy = OldRT->getPointeeType();
6808 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006809 }
6810 }
Mike Stump11289f42009-09-09 15:08:12 +00006811
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006812 // The return types aren't either both pointers or references to a class type.
6813 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006814 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006815 diag::err_different_return_type_for_overriding_virtual_function)
6816 << New->getDeclName() << NewTy << OldTy;
6817 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006818
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006819 return true;
6820 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006821
Anders Carlssone60365b2009-12-31 18:34:24 +00006822 // C++ [class.virtual]p6:
6823 // If the return type of D::f differs from the return type of B::f, the
6824 // class type in the return type of D::f shall be complete at the point of
6825 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006826 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6827 if (!RT->isBeingDefined() &&
6828 RequireCompleteType(New->getLocation(), NewClassTy,
6829 PDiag(diag::err_covariant_return_incomplete)
6830 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006831 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006832 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006833
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006834 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006835 // Check if the new class derives from the old class.
6836 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6837 Diag(New->getLocation(),
6838 diag::err_covariant_return_not_derived)
6839 << New->getDeclName() << NewTy << OldTy;
6840 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6841 return true;
6842 }
Mike Stump11289f42009-09-09 15:08:12 +00006843
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006844 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006845 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006846 diag::err_covariant_return_inaccessible_base,
6847 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6848 // FIXME: Should this point to the return type?
6849 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006850 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6851 return true;
6852 }
6853 }
Mike Stump11289f42009-09-09 15:08:12 +00006854
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006855 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006856 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006857 Diag(New->getLocation(),
6858 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006859 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006860 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6861 return true;
6862 };
Mike Stump11289f42009-09-09 15:08:12 +00006863
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006864
6865 // The new class type must have the same or less qualifiers as the old type.
6866 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6867 Diag(New->getLocation(),
6868 diag::err_covariant_return_type_class_type_more_qualified)
6869 << New->getDeclName() << NewTy << OldTy;
6870 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6871 return true;
6872 };
Mike Stump11289f42009-09-09 15:08:12 +00006873
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006874 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006875}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006876
Alexis Hunt96d5c762009-11-21 08:43:09 +00006877bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6878 const CXXMethodDecl *Old)
6879{
6880 if (Old->hasAttr<FinalAttr>()) {
6881 Diag(New->getLocation(), diag::err_final_function_overridden)
6882 << New->getDeclName();
6883 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6884 return true;
6885 }
6886
6887 return false;
6888}
6889
Douglas Gregor21920e372009-12-01 17:24:26 +00006890/// \brief Mark the given method pure.
6891///
6892/// \param Method the method to be marked pure.
6893///
6894/// \param InitRange the source range that covers the "0" initializer.
6895bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6896 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6897 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006898 return false;
6899 }
6900
6901 if (!Method->isInvalidDecl())
6902 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6903 << Method->getDeclName() << InitRange;
6904 return true;
6905}
6906
John McCall1f4ee7b2009-12-19 09:28:58 +00006907/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6908/// an initializer for the out-of-line declaration 'Dcl'. The scope
6909/// is a fresh scope pushed for just this purpose.
6910///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006911/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6912/// static data member of class X, names should be looked up in the scope of
6913/// class X.
John McCall48871652010-08-21 09:40:31 +00006914void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006915 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006916 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006917
John McCall1f4ee7b2009-12-19 09:28:58 +00006918 // We should only get called for declarations with scope specifiers, like:
6919 // int foo::bar;
6920 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006921 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006922}
6923
6924/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006925/// initializer for the out-of-line declaration 'D'.
6926void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006927 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006928 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006929
John McCall1f4ee7b2009-12-19 09:28:58 +00006930 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006931 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006932}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006933
6934/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6935/// C++ if/switch/while/for statement.
6936/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006937DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006938 // C++ 6.4p2:
6939 // The declarator shall not specify a function or an array.
6940 // The type-specifier-seq shall not contain typedef and shall not declare a
6941 // new class or enumeration.
6942 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6943 "Parser allowed 'typedef' as storage class of condition decl.");
6944
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006945 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006946 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6947 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006948
6949 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6950 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6951 // would be created and CXXConditionDeclExpr wants a VarDecl.
6952 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6953 << D.getSourceRange();
6954 return DeclResult();
6955 } else if (OwnedTag && OwnedTag->isDefinition()) {
6956 // The type-specifier-seq shall not declare a new class or enumeration.
6957 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6958 }
6959
John McCall48871652010-08-21 09:40:31 +00006960 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006961 if (!Dcl)
6962 return DeclResult();
6963
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006964 return Dcl;
6965}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006966
Douglas Gregor88d292c2010-05-13 16:44:06 +00006967void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6968 bool DefinitionRequired) {
6969 // Ignore any vtable uses in unevaluated operands or for classes that do
6970 // not have a vtable.
6971 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6972 CurContext->isDependentContext() ||
6973 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006974 return;
6975
Douglas Gregor88d292c2010-05-13 16:44:06 +00006976 // Try to insert this class into the map.
6977 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6978 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6979 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6980 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006981 // If we already had an entry, check to see if we are promoting this vtable
6982 // to required a definition. If so, we need to reappend to the VTableUses
6983 // list, since we may have already processed the first entry.
6984 if (DefinitionRequired && !Pos.first->second) {
6985 Pos.first->second = true;
6986 } else {
6987 // Otherwise, we can early exit.
6988 return;
6989 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006990 }
6991
6992 // Local classes need to have their virtual members marked
6993 // immediately. For all other classes, we mark their virtual members
6994 // at the end of the translation unit.
6995 if (Class->isLocalClass())
6996 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006997 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006998 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006999}
7000
Douglas Gregor88d292c2010-05-13 16:44:06 +00007001bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007002 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007003 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007004
Douglas Gregor88d292c2010-05-13 16:44:06 +00007005 // Note: The VTableUses vector could grow as a result of marking
7006 // the members of a class as "used", so we check the size each
7007 // time through the loop and prefer indices (with are stable) to
7008 // iterators (which are not).
7009 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007010 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007011 if (!Class)
7012 continue;
7013
7014 SourceLocation Loc = VTableUses[I].second;
7015
7016 // If this class has a key function, but that key function is
7017 // defined in another translation unit, we don't need to emit the
7018 // vtable even though we're using it.
7019 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007020 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007021 switch (KeyFunction->getTemplateSpecializationKind()) {
7022 case TSK_Undeclared:
7023 case TSK_ExplicitSpecialization:
7024 case TSK_ExplicitInstantiationDeclaration:
7025 // The key function is in another translation unit.
7026 continue;
7027
7028 case TSK_ExplicitInstantiationDefinition:
7029 case TSK_ImplicitInstantiation:
7030 // We will be instantiating the key function.
7031 break;
7032 }
7033 } else if (!KeyFunction) {
7034 // If we have a class with no key function that is the subject
7035 // of an explicit instantiation declaration, suppress the
7036 // vtable; it will live with the explicit instantiation
7037 // definition.
7038 bool IsExplicitInstantiationDeclaration
7039 = Class->getTemplateSpecializationKind()
7040 == TSK_ExplicitInstantiationDeclaration;
7041 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7042 REnd = Class->redecls_end();
7043 R != REnd; ++R) {
7044 TemplateSpecializationKind TSK
7045 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7046 if (TSK == TSK_ExplicitInstantiationDeclaration)
7047 IsExplicitInstantiationDeclaration = true;
7048 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7049 IsExplicitInstantiationDeclaration = false;
7050 break;
7051 }
7052 }
7053
7054 if (IsExplicitInstantiationDeclaration)
7055 continue;
7056 }
7057
7058 // Mark all of the virtual members of this class as referenced, so
7059 // that we can build a vtable. Then, tell the AST consumer that a
7060 // vtable for this class is required.
7061 MarkVirtualMembersReferenced(Loc, Class);
7062 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7063 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7064
7065 // Optionally warn if we're emitting a weak vtable.
7066 if (Class->getLinkage() == ExternalLinkage &&
7067 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007068 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007069 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7070 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007071 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007072 VTableUses.clear();
7073
Anders Carlsson82fccd02009-12-07 08:24:59 +00007074 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007075}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007076
Rafael Espindola5b334082010-03-26 00:36:59 +00007077void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7078 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007079 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7080 e = RD->method_end(); i != e; ++i) {
7081 CXXMethodDecl *MD = *i;
7082
7083 // C++ [basic.def.odr]p2:
7084 // [...] A virtual member function is used if it is not pure. [...]
7085 if (MD->isVirtual() && !MD->isPure())
7086 MarkDeclarationReferenced(Loc, MD);
7087 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007088
7089 // Only classes that have virtual bases need a VTT.
7090 if (RD->getNumVBases() == 0)
7091 return;
7092
7093 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7094 e = RD->bases_end(); i != e; ++i) {
7095 const CXXRecordDecl *Base =
7096 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007097 if (Base->getNumVBases() == 0)
7098 continue;
7099 MarkVirtualMembersReferenced(Loc, Base);
7100 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007101}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007102
7103/// SetIvarInitializers - This routine builds initialization ASTs for the
7104/// Objective-C implementation whose ivars need be initialized.
7105void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7106 if (!getLangOptions().CPlusPlus)
7107 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007108 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007109 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7110 CollectIvarsToConstructOrDestruct(OID, ivars);
7111 if (ivars.empty())
7112 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007113 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007114 for (unsigned i = 0; i < ivars.size(); i++) {
7115 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007116 if (Field->isInvalidDecl())
7117 continue;
7118
Alexis Hunt1d792652011-01-08 20:30:50 +00007119 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007120 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7121 InitializationKind InitKind =
7122 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7123
7124 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007125 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007126 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007127 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007128 // Note, MemberInit could actually come back empty if no initialization
7129 // is required (e.g., because it would call a trivial default constructor)
7130 if (!MemberInit.get() || MemberInit.isInvalid())
7131 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007132
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007133 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007134 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7135 SourceLocation(),
7136 MemberInit.takeAs<Expr>(),
7137 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007138 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007139
7140 // Be sure that the destructor is accessible and is marked as referenced.
7141 if (const RecordType *RecordTy
7142 = Context.getBaseElementType(Field->getType())
7143 ->getAs<RecordType>()) {
7144 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007145 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007146 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7147 CheckDestructorAccess(Field->getLocation(), Destructor,
7148 PDiag(diag::err_access_dtor_ivar)
7149 << Context.getBaseElementType(Field->getType()));
7150 }
7151 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007152 }
7153 ObjCImplementation->setIvarInitializers(Context,
7154 AllToInit.data(), AllToInit.size());
7155 }
7156}