blob: b9d760b41244e3e6b30928beeee86200488a892f [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
Anders Carlssonfd835532011-01-20 05:57:14 +0000855/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000856void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000857 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
858 if (!MD || !MD->isVirtual())
859 return;
860
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000861 if (MD->isDependentContext())
862 return;
863
Anders Carlssonfd835532011-01-20 05:57:14 +0000864 // C++0x [class.virtual]p3:
865 // If a virtual function is marked with the virt-specifier override and does
866 // not override a member function of a base class,
867 // the program is ill-formed.
868 bool HasOverriddenMethods =
869 MD->begin_overridden_methods() != MD->end_overridden_methods();
870 if (MD->isMarkedOverride() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000871 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000872 diag::err_function_marked_override_not_overriding)
873 << MD->getDeclName();
874 return;
875 }
876}
877
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000878/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
879/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
880/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000881/// any.
John McCall48871652010-08-21 09:40:31 +0000882Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000883Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000884 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000885 ExprTy *BW, const VirtSpecifiers &VS,
886 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000887 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000888 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000889 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
890 DeclarationName Name = NameInfo.getName();
891 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000892
893 // For anonymous bitfields, the location should point to the type.
894 if (Loc.isInvalid())
895 Loc = D.getSourceRange().getBegin();
896
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000897 Expr *BitWidth = static_cast<Expr*>(BW);
898 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000899
John McCallb1cd7da2010-06-04 08:34:12 +0000900 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000901 assert(!DS.isFriendSpecified());
902
John McCallb1cd7da2010-06-04 08:34:12 +0000903 bool isFunc = false;
904 if (D.isFunctionDeclarator())
905 isFunc = true;
906 else if (D.getNumTypeObjects() == 0 &&
907 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000908 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000909 isFunc = TDType->isFunctionType();
910 }
911
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000912 // C++ 9.2p6: A member shall not be declared to have automatic storage
913 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000914 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
915 // data members and cannot be applied to names declared const or static,
916 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000917 switch (DS.getStorageClassSpec()) {
918 case DeclSpec::SCS_unspecified:
919 case DeclSpec::SCS_typedef:
920 case DeclSpec::SCS_static:
921 // FALL THROUGH.
922 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000923 case DeclSpec::SCS_mutable:
924 if (isFunc) {
925 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000926 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000927 else
Chris Lattner3b054132008-11-19 05:08:23 +0000928 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000929
Sebastian Redl8071edb2008-11-17 23:24:37 +0000930 // FIXME: It would be nicer if the keyword was ignored only for this
931 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000932 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000933 }
934 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935 default:
936 if (DS.getStorageClassSpecLoc().isValid())
937 Diag(DS.getStorageClassSpecLoc(),
938 diag::err_storageclass_invalid_for_member);
939 else
940 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
941 D.getMutableDeclSpec().ClearStorageClassSpecs();
942 }
943
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000944 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
945 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000946 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000947
948 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000949 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000950 CXXScopeSpec &SS = D.getCXXScopeSpec();
951
952
953 if (SS.isSet() && !SS.isInvalid()) {
954 // The user provided a superfluous scope specifier inside a class
955 // definition:
956 //
957 // class X {
958 // int X::member;
959 // };
960 DeclContext *DC = 0;
961 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
962 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
963 << Name << FixItHint::CreateRemoval(SS.getRange());
964 else
965 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
966 << Name << SS.getRange();
967
968 SS.clear();
969 }
970
Douglas Gregor3447e762009-08-20 22:52:58 +0000971 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000972 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000973 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
974 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000975 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000976 } else {
John McCall48871652010-08-21 09:40:31 +0000977 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000978 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000979 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000980 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000981
982 // Non-instance-fields can't have a bitfield.
983 if (BitWidth) {
984 if (Member->isInvalidDecl()) {
985 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000986 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000987 // C++ 9.6p3: A bit-field shall not be a static member.
988 // "static member 'A' cannot be a bit-field"
989 Diag(Loc, diag::err_static_not_bitfield)
990 << Name << BitWidth->getSourceRange();
991 } else if (isa<TypedefDecl>(Member)) {
992 // "typedef member 'x' cannot be a bit-field"
993 Diag(Loc, diag::err_typedef_not_bitfield)
994 << Name << BitWidth->getSourceRange();
995 } else {
996 // A function typedef ("typedef int f(); f a;").
997 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
998 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000999 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001000 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Chris Lattnerd26760a2009-03-05 23:01:03 +00001003 BitWidth = 0;
1004 Member->setInvalidDecl();
1005 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001006
1007 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001008
Douglas Gregor3447e762009-08-20 22:52:58 +00001009 // If we have declared a member function template, set the access of the
1010 // templated declaration as well.
1011 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1012 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001013 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001014
Anders Carlsson13a69102011-01-20 04:34:22 +00001015 if (VS.isOverrideSpecified()) {
1016 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1017 if (!MD || !MD->isVirtual()) {
1018 Diag(Member->getLocStart(),
1019 diag::override_keyword_only_allowed_on_virtual_member_functions)
1020 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001021 } else
1022 MD->setIsMarkedOverride(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001023 }
1024 if (VS.isFinalSpecified()) {
1025 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1026 if (!MD || !MD->isVirtual()) {
1027 Diag(Member->getLocStart(),
1028 diag::override_keyword_only_allowed_on_virtual_member_functions)
1029 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001030 } else
1031 MD->setIsMarkedFinal(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001032 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001033
Anders Carlssonc87f8612011-01-20 06:29:02 +00001034 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001035
Douglas Gregor92751d42008-11-17 22:58:34 +00001036 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001037
Douglas Gregor0c880302009-03-11 23:00:04 +00001038 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001039 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001040 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001041 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001042
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001043 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001044 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001045 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001046 }
John McCall48871652010-08-21 09:40:31 +00001047 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001048}
1049
Douglas Gregor15e77a22009-12-31 09:10:24 +00001050/// \brief Find the direct and/or virtual base specifiers that
1051/// correspond to the given base type, for use in base initialization
1052/// within a constructor.
1053static bool FindBaseInitializer(Sema &SemaRef,
1054 CXXRecordDecl *ClassDecl,
1055 QualType BaseType,
1056 const CXXBaseSpecifier *&DirectBaseSpec,
1057 const CXXBaseSpecifier *&VirtualBaseSpec) {
1058 // First, check for a direct base class.
1059 DirectBaseSpec = 0;
1060 for (CXXRecordDecl::base_class_const_iterator Base
1061 = ClassDecl->bases_begin();
1062 Base != ClassDecl->bases_end(); ++Base) {
1063 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1064 // We found a direct base of this type. That's what we're
1065 // initializing.
1066 DirectBaseSpec = &*Base;
1067 break;
1068 }
1069 }
1070
1071 // Check for a virtual base class.
1072 // FIXME: We might be able to short-circuit this if we know in advance that
1073 // there are no virtual bases.
1074 VirtualBaseSpec = 0;
1075 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1076 // We haven't found a base yet; search the class hierarchy for a
1077 // virtual base class.
1078 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1079 /*DetectVirtual=*/false);
1080 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1081 BaseType, Paths)) {
1082 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1083 Path != Paths.end(); ++Path) {
1084 if (Path->back().Base->isVirtual()) {
1085 VirtualBaseSpec = Path->back().Base;
1086 break;
1087 }
1088 }
1089 }
1090 }
1091
1092 return DirectBaseSpec || VirtualBaseSpec;
1093}
1094
Douglas Gregore8381c02008-11-05 04:29:56 +00001095/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001096MemInitResult
John McCall48871652010-08-21 09:40:31 +00001097Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001098 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001099 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001100 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001101 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001102 SourceLocation IdLoc,
1103 SourceLocation LParenLoc,
1104 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001105 SourceLocation RParenLoc,
1106 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001107 if (!ConstructorD)
1108 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001109
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001110 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001111
1112 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001113 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001114 if (!Constructor) {
1115 // The user wrote a constructor initializer on a function that is
1116 // not a C++ constructor. Ignore the error for now, because we may
1117 // have more member initializers coming; we'll diagnose it just
1118 // once in ActOnMemInitializers.
1119 return true;
1120 }
1121
1122 CXXRecordDecl *ClassDecl = Constructor->getParent();
1123
1124 // C++ [class.base.init]p2:
1125 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001126 // constructor's class and, if not found in that scope, are looked
1127 // up in the scope containing the constructor's definition.
1128 // [Note: if the constructor's class contains a member with the
1129 // same name as a direct or virtual base class of the class, a
1130 // mem-initializer-id naming the member or base class and composed
1131 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001132 // mem-initializer-id for the hidden base class may be specified
1133 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001134 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001135 // Look for a member, first.
1136 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001137 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001138 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001139 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001140 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001141
Douglas Gregor44e7df62011-01-04 00:32:56 +00001142 if (Member) {
1143 if (EllipsisLoc.isValid())
1144 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1145 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1146
Francois Pichetd583da02010-12-04 09:14:42 +00001147 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001148 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001149 }
1150
Francois Pichetd583da02010-12-04 09:14:42 +00001151 // Handle anonymous union case.
1152 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001153 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1154 if (EllipsisLoc.isValid())
1155 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1156 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1157
Francois Pichetd583da02010-12-04 09:14:42 +00001158 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1159 NumArgs, IdLoc,
1160 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001161 }
Francois Pichetd583da02010-12-04 09:14:42 +00001162 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001163 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001164 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001165 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001166 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001167
1168 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001169 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001170 } else {
1171 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1172 LookupParsedName(R, S, &SS);
1173
1174 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1175 if (!TyD) {
1176 if (R.isAmbiguous()) return true;
1177
John McCallda6841b2010-04-09 19:01:14 +00001178 // We don't want access-control diagnostics here.
1179 R.suppressDiagnostics();
1180
Douglas Gregora3b624a2010-01-19 06:46:48 +00001181 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1182 bool NotUnknownSpecialization = false;
1183 DeclContext *DC = computeDeclContext(SS, false);
1184 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1185 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1186
1187 if (!NotUnknownSpecialization) {
1188 // When the scope specifier can refer to a member of an unknown
1189 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001190 BaseType = CheckTypenameType(ETK_None,
1191 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001192 *MemberOrBase, SourceLocation(),
1193 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001194 if (BaseType.isNull())
1195 return true;
1196
Douglas Gregora3b624a2010-01-19 06:46:48 +00001197 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001198 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001199 }
1200 }
1201
Douglas Gregor15e77a22009-12-31 09:10:24 +00001202 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001203 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001204 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1205 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001206 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001207 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001208 // We have found a non-static data member with a similar
1209 // name to what was typed; complain and initialize that
1210 // member.
1211 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1212 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001213 << FixItHint::CreateReplacement(R.getNameLoc(),
1214 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001215 Diag(Member->getLocation(), diag::note_previous_decl)
1216 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001217
1218 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1219 LParenLoc, RParenLoc);
1220 }
1221 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1222 const CXXBaseSpecifier *DirectBaseSpec;
1223 const CXXBaseSpecifier *VirtualBaseSpec;
1224 if (FindBaseInitializer(*this, ClassDecl,
1225 Context.getTypeDeclType(Type),
1226 DirectBaseSpec, VirtualBaseSpec)) {
1227 // We have found a direct or virtual base class with a
1228 // similar name to what was typed; complain and initialize
1229 // that base class.
1230 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1231 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001232 << FixItHint::CreateReplacement(R.getNameLoc(),
1233 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001234
1235 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1236 : VirtualBaseSpec;
1237 Diag(BaseSpec->getSourceRange().getBegin(),
1238 diag::note_base_class_specified_here)
1239 << BaseSpec->getType()
1240 << BaseSpec->getSourceRange();
1241
Douglas Gregor15e77a22009-12-31 09:10:24 +00001242 TyD = Type;
1243 }
1244 }
1245 }
1246
Douglas Gregora3b624a2010-01-19 06:46:48 +00001247 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001248 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1249 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1250 return true;
1251 }
John McCallb5a0d312009-12-21 10:41:20 +00001252 }
1253
Douglas Gregora3b624a2010-01-19 06:46:48 +00001254 if (BaseType.isNull()) {
1255 BaseType = Context.getTypeDeclType(TyD);
1256 if (SS.isSet()) {
1257 NestedNameSpecifier *Qualifier =
1258 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001259
Douglas Gregora3b624a2010-01-19 06:46:48 +00001260 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001261 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001262 }
John McCallb5a0d312009-12-21 10:41:20 +00001263 }
1264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
John McCallbcd03502009-12-07 02:54:59 +00001266 if (!TInfo)
1267 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001268
John McCallbcd03502009-12-07 02:54:59 +00001269 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001270 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001271}
1272
John McCalle22a04a2009-11-04 23:02:40 +00001273/// Checks an initializer expression for use of uninitialized fields, such as
1274/// containing the field that is being initialized. Returns true if there is an
1275/// uninitialized field was used an updates the SourceLocation parameter; false
1276/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001277static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001278 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001279 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001280 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1281
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001282 if (isa<CallExpr>(S)) {
1283 // Do not descend into function calls or constructors, as the use
1284 // of an uninitialized field may be valid. One would have to inspect
1285 // the contents of the function/ctor to determine if it is safe or not.
1286 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1287 // may be safe, depending on what the function/ctor does.
1288 return false;
1289 }
1290 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1291 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001292
1293 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1294 // The member expression points to a static data member.
1295 assert(VD->isStaticDataMember() &&
1296 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001297 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001298 return false;
1299 }
1300
1301 if (isa<EnumConstantDecl>(RhsField)) {
1302 // The member expression points to an enum.
1303 return false;
1304 }
1305
John McCalle22a04a2009-11-04 23:02:40 +00001306 if (RhsField == LhsField) {
1307 // Initializing a field with itself. Throw a warning.
1308 // But wait; there are exceptions!
1309 // Exception #1: The field may not belong to this record.
1310 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001311 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001312 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1313 // Even though the field matches, it does not belong to this record.
1314 return false;
1315 }
1316 // None of the exceptions triggered; return true to indicate an
1317 // uninitialized field was used.
1318 *L = ME->getMemberLoc();
1319 return true;
1320 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001321 } else if (isa<SizeOfAlignOfExpr>(S)) {
1322 // sizeof/alignof doesn't reference contents, do not warn.
1323 return false;
1324 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1325 // address-of doesn't reference contents (the pointer may be dereferenced
1326 // in the same expression but it would be rare; and weird).
1327 if (UOE->getOpcode() == UO_AddrOf)
1328 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001329 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001330 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1331 it != e; ++it) {
1332 if (!*it) {
1333 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001334 continue;
1335 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001336 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1337 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001338 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001339 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001340}
1341
John McCallfaf5fb42010-08-26 23:41:50 +00001342MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001343Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001344 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001345 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001346 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001347 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1348 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1349 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001350 "Member must be a FieldDecl or IndirectFieldDecl");
1351
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001352 if (Member->isInvalidDecl())
1353 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001354
John McCalle22a04a2009-11-04 23:02:40 +00001355 // Diagnose value-uses of fields to initialize themselves, e.g.
1356 // foo(foo)
1357 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001358 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001359 for (unsigned i = 0; i < NumArgs; ++i) {
1360 SourceLocation L;
1361 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1362 // FIXME: Return true in the case when other fields are used before being
1363 // uninitialized. For example, let this field be the i'th field. When
1364 // initializing the i'th field, throw a warning if any of the >= i'th
1365 // fields are used, as they are not yet initialized.
1366 // Right now we are only handling the case where the i'th field uses
1367 // itself in its initializer.
1368 Diag(L, diag::warn_field_is_uninit);
1369 }
1370 }
1371
Eli Friedman8e1433b2009-07-29 19:44:27 +00001372 bool HasDependentArg = false;
1373 for (unsigned i = 0; i < NumArgs; i++)
1374 HasDependentArg |= Args[i]->isTypeDependent();
1375
Chandler Carruthd44c3102010-12-06 09:23:57 +00001376 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001377 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001378 // Can't check initialization for a member of dependent type or when
1379 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001380 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1381 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001382
1383 // Erase any temporaries within this evaluation context; we're not
1384 // going to track them in the AST, since we'll be rebuilding the
1385 // ASTs during template instantiation.
1386 ExprTemporaries.erase(
1387 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1388 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001389 } else {
1390 // Initialize the member.
1391 InitializedEntity MemberEntity =
1392 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1393 : InitializedEntity::InitializeMember(IndirectMember, 0);
1394 InitializationKind Kind =
1395 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001396
Chandler Carruthd44c3102010-12-06 09:23:57 +00001397 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1398
1399 ExprResult MemberInit =
1400 InitSeq.Perform(*this, MemberEntity, Kind,
1401 MultiExprArg(*this, Args, NumArgs), 0);
1402 if (MemberInit.isInvalid())
1403 return true;
1404
1405 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1406
1407 // C++0x [class.base.init]p7:
1408 // The initialization of each base and member constitutes a
1409 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001410 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001411 if (MemberInit.isInvalid())
1412 return true;
1413
1414 // If we are in a dependent context, template instantiation will
1415 // perform this type-checking again. Just save the arguments that we
1416 // received in a ParenListExpr.
1417 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1418 // of the information that we have about the member
1419 // initializer. However, deconstructing the ASTs is a dicey process,
1420 // and this approach is far more likely to get the corner cases right.
1421 if (CurContext->isDependentContext())
1422 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1423 RParenLoc);
1424 else
1425 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001426 }
1427
Chandler Carruthd44c3102010-12-06 09:23:57 +00001428 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001429 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001430 IdLoc, LParenLoc, Init,
1431 RParenLoc);
1432 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001433 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001434 IdLoc, LParenLoc, Init,
1435 RParenLoc);
1436 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001437}
1438
John McCallfaf5fb42010-08-26 23:41:50 +00001439MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001440Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1441 Expr **Args, unsigned NumArgs,
1442 SourceLocation LParenLoc,
1443 SourceLocation RParenLoc,
1444 CXXRecordDecl *ClassDecl,
1445 SourceLocation EllipsisLoc) {
1446 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1447 if (!LangOpts.CPlusPlus0x)
1448 return Diag(Loc, diag::err_delegation_0x_only)
1449 << TInfo->getTypeLoc().getLocalSourceRange();
1450
1451 return Diag(Loc, diag::err_delegation_unimplemented)
1452 << TInfo->getTypeLoc().getLocalSourceRange();
1453}
1454
1455MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001456Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001457 Expr **Args, unsigned NumArgs,
1458 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001459 CXXRecordDecl *ClassDecl,
1460 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001461 bool HasDependentArg = false;
1462 for (unsigned i = 0; i < NumArgs; i++)
1463 HasDependentArg |= Args[i]->isTypeDependent();
1464
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001465 SourceLocation BaseLoc
1466 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1467
1468 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1469 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1470 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1471
1472 // C++ [class.base.init]p2:
1473 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001474 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001475 // of that class, the mem-initializer is ill-formed. A
1476 // mem-initializer-list can initialize a base class using any
1477 // name that denotes that base class type.
1478 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1479
Douglas Gregor44e7df62011-01-04 00:32:56 +00001480 if (EllipsisLoc.isValid()) {
1481 // This is a pack expansion.
1482 if (!BaseType->containsUnexpandedParameterPack()) {
1483 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1484 << SourceRange(BaseLoc, RParenLoc);
1485
1486 EllipsisLoc = SourceLocation();
1487 }
1488 } else {
1489 // Check for any unexpanded parameter packs.
1490 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1491 return true;
1492
1493 for (unsigned I = 0; I != NumArgs; ++I)
1494 if (DiagnoseUnexpandedParameterPack(Args[I]))
1495 return true;
1496 }
1497
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001498 // Check for direct and virtual base classes.
1499 const CXXBaseSpecifier *DirectBaseSpec = 0;
1500 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1501 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001502 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1503 BaseType))
1504 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1505 LParenLoc, RParenLoc, ClassDecl,
1506 EllipsisLoc);
1507
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001508 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1509 VirtualBaseSpec);
1510
1511 // C++ [base.class.init]p2:
1512 // Unless the mem-initializer-id names a nonstatic data member of the
1513 // constructor's class or a direct or virtual base of that class, the
1514 // mem-initializer is ill-formed.
1515 if (!DirectBaseSpec && !VirtualBaseSpec) {
1516 // If the class has any dependent bases, then it's possible that
1517 // one of those types will resolve to the same type as
1518 // BaseType. Therefore, just treat this as a dependent base
1519 // class initialization. FIXME: Should we try to check the
1520 // initialization anyway? It seems odd.
1521 if (ClassDecl->hasAnyDependentBases())
1522 Dependent = true;
1523 else
1524 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1525 << BaseType << Context.getTypeDeclType(ClassDecl)
1526 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1527 }
1528 }
1529
1530 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001531 // Can't check initialization for a base of dependent type or when
1532 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001533 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001534 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1535 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001536
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001537 // Erase any temporaries within this evaluation context; we're not
1538 // going to track them in the AST, since we'll be rebuilding the
1539 // ASTs during template instantiation.
1540 ExprTemporaries.erase(
1541 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1542 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001543
Alexis Hunt1d792652011-01-08 20:30:50 +00001544 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001545 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001546 LParenLoc,
1547 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001548 RParenLoc,
1549 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001550 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001551
1552 // C++ [base.class.init]p2:
1553 // If a mem-initializer-id is ambiguous because it designates both
1554 // a direct non-virtual base class and an inherited virtual base
1555 // class, the mem-initializer is ill-formed.
1556 if (DirectBaseSpec && VirtualBaseSpec)
1557 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001558 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001559
1560 CXXBaseSpecifier *BaseSpec
1561 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1562 if (!BaseSpec)
1563 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1564
1565 // Initialize the base.
1566 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001567 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001568 InitializationKind Kind =
1569 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1570
1571 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1572
John McCalldadc5752010-08-24 06:29:42 +00001573 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001574 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001575 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001576 if (BaseInit.isInvalid())
1577 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001578
1579 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001580
1581 // C++0x [class.base.init]p7:
1582 // The initialization of each base and member constitutes a
1583 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001584 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001585 if (BaseInit.isInvalid())
1586 return true;
1587
1588 // If we are in a dependent context, template instantiation will
1589 // perform this type-checking again. Just save the arguments that we
1590 // received in a ParenListExpr.
1591 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1592 // of the information that we have about the base
1593 // initializer. However, deconstructing the ASTs is a dicey process,
1594 // and this approach is far more likely to get the corner cases right.
1595 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001596 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001597 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1598 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001599 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001600 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001601 LParenLoc,
1602 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001603 RParenLoc,
1604 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001605 }
1606
Alexis Hunt1d792652011-01-08 20:30:50 +00001607 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001608 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001609 LParenLoc,
1610 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001611 RParenLoc,
1612 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001613}
1614
Anders Carlsson1b00e242010-04-23 03:10:23 +00001615/// ImplicitInitializerKind - How an implicit base or member initializer should
1616/// initialize its base or member.
1617enum ImplicitInitializerKind {
1618 IIK_Default,
1619 IIK_Copy,
1620 IIK_Move
1621};
1622
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001623static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001624BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001625 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001626 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001627 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001628 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001629 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001630 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1631 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001632
John McCalldadc5752010-08-24 06:29:42 +00001633 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001634
1635 switch (ImplicitInitKind) {
1636 case IIK_Default: {
1637 InitializationKind InitKind
1638 = InitializationKind::CreateDefault(Constructor->getLocation());
1639 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1640 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001641 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001642 break;
1643 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001644
Anders Carlsson1b00e242010-04-23 03:10:23 +00001645 case IIK_Copy: {
1646 ParmVarDecl *Param = Constructor->getParamDecl(0);
1647 QualType ParamType = Param->getType().getNonReferenceType();
1648
1649 Expr *CopyCtorArg =
1650 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001651 Constructor->getLocation(), ParamType,
1652 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001653
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001654 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001655 QualType ArgTy =
1656 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1657 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001658
1659 CXXCastPath BasePath;
1660 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001661 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001662 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001663 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001664
Anders Carlsson1b00e242010-04-23 03:10:23 +00001665 InitializationKind InitKind
1666 = InitializationKind::CreateDirect(Constructor->getLocation(),
1667 SourceLocation(), SourceLocation());
1668 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1669 &CopyCtorArg, 1);
1670 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001671 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001672 break;
1673 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001674
Anders Carlsson1b00e242010-04-23 03:10:23 +00001675 case IIK_Move:
1676 assert(false && "Unhandled initializer kind!");
1677 }
John McCallb268a282010-08-23 23:25:46 +00001678
Douglas Gregora40433a2010-12-07 00:41:46 +00001679 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001680 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001681 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001682
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001683 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001684 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001685 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1686 SourceLocation()),
1687 BaseSpec->isVirtual(),
1688 SourceLocation(),
1689 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001690 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001691 SourceLocation());
1692
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001693 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001694}
1695
Anders Carlsson3c1db572010-04-23 02:15:47 +00001696static bool
1697BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001698 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001699 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001700 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001701 if (Field->isInvalidDecl())
1702 return true;
1703
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001704 SourceLocation Loc = Constructor->getLocation();
1705
Anders Carlsson423f5d82010-04-23 16:04:08 +00001706 if (ImplicitInitKind == IIK_Copy) {
1707 ParmVarDecl *Param = Constructor->getParamDecl(0);
1708 QualType ParamType = Param->getType().getNonReferenceType();
1709
1710 Expr *MemberExprBase =
1711 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001712 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001713
1714 // Build a reference to this field within the parameter.
1715 CXXScopeSpec SS;
1716 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1717 Sema::LookupMemberName);
1718 MemberLookup.addDecl(Field, AS_public);
1719 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001720 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001721 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001722 ParamType, Loc,
1723 /*IsArrow=*/false,
1724 SS,
1725 /*FirstQualifierInScope=*/0,
1726 MemberLookup,
1727 /*TemplateArgs=*/0);
1728 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001729 return true;
1730
Douglas Gregor94f9a482010-05-05 05:51:00 +00001731 // When the field we are copying is an array, create index variables for
1732 // each dimension of the array. We use these index variables to subscript
1733 // the source array, and other clients (e.g., CodeGen) will perform the
1734 // necessary iteration with these index variables.
1735 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1736 QualType BaseType = Field->getType();
1737 QualType SizeType = SemaRef.Context.getSizeType();
1738 while (const ConstantArrayType *Array
1739 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1740 // Create the iteration variable for this array index.
1741 IdentifierInfo *IterationVarName = 0;
1742 {
1743 llvm::SmallString<8> Str;
1744 llvm::raw_svector_ostream OS(Str);
1745 OS << "__i" << IndexVariables.size();
1746 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1747 }
1748 VarDecl *IterationVar
1749 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1750 IterationVarName, SizeType,
1751 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001752 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001753 IndexVariables.push_back(IterationVar);
1754
1755 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001756 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001757 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001758 assert(!IterationVarRef.isInvalid() &&
1759 "Reference to invented variable cannot fail!");
1760
1761 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001762 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001763 Loc,
John McCallb268a282010-08-23 23:25:46 +00001764 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001765 Loc);
1766 if (CopyCtorArg.isInvalid())
1767 return true;
1768
1769 BaseType = Array->getElementType();
1770 }
1771
1772 // Construct the entity that we will be initializing. For an array, this
1773 // will be first element in the array, which may require several levels
1774 // of array-subscript entities.
1775 llvm::SmallVector<InitializedEntity, 4> Entities;
1776 Entities.reserve(1 + IndexVariables.size());
1777 Entities.push_back(InitializedEntity::InitializeMember(Field));
1778 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1779 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1780 0,
1781 Entities.back()));
1782
1783 // Direct-initialize to use the copy constructor.
1784 InitializationKind InitKind =
1785 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1786
1787 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1788 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1789 &CopyCtorArgE, 1);
1790
John McCalldadc5752010-08-24 06:29:42 +00001791 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001792 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001793 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001794 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001795 if (MemberInit.isInvalid())
1796 return true;
1797
1798 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001799 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001800 MemberInit.takeAs<Expr>(), Loc,
1801 IndexVariables.data(),
1802 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001803 return false;
1804 }
1805
Anders Carlsson423f5d82010-04-23 16:04:08 +00001806 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1807
Anders Carlsson3c1db572010-04-23 02:15:47 +00001808 QualType FieldBaseElementType =
1809 SemaRef.Context.getBaseElementType(Field->getType());
1810
Anders Carlsson3c1db572010-04-23 02:15:47 +00001811 if (FieldBaseElementType->isRecordType()) {
1812 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001813 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001814 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001815
1816 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001817 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001818 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001819
Douglas Gregora40433a2010-12-07 00:41:46 +00001820 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001821 if (MemberInit.isInvalid())
1822 return true;
1823
1824 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001825 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001826 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001827 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001828 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001829 return false;
1830 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001831
1832 if (FieldBaseElementType->isReferenceType()) {
1833 SemaRef.Diag(Constructor->getLocation(),
1834 diag::err_uninitialized_member_in_ctor)
1835 << (int)Constructor->isImplicit()
1836 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1837 << 0 << Field->getDeclName();
1838 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1839 return true;
1840 }
1841
1842 if (FieldBaseElementType.isConstQualified()) {
1843 SemaRef.Diag(Constructor->getLocation(),
1844 diag::err_uninitialized_member_in_ctor)
1845 << (int)Constructor->isImplicit()
1846 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1847 << 1 << Field->getDeclName();
1848 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1849 return true;
1850 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001851
1852 // Nothing to initialize.
1853 CXXMemberInit = 0;
1854 return false;
1855}
John McCallbc83b3f2010-05-20 23:23:51 +00001856
1857namespace {
1858struct BaseAndFieldInfo {
1859 Sema &S;
1860 CXXConstructorDecl *Ctor;
1861 bool AnyErrorsInInits;
1862 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001863 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1864 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001865
1866 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1867 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1868 // FIXME: Handle implicit move constructors.
1869 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1870 IIK = IIK_Copy;
1871 else
1872 IIK = IIK_Default;
1873 }
1874};
1875}
1876
1877static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1878 FieldDecl *Top, FieldDecl *Field) {
1879
Chandler Carruth139e9622010-06-30 02:59:29 +00001880 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001881 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001882 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001883 return false;
1884 }
1885
1886 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1887 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1888 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001889 CXXRecordDecl *FieldClassDecl
1890 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001891
1892 // Even though union members never have non-trivial default
1893 // constructions in C++03, we still build member initializers for aggregate
1894 // record types which can be union members, and C++0x allows non-trivial
1895 // default constructors for union members, so we ensure that only one
1896 // member is initialized for these.
1897 if (FieldClassDecl->isUnion()) {
1898 // First check for an explicit initializer for one field.
1899 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1900 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001901 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001902 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001903
1904 // Once we've initialized a field of an anonymous union, the union
1905 // field in the class is also initialized, so exit immediately.
1906 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001907 } else if ((*FA)->isAnonymousStructOrUnion()) {
1908 if (CollectFieldInitializer(Info, Top, *FA))
1909 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001910 }
1911 }
1912
1913 // Fallthrough and construct a default initializer for the union as
1914 // a whole, which can call its default constructor if such a thing exists
1915 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1916 // behavior going forward with C++0x, when anonymous unions there are
1917 // finalized, we should revisit this.
1918 } else {
1919 // For structs, we simply descend through to initialize all members where
1920 // necessary.
1921 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1922 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1923 if (CollectFieldInitializer(Info, Top, *FA))
1924 return true;
1925 }
1926 }
John McCallbc83b3f2010-05-20 23:23:51 +00001927 }
1928
1929 // Don't try to build an implicit initializer if there were semantic
1930 // errors in any of the initializers (and therefore we might be
1931 // missing some that the user actually wrote).
1932 if (Info.AnyErrorsInInits)
1933 return false;
1934
Alexis Hunt1d792652011-01-08 20:30:50 +00001935 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001936 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1937 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001938
Francois Pichetd583da02010-12-04 09:14:42 +00001939 if (Init)
1940 Info.AllToInit.push_back(Init);
1941
John McCallbc83b3f2010-05-20 23:23:51 +00001942 return false;
1943}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001944
Eli Friedman9cf6b592009-11-09 19:20:36 +00001945bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001946Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1947 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001948 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001949 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001950 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001951 // Just store the initializers as written, they will be checked during
1952 // instantiation.
1953 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001954 Constructor->setNumCtorInitializers(NumInitializers);
1955 CXXCtorInitializer **baseOrMemberInitializers =
1956 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001957 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001958 NumInitializers * sizeof(CXXCtorInitializer*));
1959 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001960 }
1961
1962 return false;
1963 }
1964
John McCallbc83b3f2010-05-20 23:23:51 +00001965 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001966
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001967 // We need to build the initializer AST according to order of construction
1968 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001969 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001970 if (!ClassDecl)
1971 return true;
1972
Eli Friedman9cf6b592009-11-09 19:20:36 +00001973 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001975 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001976 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001977
1978 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001979 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001980 else
Francois Pichetd583da02010-12-04 09:14:42 +00001981 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001982 }
1983
Anders Carlsson43c64af2010-04-21 19:52:01 +00001984 // Keep track of the direct virtual bases.
1985 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1986 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1987 E = ClassDecl->bases_end(); I != E; ++I) {
1988 if (I->isVirtual())
1989 DirectVBases.insert(I);
1990 }
1991
Anders Carlssondb0a9652010-04-02 06:26:44 +00001992 // Push virtual bases before others.
1993 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1994 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1995
Alexis Hunt1d792652011-01-08 20:30:50 +00001996 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001997 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1998 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001999 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002000 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002001 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002002 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002003 VBase, IsInheritedVirtualBase,
2004 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002005 HadError = true;
2006 continue;
2007 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002008
John McCallbc83b3f2010-05-20 23:23:51 +00002009 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002010 }
2011 }
Mike Stump11289f42009-09-09 15:08:12 +00002012
John McCallbc83b3f2010-05-20 23:23:51 +00002013 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002014 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2015 E = ClassDecl->bases_end(); Base != E; ++Base) {
2016 // Virtuals are in the virtual base list and already constructed.
2017 if (Base->isVirtual())
2018 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Alexis Hunt1d792652011-01-08 20:30:50 +00002020 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002021 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2022 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002023 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002024 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002025 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002026 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002027 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002028 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002029 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002030 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002031
John McCallbc83b3f2010-05-20 23:23:51 +00002032 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002033 }
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
John McCallbc83b3f2010-05-20 23:23:51 +00002036 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002037 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002038 E = ClassDecl->field_end(); Field != E; ++Field) {
2039 if ((*Field)->getType()->isIncompleteArrayType()) {
2040 assert(ClassDecl->hasFlexibleArrayMember() &&
2041 "Incomplete array type is not valid");
2042 continue;
2043 }
John McCallbc83b3f2010-05-20 23:23:51 +00002044 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002045 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002046 }
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCallbc83b3f2010-05-20 23:23:51 +00002048 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002049 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002050 Constructor->setNumCtorInitializers(NumInitializers);
2051 CXXCtorInitializer **baseOrMemberInitializers =
2052 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002053 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002054 NumInitializers * sizeof(CXXCtorInitializer*));
2055 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002056
John McCalla6309952010-03-16 21:39:52 +00002057 // Constructors implicitly reference the base and member
2058 // destructors.
2059 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2060 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002061 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002062
2063 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002064}
2065
Eli Friedman952c15d2009-07-21 19:28:10 +00002066static void *GetKeyForTopLevelField(FieldDecl *Field) {
2067 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002069 if (RT->getDecl()->isAnonymousStructOrUnion())
2070 return static_cast<void *>(RT->getDecl());
2071 }
2072 return static_cast<void *>(Field);
2073}
2074
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002075static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002076 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002077}
2078
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002079static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002080 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002081 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002082 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002083
Eli Friedman952c15d2009-07-21 19:28:10 +00002084 // For fields injected into the class via declaration of an anonymous union,
2085 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002086 FieldDecl *Field = Member->getAnyMember();
2087
John McCall23eebd92010-04-10 09:28:51 +00002088 // If the field is a member of an anonymous struct or union, our key
2089 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002090 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002091 if (RD->isAnonymousStructOrUnion()) {
2092 while (true) {
2093 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2094 if (Parent->isAnonymousStructOrUnion())
2095 RD = Parent;
2096 else
2097 break;
2098 }
2099
Anders Carlsson83ac3122010-03-30 16:19:37 +00002100 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Anders Carlssona942dcd2010-03-30 15:39:27 +00002103 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002104}
2105
Anders Carlssone857b292010-04-02 03:37:03 +00002106static void
2107DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002108 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002109 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002110 unsigned NumInits) {
2111 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002112 return;
Mike Stump11289f42009-09-09 15:08:12 +00002113
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002114 // Don't check initializers order unless the warning is enabled at the
2115 // location of at least one initializer.
2116 bool ShouldCheckOrder = false;
2117 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002118 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002119 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2120 Init->getSourceLocation())
2121 != Diagnostic::Ignored) {
2122 ShouldCheckOrder = true;
2123 break;
2124 }
2125 }
2126 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002127 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002128
John McCallbb7b6582010-04-10 07:37:23 +00002129 // Build the list of bases and members in the order that they'll
2130 // actually be initialized. The explicit initializers should be in
2131 // this same order but may be missing things.
2132 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002133
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002134 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2135
John McCallbb7b6582010-04-10 07:37:23 +00002136 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002137 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002138 ClassDecl->vbases_begin(),
2139 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002140 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002141
John McCallbb7b6582010-04-10 07:37:23 +00002142 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002143 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002144 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002145 if (Base->isVirtual())
2146 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002147 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
John McCallbb7b6582010-04-10 07:37:23 +00002150 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002151 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2152 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002153 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002154
John McCallbb7b6582010-04-10 07:37:23 +00002155 unsigned NumIdealInits = IdealInitKeys.size();
2156 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002157
Alexis Hunt1d792652011-01-08 20:30:50 +00002158 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002159 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002160 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002161 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002162
2163 // Scan forward to try to find this initializer in the idealized
2164 // initializers list.
2165 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2166 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002167 break;
John McCallbb7b6582010-04-10 07:37:23 +00002168
2169 // If we didn't find this initializer, it must be because we
2170 // scanned past it on a previous iteration. That can only
2171 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002172 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002173 Sema::SemaDiagnosticBuilder D =
2174 SemaRef.Diag(PrevInit->getSourceLocation(),
2175 diag::warn_initializer_out_of_order);
2176
Francois Pichetd583da02010-12-04 09:14:42 +00002177 if (PrevInit->isAnyMemberInitializer())
2178 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002179 else
2180 D << 1 << PrevInit->getBaseClassInfo()->getType();
2181
Francois Pichetd583da02010-12-04 09:14:42 +00002182 if (Init->isAnyMemberInitializer())
2183 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002184 else
2185 D << 1 << Init->getBaseClassInfo()->getType();
2186
2187 // Move back to the initializer's location in the ideal list.
2188 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2189 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002190 break;
John McCallbb7b6582010-04-10 07:37:23 +00002191
2192 assert(IdealIndex != NumIdealInits &&
2193 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002194 }
John McCallbb7b6582010-04-10 07:37:23 +00002195
2196 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002197 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002198}
2199
John McCall23eebd92010-04-10 09:28:51 +00002200namespace {
2201bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002202 CXXCtorInitializer *Init,
2203 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002204 if (!PrevInit) {
2205 PrevInit = Init;
2206 return false;
2207 }
2208
2209 if (FieldDecl *Field = Init->getMember())
2210 S.Diag(Init->getSourceLocation(),
2211 diag::err_multiple_mem_initialization)
2212 << Field->getDeclName()
2213 << Init->getSourceRange();
2214 else {
John McCall424cec92011-01-19 06:33:43 +00002215 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002216 assert(BaseClass && "neither field nor base");
2217 S.Diag(Init->getSourceLocation(),
2218 diag::err_multiple_base_initialization)
2219 << QualType(BaseClass, 0)
2220 << Init->getSourceRange();
2221 }
2222 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2223 << 0 << PrevInit->getSourceRange();
2224
2225 return true;
2226}
2227
Alexis Hunt1d792652011-01-08 20:30:50 +00002228typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002229typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2230
2231bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002232 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002233 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002234 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002235 RecordDecl *Parent = Field->getParent();
2236 if (!Parent->isAnonymousStructOrUnion())
2237 return false;
2238
2239 NamedDecl *Child = Field;
2240 do {
2241 if (Parent->isUnion()) {
2242 UnionEntry &En = Unions[Parent];
2243 if (En.first && En.first != Child) {
2244 S.Diag(Init->getSourceLocation(),
2245 diag::err_multiple_mem_union_initialization)
2246 << Field->getDeclName()
2247 << Init->getSourceRange();
2248 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2249 << 0 << En.second->getSourceRange();
2250 return true;
2251 } else if (!En.first) {
2252 En.first = Child;
2253 En.second = Init;
2254 }
2255 }
2256
2257 Child = Parent;
2258 Parent = cast<RecordDecl>(Parent->getDeclContext());
2259 } while (Parent->isAnonymousStructOrUnion());
2260
2261 return false;
2262}
2263}
2264
Anders Carlssone857b292010-04-02 03:37:03 +00002265/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002266void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002267 SourceLocation ColonLoc,
2268 MemInitTy **meminits, unsigned NumMemInits,
2269 bool AnyErrors) {
2270 if (!ConstructorDecl)
2271 return;
2272
2273 AdjustDeclIfTemplate(ConstructorDecl);
2274
2275 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002276 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002277
2278 if (!Constructor) {
2279 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2280 return;
2281 }
2282
Alexis Hunt1d792652011-01-08 20:30:50 +00002283 CXXCtorInitializer **MemInits =
2284 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002285
2286 // Mapping for the duplicate initializers check.
2287 // For member initializers, this is keyed with a FieldDecl*.
2288 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002289 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002290
2291 // Mapping for the inconsistent anonymous-union initializers check.
2292 RedundantUnionMap MemberUnions;
2293
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002294 bool HadError = false;
2295 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002296 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002297
Abramo Bagnara341d7832010-05-26 18:09:23 +00002298 // Set the source order index.
2299 Init->setSourceOrder(i);
2300
Francois Pichetd583da02010-12-04 09:14:42 +00002301 if (Init->isAnyMemberInitializer()) {
2302 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002303 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2304 CheckRedundantUnionInit(*this, Init, MemberUnions))
2305 HadError = true;
2306 } else {
2307 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2308 if (CheckRedundantInit(*this, Init, Members[Key]))
2309 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002310 }
Anders Carlssone857b292010-04-02 03:37:03 +00002311 }
2312
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002313 if (HadError)
2314 return;
2315
Anders Carlssone857b292010-04-02 03:37:03 +00002316 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002317
Alexis Hunt1d792652011-01-08 20:30:50 +00002318 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002319}
2320
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002321void
John McCalla6309952010-03-16 21:39:52 +00002322Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2323 CXXRecordDecl *ClassDecl) {
2324 // Ignore dependent contexts.
2325 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002326 return;
John McCall1064d7e2010-03-16 05:22:47 +00002327
2328 // FIXME: all the access-control diagnostics are positioned on the
2329 // field/base declaration. That's probably good; that said, the
2330 // user might reasonably want to know why the destructor is being
2331 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002332
Anders Carlssondee9a302009-11-17 04:44:12 +00002333 // Non-static data members.
2334 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2335 E = ClassDecl->field_end(); I != E; ++I) {
2336 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002337 if (Field->isInvalidDecl())
2338 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002339 QualType FieldType = Context.getBaseElementType(Field->getType());
2340
2341 const RecordType* RT = FieldType->getAs<RecordType>();
2342 if (!RT)
2343 continue;
2344
2345 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2346 if (FieldClassDecl->hasTrivialDestructor())
2347 continue;
2348
Douglas Gregore71edda2010-07-01 22:47:18 +00002349 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002350 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002351 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002352 << Field->getDeclName()
2353 << FieldType);
2354
John McCalla6309952010-03-16 21:39:52 +00002355 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002356 }
2357
John McCall1064d7e2010-03-16 05:22:47 +00002358 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2359
Anders Carlssondee9a302009-11-17 04:44:12 +00002360 // Bases.
2361 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2362 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002363 // Bases are always records in a well-formed non-dependent class.
2364 const RecordType *RT = Base->getType()->getAs<RecordType>();
2365
2366 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002367 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002368 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002369
2370 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002371 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002372 if (BaseClassDecl->hasTrivialDestructor())
2373 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002374
Douglas Gregore71edda2010-07-01 22:47:18 +00002375 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002376
2377 // FIXME: caret should be on the start of the class name
2378 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002379 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002380 << Base->getType()
2381 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002382
John McCalla6309952010-03-16 21:39:52 +00002383 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002384 }
2385
2386 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002387 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2388 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002389
2390 // Bases are always records in a well-formed non-dependent class.
2391 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2392
2393 // Ignore direct virtual bases.
2394 if (DirectVirtualBases.count(RT))
2395 continue;
2396
Anders Carlssondee9a302009-11-17 04:44:12 +00002397 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002398 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002399 if (BaseClassDecl->hasTrivialDestructor())
2400 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002401
Douglas Gregore71edda2010-07-01 22:47:18 +00002402 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002403 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002404 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002405 << VBase->getType());
2406
John McCalla6309952010-03-16 21:39:52 +00002407 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002408 }
2409}
2410
John McCall48871652010-08-21 09:40:31 +00002411void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002412 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002413 return;
Mike Stump11289f42009-09-09 15:08:12 +00002414
Mike Stump11289f42009-09-09 15:08:12 +00002415 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002416 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002417 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002418}
2419
Mike Stump11289f42009-09-09 15:08:12 +00002420bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002421 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002422 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002423 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002424 else
John McCall02db245d2010-08-18 09:41:07 +00002425 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002426}
2427
Anders Carlssoneabf7702009-08-27 00:13:57 +00002428bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002429 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002430 if (!getLangOptions().CPlusPlus)
2431 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002432
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002433 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002434 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002435
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002436 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002437 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002438 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002439 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002441 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002442 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002443 }
Mike Stump11289f42009-09-09 15:08:12 +00002444
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002445 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002446 if (!RT)
2447 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002448
John McCall67da35c2010-02-04 22:26:26 +00002449 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002450
John McCall02db245d2010-08-18 09:41:07 +00002451 // We can't answer whether something is abstract until it has a
2452 // definition. If it's currently being defined, we'll walk back
2453 // over all the declarations when we have a full definition.
2454 const CXXRecordDecl *Def = RD->getDefinition();
2455 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002456 return false;
2457
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002458 if (!RD->isAbstract())
2459 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002460
Anders Carlssoneabf7702009-08-27 00:13:57 +00002461 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002462 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002463
John McCall02db245d2010-08-18 09:41:07 +00002464 return true;
2465}
2466
2467void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2468 // Check if we've already emitted the list of pure virtual functions
2469 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002470 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002471 return;
Mike Stump11289f42009-09-09 15:08:12 +00002472
Douglas Gregor4165bd62010-03-23 23:47:56 +00002473 CXXFinalOverriderMap FinalOverriders;
2474 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002475
Anders Carlssona2f74f32010-06-03 01:00:02 +00002476 // Keep a set of seen pure methods so we won't diagnose the same method
2477 // more than once.
2478 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2479
Douglas Gregor4165bd62010-03-23 23:47:56 +00002480 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2481 MEnd = FinalOverriders.end();
2482 M != MEnd;
2483 ++M) {
2484 for (OverridingMethods::iterator SO = M->second.begin(),
2485 SOEnd = M->second.end();
2486 SO != SOEnd; ++SO) {
2487 // C++ [class.abstract]p4:
2488 // A class is abstract if it contains or inherits at least one
2489 // pure virtual function for which the final overrider is pure
2490 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002491
Douglas Gregor4165bd62010-03-23 23:47:56 +00002492 //
2493 if (SO->second.size() != 1)
2494 continue;
2495
2496 if (!SO->second.front().Method->isPure())
2497 continue;
2498
Anders Carlssona2f74f32010-06-03 01:00:02 +00002499 if (!SeenPureMethods.insert(SO->second.front().Method))
2500 continue;
2501
Douglas Gregor4165bd62010-03-23 23:47:56 +00002502 Diag(SO->second.front().Method->getLocation(),
2503 diag::note_pure_virtual_function)
2504 << SO->second.front().Method->getDeclName();
2505 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002506 }
2507
2508 if (!PureVirtualClassDiagSet)
2509 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2510 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002511}
2512
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002513namespace {
John McCall02db245d2010-08-18 09:41:07 +00002514struct AbstractUsageInfo {
2515 Sema &S;
2516 CXXRecordDecl *Record;
2517 CanQualType AbstractType;
2518 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002519
John McCall02db245d2010-08-18 09:41:07 +00002520 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2521 : S(S), Record(Record),
2522 AbstractType(S.Context.getCanonicalType(
2523 S.Context.getTypeDeclType(Record))),
2524 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002525
John McCall02db245d2010-08-18 09:41:07 +00002526 void DiagnoseAbstractType() {
2527 if (Invalid) return;
2528 S.DiagnoseAbstractType(Record);
2529 Invalid = true;
2530 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002531
John McCall02db245d2010-08-18 09:41:07 +00002532 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2533};
2534
2535struct CheckAbstractUsage {
2536 AbstractUsageInfo &Info;
2537 const NamedDecl *Ctx;
2538
2539 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2540 : Info(Info), Ctx(Ctx) {}
2541
2542 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2543 switch (TL.getTypeLocClass()) {
2544#define ABSTRACT_TYPELOC(CLASS, PARENT)
2545#define TYPELOC(CLASS, PARENT) \
2546 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2547#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002548 }
John McCall02db245d2010-08-18 09:41:07 +00002549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550
John McCall02db245d2010-08-18 09:41:07 +00002551 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2552 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2553 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2554 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2555 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002556 }
John McCall02db245d2010-08-18 09:41:07 +00002557 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002558
John McCall02db245d2010-08-18 09:41:07 +00002559 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2560 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
John McCall02db245d2010-08-18 09:41:07 +00002563 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2564 // Visit the type parameters from a permissive context.
2565 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2566 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2567 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2568 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2569 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2570 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002571 }
John McCall02db245d2010-08-18 09:41:07 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
John McCall02db245d2010-08-18 09:41:07 +00002574 // Visit pointee types from a permissive context.
2575#define CheckPolymorphic(Type) \
2576 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2577 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2578 }
2579 CheckPolymorphic(PointerTypeLoc)
2580 CheckPolymorphic(ReferenceTypeLoc)
2581 CheckPolymorphic(MemberPointerTypeLoc)
2582 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002583
John McCall02db245d2010-08-18 09:41:07 +00002584 /// Handle all the types we haven't given a more specific
2585 /// implementation for above.
2586 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2587 // Every other kind of type that we haven't called out already
2588 // that has an inner type is either (1) sugar or (2) contains that
2589 // inner type in some way as a subobject.
2590 if (TypeLoc Next = TL.getNextTypeLoc())
2591 return Visit(Next, Sel);
2592
2593 // If there's no inner type and we're in a permissive context,
2594 // don't diagnose.
2595 if (Sel == Sema::AbstractNone) return;
2596
2597 // Check whether the type matches the abstract type.
2598 QualType T = TL.getType();
2599 if (T->isArrayType()) {
2600 Sel = Sema::AbstractArrayType;
2601 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002602 }
John McCall02db245d2010-08-18 09:41:07 +00002603 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2604 if (CT != Info.AbstractType) return;
2605
2606 // It matched; do some magic.
2607 if (Sel == Sema::AbstractArrayType) {
2608 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2609 << T << TL.getSourceRange();
2610 } else {
2611 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2612 << Sel << T << TL.getSourceRange();
2613 }
2614 Info.DiagnoseAbstractType();
2615 }
2616};
2617
2618void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2619 Sema::AbstractDiagSelID Sel) {
2620 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2621}
2622
2623}
2624
2625/// Check for invalid uses of an abstract type in a method declaration.
2626static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2627 CXXMethodDecl *MD) {
2628 // No need to do the check on definitions, which require that
2629 // the return/param types be complete.
2630 if (MD->isThisDeclarationADefinition())
2631 return;
2632
2633 // For safety's sake, just ignore it if we don't have type source
2634 // information. This should never happen for non-implicit methods,
2635 // but...
2636 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2637 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2638}
2639
2640/// Check for invalid uses of an abstract type within a class definition.
2641static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2642 CXXRecordDecl *RD) {
2643 for (CXXRecordDecl::decl_iterator
2644 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2645 Decl *D = *I;
2646 if (D->isImplicit()) continue;
2647
2648 // Methods and method templates.
2649 if (isa<CXXMethodDecl>(D)) {
2650 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2651 } else if (isa<FunctionTemplateDecl>(D)) {
2652 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2653 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2654
2655 // Fields and static variables.
2656 } else if (isa<FieldDecl>(D)) {
2657 FieldDecl *FD = cast<FieldDecl>(D);
2658 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2659 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2660 } else if (isa<VarDecl>(D)) {
2661 VarDecl *VD = cast<VarDecl>(D);
2662 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2663 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2664
2665 // Nested classes and class templates.
2666 } else if (isa<CXXRecordDecl>(D)) {
2667 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2668 } else if (isa<ClassTemplateDecl>(D)) {
2669 CheckAbstractClassUsage(Info,
2670 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2671 }
2672 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002673}
2674
Douglas Gregorc99f1552009-12-03 18:33:45 +00002675/// \brief Perform semantic checks on a class definition that has been
2676/// completing, introducing implicitly-declared members, checking for
2677/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002678void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002679 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002680 return;
2681
John McCall02db245d2010-08-18 09:41:07 +00002682 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2683 AbstractUsageInfo Info(*this, Record);
2684 CheckAbstractClassUsage(Info, Record);
2685 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002686
2687 // If this is not an aggregate type and has no user-declared constructor,
2688 // complain about any non-static data members of reference or const scalar
2689 // type, since they will never get initializers.
2690 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2691 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2692 bool Complained = false;
2693 for (RecordDecl::field_iterator F = Record->field_begin(),
2694 FEnd = Record->field_end();
2695 F != FEnd; ++F) {
2696 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002697 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002698 if (!Complained) {
2699 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2700 << Record->getTagKind() << Record;
2701 Complained = true;
2702 }
2703
2704 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2705 << F->getType()->isReferenceType()
2706 << F->getDeclName();
2707 }
2708 }
2709 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002710
2711 if (Record->isDynamicClass())
2712 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002713
2714 if (Record->getIdentifier()) {
2715 // C++ [class.mem]p13:
2716 // If T is the name of a class, then each of the following shall have a
2717 // name different from T:
2718 // - every member of every anonymous union that is a member of class T.
2719 //
2720 // C++ [class.mem]p14:
2721 // In addition, if class T has a user-declared constructor (12.1), every
2722 // non-static data member of class T shall have a name different from T.
2723 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002724 R.first != R.second; ++R.first) {
2725 NamedDecl *D = *R.first;
2726 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2727 isa<IndirectFieldDecl>(D)) {
2728 Diag(D->getLocation(), diag::err_member_name_of_class)
2729 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002730 break;
2731 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002732 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002733 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002734}
2735
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002736void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002737 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002738 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002739 SourceLocation RBrac,
2740 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002741 if (!TagDecl)
2742 return;
Mike Stump11289f42009-09-09 15:08:12 +00002743
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002744 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002745
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002746 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002747 // strict aliasing violation!
2748 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002749 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002750
Douglas Gregor0be31a22010-07-02 17:43:08 +00002751 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002752 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002753}
2754
Douglas Gregor95755162010-07-01 05:10:53 +00002755namespace {
2756 /// \brief Helper class that collects exception specifications for
2757 /// implicitly-declared special member functions.
2758 class ImplicitExceptionSpecification {
2759 ASTContext &Context;
2760 bool AllowsAllExceptions;
2761 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2762 llvm::SmallVector<QualType, 4> Exceptions;
2763
2764 public:
2765 explicit ImplicitExceptionSpecification(ASTContext &Context)
2766 : Context(Context), AllowsAllExceptions(false) { }
2767
2768 /// \brief Whether the special member function should have any
2769 /// exception specification at all.
2770 bool hasExceptionSpecification() const {
2771 return !AllowsAllExceptions;
2772 }
2773
2774 /// \brief Whether the special member function should have a
2775 /// throw(...) exception specification (a Microsoft extension).
2776 bool hasAnyExceptionSpecification() const {
2777 return false;
2778 }
2779
2780 /// \brief The number of exceptions in the exception specification.
2781 unsigned size() const { return Exceptions.size(); }
2782
2783 /// \brief The set of exceptions in the exception specification.
2784 const QualType *data() const { return Exceptions.data(); }
2785
2786 /// \brief Note that
2787 void CalledDecl(CXXMethodDecl *Method) {
2788 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002789 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002790 return;
2791
2792 const FunctionProtoType *Proto
2793 = Method->getType()->getAs<FunctionProtoType>();
2794
2795 // If this function can throw any exceptions, make a note of that.
2796 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2797 AllowsAllExceptions = true;
2798 ExceptionsSeen.clear();
2799 Exceptions.clear();
2800 return;
2801 }
2802
2803 // Record the exceptions in this function's exception specification.
2804 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2805 EEnd = Proto->exception_end();
2806 E != EEnd; ++E)
2807 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2808 Exceptions.push_back(*E);
2809 }
2810 };
2811}
2812
2813
Douglas Gregor05379422008-11-03 17:51:48 +00002814/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2815/// special functions, such as the default constructor, copy
2816/// constructor, or destructor, to the given C++ class (C++
2817/// [special]p1). This routine can only be executed just before the
2818/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002819void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002820 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002821 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002822
Douglas Gregor54be3392010-07-01 17:57:27 +00002823 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002824 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002825
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002826 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2827 ++ASTContext::NumImplicitCopyAssignmentOperators;
2828
2829 // If we have a dynamic class, then the copy assignment operator may be
2830 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2831 // it shows up in the right place in the vtable and that we diagnose
2832 // problems with the implicit exception specification.
2833 if (ClassDecl->isDynamicClass())
2834 DeclareImplicitCopyAssignment(ClassDecl);
2835 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002836
Douglas Gregor7454c562010-07-02 20:37:36 +00002837 if (!ClassDecl->hasUserDeclaredDestructor()) {
2838 ++ASTContext::NumImplicitDestructors;
2839
2840 // If we have a dynamic class, then the destructor may be virtual, so we
2841 // have to declare the destructor immediately. This ensures that, e.g., it
2842 // shows up in the right place in the vtable and that we diagnose problems
2843 // with the implicit exception specification.
2844 if (ClassDecl->isDynamicClass())
2845 DeclareImplicitDestructor(ClassDecl);
2846 }
Douglas Gregor05379422008-11-03 17:51:48 +00002847}
2848
John McCall48871652010-08-21 09:40:31 +00002849void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002850 if (!D)
2851 return;
2852
2853 TemplateParameterList *Params = 0;
2854 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2855 Params = Template->getTemplateParameters();
2856 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2857 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2858 Params = PartialSpec->getTemplateParameters();
2859 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002860 return;
2861
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002862 for (TemplateParameterList::iterator Param = Params->begin(),
2863 ParamEnd = Params->end();
2864 Param != ParamEnd; ++Param) {
2865 NamedDecl *Named = cast<NamedDecl>(*Param);
2866 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002867 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002868 IdResolver.AddDecl(Named);
2869 }
2870 }
2871}
2872
John McCall48871652010-08-21 09:40:31 +00002873void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002874 if (!RecordD) return;
2875 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002876 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002877 PushDeclContext(S, Record);
2878}
2879
John McCall48871652010-08-21 09:40:31 +00002880void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002881 if (!RecordD) return;
2882 PopDeclContext();
2883}
2884
Douglas Gregor4d87df52008-12-16 21:30:33 +00002885/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2886/// parsing a top-level (non-nested) C++ class, and we are now
2887/// parsing those parts of the given Method declaration that could
2888/// not be parsed earlier (C++ [class.mem]p2), such as default
2889/// arguments. This action should enter the scope of the given
2890/// Method declaration as if we had just parsed the qualified method
2891/// name. However, it should not bring the parameters into scope;
2892/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002893void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002894}
2895
2896/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2897/// C++ method declaration. We're (re-)introducing the given
2898/// function parameter into scope for use in parsing later parts of
2899/// the method declaration. For example, we could see an
2900/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002901void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002902 if (!ParamD)
2903 return;
Mike Stump11289f42009-09-09 15:08:12 +00002904
John McCall48871652010-08-21 09:40:31 +00002905 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002906
2907 // If this parameter has an unparsed default argument, clear it out
2908 // to make way for the parsed default argument.
2909 if (Param->hasUnparsedDefaultArg())
2910 Param->setDefaultArg(0);
2911
John McCall48871652010-08-21 09:40:31 +00002912 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002913 if (Param->getDeclName())
2914 IdResolver.AddDecl(Param);
2915}
2916
2917/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2918/// processing the delayed method declaration for Method. The method
2919/// declaration is now considered finished. There may be a separate
2920/// ActOnStartOfFunctionDef action later (not necessarily
2921/// immediately!) for this method, if it was also defined inside the
2922/// class body.
John McCall48871652010-08-21 09:40:31 +00002923void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002924 if (!MethodD)
2925 return;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002927 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002928
John McCall48871652010-08-21 09:40:31 +00002929 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002930
2931 // Now that we have our default arguments, check the constructor
2932 // again. It could produce additional diagnostics or affect whether
2933 // the class has implicitly-declared destructors, among other
2934 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002935 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2936 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002937
2938 // Check the default arguments, which we may have added.
2939 if (!Method->isInvalidDecl())
2940 CheckCXXDefaultArguments(Method);
2941}
2942
Douglas Gregor831c93f2008-11-05 20:51:48 +00002943/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002944/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002945/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002946/// emit diagnostics and set the invalid bit to true. In any case, the type
2947/// will be updated to reflect a well-formed type for the constructor and
2948/// returned.
2949QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002950 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002951 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002952
2953 // C++ [class.ctor]p3:
2954 // A constructor shall not be virtual (10.3) or static (9.4). A
2955 // constructor can be invoked for a const, volatile or const
2956 // volatile object. A constructor shall not be declared const,
2957 // volatile, or const volatile (9.3.2).
2958 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002959 if (!D.isInvalidType())
2960 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2961 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2962 << SourceRange(D.getIdentifierLoc());
2963 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002964 }
John McCall8e7d6562010-08-26 03:08:43 +00002965 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002966 if (!D.isInvalidType())
2967 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2968 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2969 << SourceRange(D.getIdentifierLoc());
2970 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002971 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002974 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002975 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002976 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2978 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002979 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2981 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002982 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002983 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2984 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002985 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002986 }
Mike Stump11289f42009-09-09 15:08:12 +00002987
Douglas Gregor831c93f2008-11-05 20:51:48 +00002988 // Rebuild the function type "R" without any type qualifiers (in
2989 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002990 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002991 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002992 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2993 return R;
2994
2995 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2996 EPI.TypeQuals = 0;
2997
Chris Lattner38378bf2009-04-25 08:28:21 +00002998 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002999 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003000}
3001
Douglas Gregor4d87df52008-12-16 21:30:33 +00003002/// CheckConstructor - Checks a fully-formed constructor for
3003/// well-formedness, issuing any diagnostics required. Returns true if
3004/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003005void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003006 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003007 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3008 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003009 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003010
3011 // C++ [class.copy]p3:
3012 // A declaration of a constructor for a class X is ill-formed if
3013 // its first parameter is of type (optionally cv-qualified) X and
3014 // either there are no other parameters or else all other
3015 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003016 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003017 ((Constructor->getNumParams() == 1) ||
3018 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003019 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3020 Constructor->getTemplateSpecializationKind()
3021 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003022 QualType ParamType = Constructor->getParamDecl(0)->getType();
3023 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3024 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003025 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003026 const char *ConstRef
3027 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3028 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003029 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003030 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003031
3032 // FIXME: Rather that making the constructor invalid, we should endeavor
3033 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003034 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003035 }
3036 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003037}
3038
John McCalldeb646e2010-08-04 01:04:25 +00003039/// CheckDestructor - Checks a fully-formed destructor definition for
3040/// well-formedness, issuing any diagnostics required. Returns true
3041/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003042bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003043 CXXRecordDecl *RD = Destructor->getParent();
3044
3045 if (Destructor->isVirtual()) {
3046 SourceLocation Loc;
3047
3048 if (!Destructor->isImplicit())
3049 Loc = Destructor->getLocation();
3050 else
3051 Loc = RD->getLocation();
3052
3053 // If we have a virtual destructor, look up the deallocation function
3054 FunctionDecl *OperatorDelete = 0;
3055 DeclarationName Name =
3056 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003057 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003058 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003059
3060 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003061
3062 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003063 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003064
3065 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003066}
3067
Mike Stump11289f42009-09-09 15:08:12 +00003068static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003069FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3070 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3071 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003072 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003073}
3074
Douglas Gregor831c93f2008-11-05 20:51:48 +00003075/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3076/// the well-formednes of the destructor declarator @p D with type @p
3077/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003078/// emit diagnostics and set the declarator to invalid. Even if this happens,
3079/// will be updated to reflect a well-formed type for the destructor and
3080/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003081QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003082 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003083 // C++ [class.dtor]p1:
3084 // [...] A typedef-name that names a class is a class-name
3085 // (7.1.3); however, a typedef-name that names a class shall not
3086 // be used as the identifier in the declarator for a destructor
3087 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003088 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003089 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003090 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003091 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003092
3093 // C++ [class.dtor]p2:
3094 // A destructor is used to destroy objects of its class type. A
3095 // destructor takes no parameters, and no return type can be
3096 // specified for it (not even void). The address of a destructor
3097 // shall not be taken. A destructor shall not be static. A
3098 // destructor can be invoked for a const, volatile or const
3099 // volatile object. A destructor shall not be declared const,
3100 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003101 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003102 if (!D.isInvalidType())
3103 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3104 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003105 << SourceRange(D.getIdentifierLoc())
3106 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3107
John McCall8e7d6562010-08-26 03:08:43 +00003108 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003109 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003110 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003111 // Destructors don't have return types, but the parser will
3112 // happily parse something like:
3113 //
3114 // class X {
3115 // float ~X();
3116 // };
3117 //
3118 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003119 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3120 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3121 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003124 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003125 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003126 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003127 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3128 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003129 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003130 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3131 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003132 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003133 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3134 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003135 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003136 }
3137
3138 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003139 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003140 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3141
3142 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003143 FTI.freeArgs();
3144 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003145 }
3146
Mike Stump11289f42009-09-09 15:08:12 +00003147 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003148 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003149 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003150 D.setInvalidType();
3151 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003152
3153 // Rebuild the function type "R" without any type qualifiers or
3154 // parameters (in case any of the errors above fired) and with
3155 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003156 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003157 if (!D.isInvalidType())
3158 return R;
3159
Douglas Gregor95755162010-07-01 05:10:53 +00003160 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003161 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3162 EPI.Variadic = false;
3163 EPI.TypeQuals = 0;
3164 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003165}
3166
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003167/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3168/// well-formednes of the conversion function declarator @p D with
3169/// type @p R. If there are any errors in the declarator, this routine
3170/// will emit diagnostics and return true. Otherwise, it will return
3171/// false. Either way, the type @p R will be updated to reflect a
3172/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003173void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003174 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003175 // C++ [class.conv.fct]p1:
3176 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003177 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003178 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003179 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003180 if (!D.isInvalidType())
3181 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3182 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3183 << SourceRange(D.getIdentifierLoc());
3184 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003185 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003186 }
John McCall212fa2e2010-04-13 00:04:31 +00003187
3188 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3189
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003190 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003191 // Conversion functions don't have return types, but the parser will
3192 // happily parse something like:
3193 //
3194 // class X {
3195 // float operator bool();
3196 // };
3197 //
3198 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003199 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3200 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3201 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003202 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003203 }
3204
John McCall212fa2e2010-04-13 00:04:31 +00003205 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3206
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003207 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003208 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003209 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3210
3211 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003212 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003213 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003214 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003215 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003216 D.setInvalidType();
3217 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003218
John McCall212fa2e2010-04-13 00:04:31 +00003219 // Diagnose "&operator bool()" and other such nonsense. This
3220 // is actually a gcc extension which we don't support.
3221 if (Proto->getResultType() != ConvType) {
3222 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3223 << Proto->getResultType();
3224 D.setInvalidType();
3225 ConvType = Proto->getResultType();
3226 }
3227
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003228 // C++ [class.conv.fct]p4:
3229 // The conversion-type-id shall not represent a function type nor
3230 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003231 if (ConvType->isArrayType()) {
3232 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3233 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003234 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003235 } else if (ConvType->isFunctionType()) {
3236 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3237 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003238 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003239 }
3240
3241 // Rebuild the function type "R" without any parameters (in case any
3242 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003243 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003244 if (D.isInvalidType())
3245 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003246
Douglas Gregor5fb53972009-01-14 15:45:31 +00003247 // C++0x explicit conversion operators.
3248 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003249 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003250 diag::warn_explicit_conversion_functions)
3251 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003252}
3253
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003254/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3255/// the declaration of the given C++ conversion function. This routine
3256/// is responsible for recording the conversion function in the C++
3257/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003258Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003259 assert(Conversion && "Expected to receive a conversion function declaration");
3260
Douglas Gregor4287b372008-12-12 08:25:50 +00003261 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003262
3263 // Make sure we aren't redeclaring the conversion function.
3264 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003265
3266 // C++ [class.conv.fct]p1:
3267 // [...] A conversion function is never used to convert a
3268 // (possibly cv-qualified) object to the (possibly cv-qualified)
3269 // same object type (or a reference to it), to a (possibly
3270 // cv-qualified) base class of that type (or a reference to it),
3271 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003272 // FIXME: Suppress this warning if the conversion function ends up being a
3273 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003274 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003275 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003276 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003277 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003278 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3279 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003280 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003281 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003282 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3283 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003284 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003285 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003286 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003287 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003288 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003289 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003290 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003291 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003292 }
3293
Douglas Gregor457104e2010-09-29 04:25:11 +00003294 if (FunctionTemplateDecl *ConversionTemplate
3295 = Conversion->getDescribedFunctionTemplate())
3296 return ConversionTemplate;
3297
John McCall48871652010-08-21 09:40:31 +00003298 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003299}
3300
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003301//===----------------------------------------------------------------------===//
3302// Namespace Handling
3303//===----------------------------------------------------------------------===//
3304
John McCallb1be5232010-08-26 09:15:37 +00003305
3306
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003307/// ActOnStartNamespaceDef - This is called at the start of a namespace
3308/// definition.
John McCall48871652010-08-21 09:40:31 +00003309Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003310 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003311 SourceLocation IdentLoc,
3312 IdentifierInfo *II,
3313 SourceLocation LBrace,
3314 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003315 // anonymous namespace starts at its left brace
3316 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3317 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003318 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003319 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003320
3321 Scope *DeclRegionScope = NamespcScope->getParent();
3322
Anders Carlssona7bcade2010-02-07 01:09:23 +00003323 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3324
John McCall2faf32c2010-12-10 02:59:44 +00003325 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3326 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003327
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003328 if (II) {
3329 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003330 // The identifier in an original-namespace-definition shall not
3331 // have been previously defined in the declarative region in
3332 // which the original-namespace-definition appears. The
3333 // identifier in an original-namespace-definition is the name of
3334 // the namespace. Subsequently in that declarative region, it is
3335 // treated as an original-namespace-name.
3336 //
3337 // Since namespace names are unique in their scope, and we don't
3338 // look through using directives, just
3339 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3340 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003341
Douglas Gregor91f84212008-12-11 16:49:14 +00003342 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3343 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003344 if (Namespc->isInline() != OrigNS->isInline()) {
3345 // inline-ness must match
3346 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3347 << Namespc->isInline();
3348 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3349 Namespc->setInvalidDecl();
3350 // Recover by ignoring the new namespace's inline status.
3351 Namespc->setInline(OrigNS->isInline());
3352 }
3353
Douglas Gregor91f84212008-12-11 16:49:14 +00003354 // Attach this namespace decl to the chain of extended namespace
3355 // definitions.
3356 OrigNS->setNextNamespace(Namespc);
3357 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003358
Mike Stump11289f42009-09-09 15:08:12 +00003359 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003360 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003361 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003362 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003363 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003364 } else if (PrevDecl) {
3365 // This is an invalid name redefinition.
3366 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3367 << Namespc->getDeclName();
3368 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3369 Namespc->setInvalidDecl();
3370 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003371 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003372 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003373 // This is the first "real" definition of the namespace "std", so update
3374 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003375 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003376 // We had already defined a dummy namespace "std". Link this new
3377 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003378 StdNS->setNextNamespace(Namespc);
3379 StdNS->setLocation(IdentLoc);
3380 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003381 }
3382
3383 // Make our StdNamespace cache point at the first real definition of the
3384 // "std" namespace.
3385 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003386 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003387
3388 PushOnScopeChains(Namespc, DeclRegionScope);
3389 } else {
John McCall4fa53422009-10-01 00:25:31 +00003390 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003391 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003392
3393 // Link the anonymous namespace into its parent.
3394 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003395 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003396 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3397 PrevDecl = TU->getAnonymousNamespace();
3398 TU->setAnonymousNamespace(Namespc);
3399 } else {
3400 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3401 PrevDecl = ND->getAnonymousNamespace();
3402 ND->setAnonymousNamespace(Namespc);
3403 }
3404
3405 // Link the anonymous namespace with its previous declaration.
3406 if (PrevDecl) {
3407 assert(PrevDecl->isAnonymousNamespace());
3408 assert(!PrevDecl->getNextNamespace());
3409 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3410 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003411
3412 if (Namespc->isInline() != PrevDecl->isInline()) {
3413 // inline-ness must match
3414 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3415 << Namespc->isInline();
3416 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3417 Namespc->setInvalidDecl();
3418 // Recover by ignoring the new namespace's inline status.
3419 Namespc->setInline(PrevDecl->isInline());
3420 }
John McCall0db42252009-12-16 02:06:49 +00003421 }
John McCall4fa53422009-10-01 00:25:31 +00003422
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003423 CurContext->addDecl(Namespc);
3424
John McCall4fa53422009-10-01 00:25:31 +00003425 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3426 // behaves as if it were replaced by
3427 // namespace unique { /* empty body */ }
3428 // using namespace unique;
3429 // namespace unique { namespace-body }
3430 // where all occurrences of 'unique' in a translation unit are
3431 // replaced by the same identifier and this identifier differs
3432 // from all other identifiers in the entire program.
3433
3434 // We just create the namespace with an empty name and then add an
3435 // implicit using declaration, just like the standard suggests.
3436 //
3437 // CodeGen enforces the "universally unique" aspect by giving all
3438 // declarations semantically contained within an anonymous
3439 // namespace internal linkage.
3440
John McCall0db42252009-12-16 02:06:49 +00003441 if (!PrevDecl) {
3442 UsingDirectiveDecl* UD
3443 = UsingDirectiveDecl::Create(Context, CurContext,
3444 /* 'using' */ LBrace,
3445 /* 'namespace' */ SourceLocation(),
3446 /* qualifier */ SourceRange(),
3447 /* NNS */ NULL,
3448 /* identifier */ SourceLocation(),
3449 Namespc,
3450 /* Ancestor */ CurContext);
3451 UD->setImplicit();
3452 CurContext->addDecl(UD);
3453 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003454 }
3455
3456 // Although we could have an invalid decl (i.e. the namespace name is a
3457 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003458 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3459 // for the namespace has the declarations that showed up in that particular
3460 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003461 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003462 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003463}
3464
Sebastian Redla6602e92009-11-23 15:34:23 +00003465/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3466/// is a namespace alias, returns the namespace it points to.
3467static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3468 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3469 return AD->getNamespace();
3470 return dyn_cast_or_null<NamespaceDecl>(D);
3471}
3472
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003473/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3474/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003475void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003476 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3477 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3478 Namespc->setRBracLoc(RBrace);
3479 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003480 if (Namespc->hasAttr<VisibilityAttr>())
3481 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003482}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003483
John McCall28a0cf72010-08-25 07:42:41 +00003484CXXRecordDecl *Sema::getStdBadAlloc() const {
3485 return cast_or_null<CXXRecordDecl>(
3486 StdBadAlloc.get(Context.getExternalSource()));
3487}
3488
3489NamespaceDecl *Sema::getStdNamespace() const {
3490 return cast_or_null<NamespaceDecl>(
3491 StdNamespace.get(Context.getExternalSource()));
3492}
3493
Douglas Gregorcdf87022010-06-29 17:53:46 +00003494/// \brief Retrieve the special "std" namespace, which may require us to
3495/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003496NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003497 if (!StdNamespace) {
3498 // The "std" namespace has not yet been defined, so build one implicitly.
3499 StdNamespace = NamespaceDecl::Create(Context,
3500 Context.getTranslationUnitDecl(),
3501 SourceLocation(),
3502 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003503 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003504 }
3505
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003506 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003507}
3508
John McCall48871652010-08-21 09:40:31 +00003509Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003510 SourceLocation UsingLoc,
3511 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003512 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003513 SourceLocation IdentLoc,
3514 IdentifierInfo *NamespcName,
3515 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003516 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3517 assert(NamespcName && "Invalid NamespcName.");
3518 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003519
3520 // This can only happen along a recovery path.
3521 while (S->getFlags() & Scope::TemplateParamScope)
3522 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003523 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003524
Douglas Gregor889ceb72009-02-03 19:21:40 +00003525 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003526 NestedNameSpecifier *Qualifier = 0;
3527 if (SS.isSet())
3528 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3529
Douglas Gregor34074322009-01-14 22:20:51 +00003530 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003531 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3532 LookupParsedName(R, S, &SS);
3533 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003534 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003535
Douglas Gregorcdf87022010-06-29 17:53:46 +00003536 if (R.empty()) {
3537 // Allow "using namespace std;" or "using namespace ::std;" even if
3538 // "std" hasn't been defined yet, for GCC compatibility.
3539 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3540 NamespcName->isStr("std")) {
3541 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003542 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003543 R.resolveKind();
3544 }
3545 // Otherwise, attempt typo correction.
3546 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3547 CTC_NoKeywords, 0)) {
3548 if (R.getAsSingle<NamespaceDecl>() ||
3549 R.getAsSingle<NamespaceAliasDecl>()) {
3550 if (DeclContext *DC = computeDeclContext(SS, false))
3551 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3552 << NamespcName << DC << Corrected << SS.getRange()
3553 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3554 else
3555 Diag(IdentLoc, diag::err_using_directive_suggest)
3556 << NamespcName << Corrected
3557 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3558 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3559 << Corrected;
3560
3561 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003562 } else {
3563 R.clear();
3564 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003565 }
3566 }
3567 }
3568
John McCall9f3059a2009-10-09 21:13:30 +00003569 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003570 NamedDecl *Named = R.getFoundDecl();
3571 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3572 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003573 // C++ [namespace.udir]p1:
3574 // A using-directive specifies that the names in the nominated
3575 // namespace can be used in the scope in which the
3576 // using-directive appears after the using-directive. During
3577 // unqualified name lookup (3.4.1), the names appear as if they
3578 // were declared in the nearest enclosing namespace which
3579 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003580 // namespace. [Note: in this context, "contains" means "contains
3581 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003582
3583 // Find enclosing context containing both using-directive and
3584 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003585 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003586 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3587 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3588 CommonAncestor = CommonAncestor->getParent();
3589
Sebastian Redla6602e92009-11-23 15:34:23 +00003590 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003591 SS.getRange(),
3592 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003593 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003594 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003595 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003596 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003597 }
3598
Douglas Gregor889ceb72009-02-03 19:21:40 +00003599 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003600 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003601}
3602
3603void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3604 // If scope has associated entity, then using directive is at namespace
3605 // or translation unit scope. We add UsingDirectiveDecls, into
3606 // it's lookup structure.
3607 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003608 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003609 else
3610 // Otherwise it is block-sope. using-directives will affect lookup
3611 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003612 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003613}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003614
Douglas Gregorfec52632009-06-20 00:51:54 +00003615
John McCall48871652010-08-21 09:40:31 +00003616Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003617 AccessSpecifier AS,
3618 bool HasUsingKeyword,
3619 SourceLocation UsingLoc,
3620 CXXScopeSpec &SS,
3621 UnqualifiedId &Name,
3622 AttributeList *AttrList,
3623 bool IsTypeName,
3624 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003625 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003626
Douglas Gregor220f4272009-11-04 16:30:06 +00003627 switch (Name.getKind()) {
3628 case UnqualifiedId::IK_Identifier:
3629 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003630 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003631 case UnqualifiedId::IK_ConversionFunctionId:
3632 break;
3633
3634 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003635 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003636 // C++0x inherited constructors.
3637 if (getLangOptions().CPlusPlus0x) break;
3638
Douglas Gregor220f4272009-11-04 16:30:06 +00003639 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3640 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003641 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003642
3643 case UnqualifiedId::IK_DestructorName:
3644 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3645 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003646 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003647
3648 case UnqualifiedId::IK_TemplateId:
3649 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3650 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003651 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003652 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003653
3654 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3655 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003656 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003657 return 0;
John McCall3969e302009-12-08 07:46:18 +00003658
John McCalla0097262009-12-11 02:10:03 +00003659 // Warn about using declarations.
3660 // TODO: store that the declaration was written without 'using' and
3661 // talk about access decls instead of using decls in the
3662 // diagnostics.
3663 if (!HasUsingKeyword) {
3664 UsingLoc = Name.getSourceRange().getBegin();
3665
3666 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003667 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003668 }
3669
Douglas Gregorc4356532010-12-16 00:46:58 +00003670 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3671 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3672 return 0;
3673
John McCall3f746822009-11-17 05:59:44 +00003674 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003675 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003676 /* IsInstantiation */ false,
3677 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003678 if (UD)
3679 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003680
John McCall48871652010-08-21 09:40:31 +00003681 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003682}
3683
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003684/// \brief Determine whether a using declaration considers the given
3685/// declarations as "equivalent", e.g., if they are redeclarations of
3686/// the same entity or are both typedefs of the same type.
3687static bool
3688IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3689 bool &SuppressRedeclaration) {
3690 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3691 SuppressRedeclaration = false;
3692 return true;
3693 }
3694
3695 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3696 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3697 SuppressRedeclaration = true;
3698 return Context.hasSameType(TD1->getUnderlyingType(),
3699 TD2->getUnderlyingType());
3700 }
3701
3702 return false;
3703}
3704
3705
John McCall84d87672009-12-10 09:41:52 +00003706/// Determines whether to create a using shadow decl for a particular
3707/// decl, given the set of decls existing prior to this using lookup.
3708bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3709 const LookupResult &Previous) {
3710 // Diagnose finding a decl which is not from a base class of the
3711 // current class. We do this now because there are cases where this
3712 // function will silently decide not to build a shadow decl, which
3713 // will pre-empt further diagnostics.
3714 //
3715 // We don't need to do this in C++0x because we do the check once on
3716 // the qualifier.
3717 //
3718 // FIXME: diagnose the following if we care enough:
3719 // struct A { int foo; };
3720 // struct B : A { using A::foo; };
3721 // template <class T> struct C : A {};
3722 // template <class T> struct D : C<T> { using B::foo; } // <---
3723 // This is invalid (during instantiation) in C++03 because B::foo
3724 // resolves to the using decl in B, which is not a base class of D<T>.
3725 // We can't diagnose it immediately because C<T> is an unknown
3726 // specialization. The UsingShadowDecl in D<T> then points directly
3727 // to A::foo, which will look well-formed when we instantiate.
3728 // The right solution is to not collapse the shadow-decl chain.
3729 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3730 DeclContext *OrigDC = Orig->getDeclContext();
3731
3732 // Handle enums and anonymous structs.
3733 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3734 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3735 while (OrigRec->isAnonymousStructOrUnion())
3736 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3737
3738 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3739 if (OrigDC == CurContext) {
3740 Diag(Using->getLocation(),
3741 diag::err_using_decl_nested_name_specifier_is_current_class)
3742 << Using->getNestedNameRange();
3743 Diag(Orig->getLocation(), diag::note_using_decl_target);
3744 return true;
3745 }
3746
3747 Diag(Using->getNestedNameRange().getBegin(),
3748 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3749 << Using->getTargetNestedNameDecl()
3750 << cast<CXXRecordDecl>(CurContext)
3751 << Using->getNestedNameRange();
3752 Diag(Orig->getLocation(), diag::note_using_decl_target);
3753 return true;
3754 }
3755 }
3756
3757 if (Previous.empty()) return false;
3758
3759 NamedDecl *Target = Orig;
3760 if (isa<UsingShadowDecl>(Target))
3761 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3762
John McCalla17e83e2009-12-11 02:33:26 +00003763 // If the target happens to be one of the previous declarations, we
3764 // don't have a conflict.
3765 //
3766 // FIXME: but we might be increasing its access, in which case we
3767 // should redeclare it.
3768 NamedDecl *NonTag = 0, *Tag = 0;
3769 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3770 I != E; ++I) {
3771 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003772 bool Result;
3773 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3774 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003775
3776 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3777 }
3778
John McCall84d87672009-12-10 09:41:52 +00003779 if (Target->isFunctionOrFunctionTemplate()) {
3780 FunctionDecl *FD;
3781 if (isa<FunctionTemplateDecl>(Target))
3782 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3783 else
3784 FD = cast<FunctionDecl>(Target);
3785
3786 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003787 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003788 case Ovl_Overload:
3789 return false;
3790
3791 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003792 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003793 break;
3794
3795 // We found a decl with the exact signature.
3796 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003797 // If we're in a record, we want to hide the target, so we
3798 // return true (without a diagnostic) to tell the caller not to
3799 // build a shadow decl.
3800 if (CurContext->isRecord())
3801 return true;
3802
3803 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003804 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003805 break;
3806 }
3807
3808 Diag(Target->getLocation(), diag::note_using_decl_target);
3809 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3810 return true;
3811 }
3812
3813 // Target is not a function.
3814
John McCall84d87672009-12-10 09:41:52 +00003815 if (isa<TagDecl>(Target)) {
3816 // No conflict between a tag and a non-tag.
3817 if (!Tag) return false;
3818
John McCalle29c5cd2009-12-10 19:51:03 +00003819 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003820 Diag(Target->getLocation(), diag::note_using_decl_target);
3821 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3822 return true;
3823 }
3824
3825 // No conflict between a tag and a non-tag.
3826 if (!NonTag) return false;
3827
John McCalle29c5cd2009-12-10 19:51:03 +00003828 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003829 Diag(Target->getLocation(), diag::note_using_decl_target);
3830 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3831 return true;
3832}
3833
John McCall3f746822009-11-17 05:59:44 +00003834/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003835UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003836 UsingDecl *UD,
3837 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003838
3839 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003840 NamedDecl *Target = Orig;
3841 if (isa<UsingShadowDecl>(Target)) {
3842 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3843 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003844 }
3845
3846 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003847 = UsingShadowDecl::Create(Context, CurContext,
3848 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003849 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003850
3851 Shadow->setAccess(UD->getAccess());
3852 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3853 Shadow->setInvalidDecl();
3854
John McCall3f746822009-11-17 05:59:44 +00003855 if (S)
John McCall3969e302009-12-08 07:46:18 +00003856 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003857 else
John McCall3969e302009-12-08 07:46:18 +00003858 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003859
John McCall3969e302009-12-08 07:46:18 +00003860
John McCall84d87672009-12-10 09:41:52 +00003861 return Shadow;
3862}
John McCall3969e302009-12-08 07:46:18 +00003863
John McCall84d87672009-12-10 09:41:52 +00003864/// Hides a using shadow declaration. This is required by the current
3865/// using-decl implementation when a resolvable using declaration in a
3866/// class is followed by a declaration which would hide or override
3867/// one or more of the using decl's targets; for example:
3868///
3869/// struct Base { void foo(int); };
3870/// struct Derived : Base {
3871/// using Base::foo;
3872/// void foo(int);
3873/// };
3874///
3875/// The governing language is C++03 [namespace.udecl]p12:
3876///
3877/// When a using-declaration brings names from a base class into a
3878/// derived class scope, member functions in the derived class
3879/// override and/or hide member functions with the same name and
3880/// parameter types in a base class (rather than conflicting).
3881///
3882/// There are two ways to implement this:
3883/// (1) optimistically create shadow decls when they're not hidden
3884/// by existing declarations, or
3885/// (2) don't create any shadow decls (or at least don't make them
3886/// visible) until we've fully parsed/instantiated the class.
3887/// The problem with (1) is that we might have to retroactively remove
3888/// a shadow decl, which requires several O(n) operations because the
3889/// decl structures are (very reasonably) not designed for removal.
3890/// (2) avoids this but is very fiddly and phase-dependent.
3891void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003892 if (Shadow->getDeclName().getNameKind() ==
3893 DeclarationName::CXXConversionFunctionName)
3894 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3895
John McCall84d87672009-12-10 09:41:52 +00003896 // Remove it from the DeclContext...
3897 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003898
John McCall84d87672009-12-10 09:41:52 +00003899 // ...and the scope, if applicable...
3900 if (S) {
John McCall48871652010-08-21 09:40:31 +00003901 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003902 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003903 }
3904
John McCall84d87672009-12-10 09:41:52 +00003905 // ...and the using decl.
3906 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3907
3908 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003909 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003910}
3911
John McCalle61f2ba2009-11-18 02:36:19 +00003912/// Builds a using declaration.
3913///
3914/// \param IsInstantiation - Whether this call arises from an
3915/// instantiation of an unresolved using declaration. We treat
3916/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003917NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3918 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003919 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003920 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003921 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003922 bool IsInstantiation,
3923 bool IsTypeName,
3924 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003925 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003926 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003927 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003928
Anders Carlssonf038fc22009-08-28 05:49:21 +00003929 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003930
Anders Carlsson59140b32009-08-28 03:16:11 +00003931 if (SS.isEmpty()) {
3932 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003933 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003934 }
Mike Stump11289f42009-09-09 15:08:12 +00003935
John McCall84d87672009-12-10 09:41:52 +00003936 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003937 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003938 ForRedeclaration);
3939 Previous.setHideTags(false);
3940 if (S) {
3941 LookupName(Previous, S);
3942
3943 // It is really dumb that we have to do this.
3944 LookupResult::Filter F = Previous.makeFilter();
3945 while (F.hasNext()) {
3946 NamedDecl *D = F.next();
3947 if (!isDeclInScope(D, CurContext, S))
3948 F.erase();
3949 }
3950 F.done();
3951 } else {
3952 assert(IsInstantiation && "no scope in non-instantiation");
3953 assert(CurContext->isRecord() && "scope not record in instantiation");
3954 LookupQualifiedName(Previous, CurContext);
3955 }
3956
Mike Stump11289f42009-09-09 15:08:12 +00003957 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003958 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3959
John McCall84d87672009-12-10 09:41:52 +00003960 // Check for invalid redeclarations.
3961 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3962 return 0;
3963
3964 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003965 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3966 return 0;
3967
John McCall84c16cf2009-11-12 03:15:40 +00003968 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003969 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003970 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003971 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003972 // FIXME: not all declaration name kinds are legal here
3973 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3974 UsingLoc, TypenameLoc,
3975 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003976 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003977 } else {
3978 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003979 UsingLoc, SS.getRange(),
3980 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003981 }
John McCallb96ec562009-12-04 22:46:56 +00003982 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003983 D = UsingDecl::Create(Context, CurContext,
3984 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003985 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003986 }
John McCallb96ec562009-12-04 22:46:56 +00003987 D->setAccess(AS);
3988 CurContext->addDecl(D);
3989
3990 if (!LookupContext) return D;
3991 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003992
John McCall0b66eb32010-05-01 00:40:08 +00003993 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003994 UD->setInvalidDecl();
3995 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003996 }
3997
John McCall3969e302009-12-08 07:46:18 +00003998 // Look up the target name.
3999
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004000 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004001
John McCall3969e302009-12-08 07:46:18 +00004002 // Unlike most lookups, we don't always want to hide tag
4003 // declarations: tag names are visible through the using declaration
4004 // even if hidden by ordinary names, *except* in a dependent context
4005 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004006 if (!IsInstantiation)
4007 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004008
John McCall27b18f82009-11-17 02:14:36 +00004009 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004010
John McCall9f3059a2009-10-09 21:13:30 +00004011 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004012 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004013 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004014 UD->setInvalidDecl();
4015 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004016 }
4017
John McCallb96ec562009-12-04 22:46:56 +00004018 if (R.isAmbiguous()) {
4019 UD->setInvalidDecl();
4020 return UD;
4021 }
Mike Stump11289f42009-09-09 15:08:12 +00004022
John McCalle61f2ba2009-11-18 02:36:19 +00004023 if (IsTypeName) {
4024 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004025 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004026 Diag(IdentLoc, diag::err_using_typename_non_type);
4027 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4028 Diag((*I)->getUnderlyingDecl()->getLocation(),
4029 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004030 UD->setInvalidDecl();
4031 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004032 }
4033 } else {
4034 // If we asked for a non-typename and we got a type, error out,
4035 // but only if this is an instantiation of an unresolved using
4036 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004037 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004038 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4039 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004040 UD->setInvalidDecl();
4041 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004042 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004043 }
4044
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004045 // C++0x N2914 [namespace.udecl]p6:
4046 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004047 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004048 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4049 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004050 UD->setInvalidDecl();
4051 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004052 }
Mike Stump11289f42009-09-09 15:08:12 +00004053
John McCall84d87672009-12-10 09:41:52 +00004054 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4055 if (!CheckUsingShadowDecl(UD, *I, Previous))
4056 BuildUsingShadowDecl(S, UD, *I);
4057 }
John McCall3f746822009-11-17 05:59:44 +00004058
4059 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004060}
4061
John McCall84d87672009-12-10 09:41:52 +00004062/// Checks that the given using declaration is not an invalid
4063/// redeclaration. Note that this is checking only for the using decl
4064/// itself, not for any ill-formedness among the UsingShadowDecls.
4065bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4066 bool isTypeName,
4067 const CXXScopeSpec &SS,
4068 SourceLocation NameLoc,
4069 const LookupResult &Prev) {
4070 // C++03 [namespace.udecl]p8:
4071 // C++0x [namespace.udecl]p10:
4072 // A using-declaration is a declaration and can therefore be used
4073 // repeatedly where (and only where) multiple declarations are
4074 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004075 //
John McCall032092f2010-11-29 18:01:58 +00004076 // That's in non-member contexts.
4077 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004078 return false;
4079
4080 NestedNameSpecifier *Qual
4081 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4082
4083 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4084 NamedDecl *D = *I;
4085
4086 bool DTypename;
4087 NestedNameSpecifier *DQual;
4088 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4089 DTypename = UD->isTypeName();
4090 DQual = UD->getTargetNestedNameDecl();
4091 } else if (UnresolvedUsingValueDecl *UD
4092 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4093 DTypename = false;
4094 DQual = UD->getTargetNestedNameSpecifier();
4095 } else if (UnresolvedUsingTypenameDecl *UD
4096 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4097 DTypename = true;
4098 DQual = UD->getTargetNestedNameSpecifier();
4099 } else continue;
4100
4101 // using decls differ if one says 'typename' and the other doesn't.
4102 // FIXME: non-dependent using decls?
4103 if (isTypeName != DTypename) continue;
4104
4105 // using decls differ if they name different scopes (but note that
4106 // template instantiation can cause this check to trigger when it
4107 // didn't before instantiation).
4108 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4109 Context.getCanonicalNestedNameSpecifier(DQual))
4110 continue;
4111
4112 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004113 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004114 return true;
4115 }
4116
4117 return false;
4118}
4119
John McCall3969e302009-12-08 07:46:18 +00004120
John McCallb96ec562009-12-04 22:46:56 +00004121/// Checks that the given nested-name qualifier used in a using decl
4122/// in the current context is appropriately related to the current
4123/// scope. If an error is found, diagnoses it and returns true.
4124bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4125 const CXXScopeSpec &SS,
4126 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004127 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004128
John McCall3969e302009-12-08 07:46:18 +00004129 if (!CurContext->isRecord()) {
4130 // C++03 [namespace.udecl]p3:
4131 // C++0x [namespace.udecl]p8:
4132 // A using-declaration for a class member shall be a member-declaration.
4133
4134 // If we weren't able to compute a valid scope, it must be a
4135 // dependent class scope.
4136 if (!NamedContext || NamedContext->isRecord()) {
4137 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4138 << SS.getRange();
4139 return true;
4140 }
4141
4142 // Otherwise, everything is known to be fine.
4143 return false;
4144 }
4145
4146 // The current scope is a record.
4147
4148 // If the named context is dependent, we can't decide much.
4149 if (!NamedContext) {
4150 // FIXME: in C++0x, we can diagnose if we can prove that the
4151 // nested-name-specifier does not refer to a base class, which is
4152 // still possible in some cases.
4153
4154 // Otherwise we have to conservatively report that things might be
4155 // okay.
4156 return false;
4157 }
4158
4159 if (!NamedContext->isRecord()) {
4160 // Ideally this would point at the last name in the specifier,
4161 // but we don't have that level of source info.
4162 Diag(SS.getRange().getBegin(),
4163 diag::err_using_decl_nested_name_specifier_is_not_class)
4164 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4165 return true;
4166 }
4167
Douglas Gregor7c842292010-12-21 07:41:49 +00004168 if (!NamedContext->isDependentContext() &&
4169 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4170 return true;
4171
John McCall3969e302009-12-08 07:46:18 +00004172 if (getLangOptions().CPlusPlus0x) {
4173 // C++0x [namespace.udecl]p3:
4174 // In a using-declaration used as a member-declaration, the
4175 // nested-name-specifier shall name a base class of the class
4176 // being defined.
4177
4178 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4179 cast<CXXRecordDecl>(NamedContext))) {
4180 if (CurContext == NamedContext) {
4181 Diag(NameLoc,
4182 diag::err_using_decl_nested_name_specifier_is_current_class)
4183 << SS.getRange();
4184 return true;
4185 }
4186
4187 Diag(SS.getRange().getBegin(),
4188 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4189 << (NestedNameSpecifier*) SS.getScopeRep()
4190 << cast<CXXRecordDecl>(CurContext)
4191 << SS.getRange();
4192 return true;
4193 }
4194
4195 return false;
4196 }
4197
4198 // C++03 [namespace.udecl]p4:
4199 // A using-declaration used as a member-declaration shall refer
4200 // to a member of a base class of the class being defined [etc.].
4201
4202 // Salient point: SS doesn't have to name a base class as long as
4203 // lookup only finds members from base classes. Therefore we can
4204 // diagnose here only if we can prove that that can't happen,
4205 // i.e. if the class hierarchies provably don't intersect.
4206
4207 // TODO: it would be nice if "definitely valid" results were cached
4208 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4209 // need to be repeated.
4210
4211 struct UserData {
4212 llvm::DenseSet<const CXXRecordDecl*> Bases;
4213
4214 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4215 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4216 Data->Bases.insert(Base);
4217 return true;
4218 }
4219
4220 bool hasDependentBases(const CXXRecordDecl *Class) {
4221 return !Class->forallBases(collect, this);
4222 }
4223
4224 /// Returns true if the base is dependent or is one of the
4225 /// accumulated base classes.
4226 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4227 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4228 return !Data->Bases.count(Base);
4229 }
4230
4231 bool mightShareBases(const CXXRecordDecl *Class) {
4232 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4233 }
4234 };
4235
4236 UserData Data;
4237
4238 // Returns false if we find a dependent base.
4239 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4240 return false;
4241
4242 // Returns false if the class has a dependent base or if it or one
4243 // of its bases is present in the base set of the current context.
4244 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4245 return false;
4246
4247 Diag(SS.getRange().getBegin(),
4248 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4249 << (NestedNameSpecifier*) SS.getScopeRep()
4250 << cast<CXXRecordDecl>(CurContext)
4251 << SS.getRange();
4252
4253 return true;
John McCallb96ec562009-12-04 22:46:56 +00004254}
4255
John McCall48871652010-08-21 09:40:31 +00004256Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004257 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004258 SourceLocation AliasLoc,
4259 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004260 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004261 SourceLocation IdentLoc,
4262 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004263
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004264 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004265 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4266 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004267
Anders Carlssondca83c42009-03-28 06:23:46 +00004268 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004269 NamedDecl *PrevDecl
4270 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4271 ForRedeclaration);
4272 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4273 PrevDecl = 0;
4274
4275 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004276 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004277 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004278 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004279 // FIXME: At some point, we'll want to create the (redundant)
4280 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004281 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004282 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004283 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004284 }
Mike Stump11289f42009-09-09 15:08:12 +00004285
Anders Carlssondca83c42009-03-28 06:23:46 +00004286 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4287 diag::err_redefinition_different_kind;
4288 Diag(AliasLoc, DiagID) << Alias;
4289 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004290 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004291 }
4292
John McCall27b18f82009-11-17 02:14:36 +00004293 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004294 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004295
John McCall9f3059a2009-10-09 21:13:30 +00004296 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004297 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4298 CTC_NoKeywords, 0)) {
4299 if (R.getAsSingle<NamespaceDecl>() ||
4300 R.getAsSingle<NamespaceAliasDecl>()) {
4301 if (DeclContext *DC = computeDeclContext(SS, false))
4302 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4303 << Ident << DC << Corrected << SS.getRange()
4304 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4305 else
4306 Diag(IdentLoc, diag::err_using_directive_suggest)
4307 << Ident << Corrected
4308 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4309
4310 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4311 << Corrected;
4312
4313 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004314 } else {
4315 R.clear();
4316 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004317 }
4318 }
4319
4320 if (R.empty()) {
4321 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004322 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004323 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004324 }
Mike Stump11289f42009-09-09 15:08:12 +00004325
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004326 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004327 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4328 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004329 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004330 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004331
John McCalld8d0d432010-02-16 06:53:13 +00004332 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004333 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004334}
4335
Douglas Gregora57478e2010-05-01 15:04:51 +00004336namespace {
4337 /// \brief Scoped object used to handle the state changes required in Sema
4338 /// to implicitly define the body of a C++ member function;
4339 class ImplicitlyDefinedFunctionScope {
4340 Sema &S;
4341 DeclContext *PreviousContext;
4342
4343 public:
4344 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4345 : S(S), PreviousContext(S.CurContext)
4346 {
4347 S.CurContext = Method;
4348 S.PushFunctionScope();
4349 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4350 }
4351
4352 ~ImplicitlyDefinedFunctionScope() {
4353 S.PopExpressionEvaluationContext();
4354 S.PopFunctionOrBlockScope();
4355 S.CurContext = PreviousContext;
4356 }
4357 };
4358}
4359
Sebastian Redlc15c3262010-09-13 22:02:47 +00004360static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4361 CXXRecordDecl *D) {
4362 ASTContext &Context = Self.Context;
4363 QualType ClassType = Context.getTypeDeclType(D);
4364 DeclarationName ConstructorName
4365 = Context.DeclarationNames.getCXXConstructorName(
4366 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4367
4368 DeclContext::lookup_const_iterator Con, ConEnd;
4369 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4370 Con != ConEnd; ++Con) {
4371 // FIXME: In C++0x, a constructor template can be a default constructor.
4372 if (isa<FunctionTemplateDecl>(*Con))
4373 continue;
4374
4375 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4376 if (Constructor->isDefaultConstructor())
4377 return Constructor;
4378 }
4379 return 0;
4380}
4381
Douglas Gregor0be31a22010-07-02 17:43:08 +00004382CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4383 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004384 // C++ [class.ctor]p5:
4385 // A default constructor for a class X is a constructor of class X
4386 // that can be called without an argument. If there is no
4387 // user-declared constructor for class X, a default constructor is
4388 // implicitly declared. An implicitly-declared default constructor
4389 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004390 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4391 "Should not build implicit default constructor!");
4392
Douglas Gregor6d880b12010-07-01 22:31:05 +00004393 // C++ [except.spec]p14:
4394 // An implicitly declared special member function (Clause 12) shall have an
4395 // exception-specification. [...]
4396 ImplicitExceptionSpecification ExceptSpec(Context);
4397
4398 // Direct base-class destructors.
4399 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4400 BEnd = ClassDecl->bases_end();
4401 B != BEnd; ++B) {
4402 if (B->isVirtual()) // Handled below.
4403 continue;
4404
Douglas Gregor9672f922010-07-03 00:47:00 +00004405 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4406 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4407 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4408 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004409 else if (CXXConstructorDecl *Constructor
4410 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004411 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004412 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004413 }
4414
4415 // Virtual base-class destructors.
4416 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4417 BEnd = ClassDecl->vbases_end();
4418 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004419 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4420 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4421 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4422 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4423 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004424 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004425 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004426 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004427 }
4428
4429 // Field destructors.
4430 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4431 FEnd = ClassDecl->field_end();
4432 F != FEnd; ++F) {
4433 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004434 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4435 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4436 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4437 ExceptSpec.CalledDecl(
4438 DeclareImplicitDefaultConstructor(FieldClassDecl));
4439 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004440 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004441 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004442 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004443 }
John McCalldb40c7f2010-12-14 08:05:40 +00004444
4445 FunctionProtoType::ExtProtoInfo EPI;
4446 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4447 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4448 EPI.NumExceptions = ExceptSpec.size();
4449 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004450
4451 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004452 CanQualType ClassType
4453 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4454 DeclarationName Name
4455 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004456 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004457 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004458 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004459 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004460 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004461 /*TInfo=*/0,
4462 /*isExplicit=*/false,
4463 /*isInline=*/true,
4464 /*isImplicitlyDeclared=*/true);
4465 DefaultCon->setAccess(AS_public);
4466 DefaultCon->setImplicit();
4467 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004468
4469 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004470 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4471
Douglas Gregor0be31a22010-07-02 17:43:08 +00004472 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004473 PushOnScopeChains(DefaultCon, S, false);
4474 ClassDecl->addDecl(DefaultCon);
4475
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004476 return DefaultCon;
4477}
4478
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004479void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4480 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004481 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004482 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004483 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004484
Anders Carlsson423f5d82010-04-23 16:04:08 +00004485 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004486 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004487
Douglas Gregora57478e2010-05-01 15:04:51 +00004488 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004489 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004490 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004491 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004492 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004493 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004494 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004495 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004496 }
Douglas Gregor73193272010-09-20 16:48:21 +00004497
4498 SourceLocation Loc = Constructor->getLocation();
4499 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4500
4501 Constructor->setUsed();
4502 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004503}
4504
Douglas Gregor0be31a22010-07-02 17:43:08 +00004505CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004506 // C++ [class.dtor]p2:
4507 // If a class has no user-declared destructor, a destructor is
4508 // declared implicitly. An implicitly-declared destructor is an
4509 // inline public member of its class.
4510
4511 // C++ [except.spec]p14:
4512 // An implicitly declared special member function (Clause 12) shall have
4513 // an exception-specification.
4514 ImplicitExceptionSpecification ExceptSpec(Context);
4515
4516 // Direct base-class destructors.
4517 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4518 BEnd = ClassDecl->bases_end();
4519 B != BEnd; ++B) {
4520 if (B->isVirtual()) // Handled below.
4521 continue;
4522
4523 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4524 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004525 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004526 }
4527
4528 // Virtual base-class destructors.
4529 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4530 BEnd = ClassDecl->vbases_end();
4531 B != BEnd; ++B) {
4532 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4533 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004534 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004535 }
4536
4537 // Field destructors.
4538 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4539 FEnd = ClassDecl->field_end();
4540 F != FEnd; ++F) {
4541 if (const RecordType *RecordTy
4542 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4543 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004544 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004545 }
4546
Douglas Gregor7454c562010-07-02 20:37:36 +00004547 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004548 FunctionProtoType::ExtProtoInfo EPI;
4549 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4550 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4551 EPI.NumExceptions = ExceptSpec.size();
4552 EPI.Exceptions = ExceptSpec.data();
4553 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004554
4555 CanQualType ClassType
4556 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4557 DeclarationName Name
4558 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004559 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004560 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004561 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004562 /*isInline=*/true,
4563 /*isImplicitlyDeclared=*/true);
4564 Destructor->setAccess(AS_public);
4565 Destructor->setImplicit();
4566 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004567
4568 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004569 ++ASTContext::NumImplicitDestructorsDeclared;
4570
4571 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004572 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004573 PushOnScopeChains(Destructor, S, false);
4574 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004575
4576 // This could be uniqued if it ever proves significant.
4577 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4578
4579 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004580
Douglas Gregorf1203042010-07-01 19:09:28 +00004581 return Destructor;
4582}
4583
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004584void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004585 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004586 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004587 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004588 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004589 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004590
Douglas Gregor54818f02010-05-12 16:39:35 +00004591 if (Destructor->isInvalidDecl())
4592 return;
4593
Douglas Gregora57478e2010-05-01 15:04:51 +00004594 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004595
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004596 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004597 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4598 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004599
Douglas Gregor54818f02010-05-12 16:39:35 +00004600 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004601 Diag(CurrentLocation, diag::note_member_synthesized_at)
4602 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4603
4604 Destructor->setInvalidDecl();
4605 return;
4606 }
4607
Douglas Gregor73193272010-09-20 16:48:21 +00004608 SourceLocation Loc = Destructor->getLocation();
4609 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4610
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004611 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004612 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004613}
4614
Douglas Gregorb139cd52010-05-01 20:49:11 +00004615/// \brief Builds a statement that copies the given entity from \p From to
4616/// \c To.
4617///
4618/// This routine is used to copy the members of a class with an
4619/// implicitly-declared copy assignment operator. When the entities being
4620/// copied are arrays, this routine builds for loops to copy them.
4621///
4622/// \param S The Sema object used for type-checking.
4623///
4624/// \param Loc The location where the implicit copy is being generated.
4625///
4626/// \param T The type of the expressions being copied. Both expressions must
4627/// have this type.
4628///
4629/// \param To The expression we are copying to.
4630///
4631/// \param From The expression we are copying from.
4632///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004633/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4634/// Otherwise, it's a non-static member subobject.
4635///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004636/// \param Depth Internal parameter recording the depth of the recursion.
4637///
4638/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004639static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004640BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004641 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004642 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004643 // C++0x [class.copy]p30:
4644 // Each subobject is assigned in the manner appropriate to its type:
4645 //
4646 // - if the subobject is of class type, the copy assignment operator
4647 // for the class is used (as if by explicit qualification; that is,
4648 // ignoring any possible virtual overriding functions in more derived
4649 // classes);
4650 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4651 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4652
4653 // Look for operator=.
4654 DeclarationName Name
4655 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4656 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4657 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4658
4659 // Filter out any result that isn't a copy-assignment operator.
4660 LookupResult::Filter F = OpLookup.makeFilter();
4661 while (F.hasNext()) {
4662 NamedDecl *D = F.next();
4663 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4664 if (Method->isCopyAssignmentOperator())
4665 continue;
4666
4667 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004668 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004669 F.done();
4670
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004671 // Suppress the protected check (C++ [class.protected]) for each of the
4672 // assignment operators we found. This strange dance is required when
4673 // we're assigning via a base classes's copy-assignment operator. To
4674 // ensure that we're getting the right base class subobject (without
4675 // ambiguities), we need to cast "this" to that subobject type; to
4676 // ensure that we don't go through the virtual call mechanism, we need
4677 // to qualify the operator= name with the base class (see below). However,
4678 // this means that if the base class has a protected copy assignment
4679 // operator, the protected member access check will fail. So, we
4680 // rewrite "protected" access to "public" access in this case, since we
4681 // know by construction that we're calling from a derived class.
4682 if (CopyingBaseSubobject) {
4683 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4684 L != LEnd; ++L) {
4685 if (L.getAccess() == AS_protected)
4686 L.setAccess(AS_public);
4687 }
4688 }
4689
Douglas Gregorb139cd52010-05-01 20:49:11 +00004690 // Create the nested-name-specifier that will be used to qualify the
4691 // reference to operator=; this is required to suppress the virtual
4692 // call mechanism.
4693 CXXScopeSpec SS;
4694 SS.setRange(Loc);
4695 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4696 T.getTypePtr()));
4697
4698 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004699 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004700 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004701 /*FirstQualifierInScope=*/0, OpLookup,
4702 /*TemplateArgs=*/0,
4703 /*SuppressQualifierCheck=*/true);
4704 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004705 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004706
4707 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004708
John McCalldadc5752010-08-24 06:29:42 +00004709 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004710 OpEqualRef.takeAs<Expr>(),
4711 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004712 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004713 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004714
4715 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004716 }
John McCallab8c2732010-03-16 06:11:48 +00004717
Douglas Gregorb139cd52010-05-01 20:49:11 +00004718 // - if the subobject is of scalar type, the built-in assignment
4719 // operator is used.
4720 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4721 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004722 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004723 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004724 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004725
4726 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004727 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004728
4729 // - if the subobject is an array, each element is assigned, in the
4730 // manner appropriate to the element type;
4731
4732 // Construct a loop over the array bounds, e.g.,
4733 //
4734 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4735 //
4736 // that will copy each of the array elements.
4737 QualType SizeType = S.Context.getSizeType();
4738
4739 // Create the iteration variable.
4740 IdentifierInfo *IterationVarName = 0;
4741 {
4742 llvm::SmallString<8> Str;
4743 llvm::raw_svector_ostream OS(Str);
4744 OS << "__i" << Depth;
4745 IterationVarName = &S.Context.Idents.get(OS.str());
4746 }
4747 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4748 IterationVarName, SizeType,
4749 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004750 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004751
4752 // Initialize the iteration variable to zero.
4753 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004754 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004755
4756 // Create a reference to the iteration variable; we'll use this several
4757 // times throughout.
4758 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004759 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004760 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4761
4762 // Create the DeclStmt that holds the iteration variable.
4763 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4764
4765 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004766 llvm::APInt Upper
4767 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004768 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004769 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004770 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4771 BO_NE, S.Context.BoolTy,
4772 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004773
4774 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004775 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004776 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4777 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004778
4779 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004780 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4781 IterationVarRef, Loc));
4782 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4783 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004784
4785 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004786 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4787 To, From, CopyingBaseSubobject,
4788 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004789 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004790 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004791
4792 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004793 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004794 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004795 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004796 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004797}
4798
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004799/// \brief Determine whether the given class has a copy assignment operator
4800/// that accepts a const-qualified argument.
4801static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4802 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4803
4804 if (!Class->hasDeclaredCopyAssignment())
4805 S.DeclareImplicitCopyAssignment(Class);
4806
4807 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4808 DeclarationName OpName
4809 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4810
4811 DeclContext::lookup_const_iterator Op, OpEnd;
4812 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4813 // C++ [class.copy]p9:
4814 // A user-declared copy assignment operator is a non-static non-template
4815 // member function of class X with exactly one parameter of type X, X&,
4816 // const X&, volatile X& or const volatile X&.
4817 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4818 if (!Method)
4819 continue;
4820
4821 if (Method->isStatic())
4822 continue;
4823 if (Method->getPrimaryTemplate())
4824 continue;
4825 const FunctionProtoType *FnType =
4826 Method->getType()->getAs<FunctionProtoType>();
4827 assert(FnType && "Overloaded operator has no prototype.");
4828 // Don't assert on this; an invalid decl might have been left in the AST.
4829 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4830 continue;
4831 bool AcceptsConst = true;
4832 QualType ArgType = FnType->getArgType(0);
4833 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4834 ArgType = Ref->getPointeeType();
4835 // Is it a non-const lvalue reference?
4836 if (!ArgType.isConstQualified())
4837 AcceptsConst = false;
4838 }
4839 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4840 continue;
4841
4842 // We have a single argument of type cv X or cv X&, i.e. we've found the
4843 // copy assignment operator. Return whether it accepts const arguments.
4844 return AcceptsConst;
4845 }
4846 assert(Class->isInvalidDecl() &&
4847 "No copy assignment operator declared in valid code.");
4848 return false;
4849}
4850
Douglas Gregor0be31a22010-07-02 17:43:08 +00004851CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004852 // Note: The following rules are largely analoguous to the copy
4853 // constructor rules. Note that virtual bases are not taken into account
4854 // for determining the argument type of the operator. Note also that
4855 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004856
4857
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004858 // C++ [class.copy]p10:
4859 // If the class definition does not explicitly declare a copy
4860 // assignment operator, one is declared implicitly.
4861 // The implicitly-defined copy assignment operator for a class X
4862 // will have the form
4863 //
4864 // X& X::operator=(const X&)
4865 //
4866 // if
4867 bool HasConstCopyAssignment = true;
4868
4869 // -- each direct base class B of X has a copy assignment operator
4870 // whose parameter is of type const B&, const volatile B& or B,
4871 // and
4872 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4873 BaseEnd = ClassDecl->bases_end();
4874 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4875 assert(!Base->getType()->isDependentType() &&
4876 "Cannot generate implicit members for class with dependent bases.");
4877 const CXXRecordDecl *BaseClassDecl
4878 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004879 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004880 }
4881
4882 // -- for all the nonstatic data members of X that are of a class
4883 // type M (or array thereof), each such class type has a copy
4884 // assignment operator whose parameter is of type const M&,
4885 // const volatile M& or M.
4886 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4887 FieldEnd = ClassDecl->field_end();
4888 HasConstCopyAssignment && Field != FieldEnd;
4889 ++Field) {
4890 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4891 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4892 const CXXRecordDecl *FieldClassDecl
4893 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004894 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004895 }
4896 }
4897
4898 // Otherwise, the implicitly declared copy assignment operator will
4899 // have the form
4900 //
4901 // X& X::operator=(X&)
4902 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4903 QualType RetType = Context.getLValueReferenceType(ArgType);
4904 if (HasConstCopyAssignment)
4905 ArgType = ArgType.withConst();
4906 ArgType = Context.getLValueReferenceType(ArgType);
4907
Douglas Gregor68e11362010-07-01 17:48:08 +00004908 // C++ [except.spec]p14:
4909 // An implicitly declared special member function (Clause 12) shall have an
4910 // exception-specification. [...]
4911 ImplicitExceptionSpecification ExceptSpec(Context);
4912 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4913 BaseEnd = ClassDecl->bases_end();
4914 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004915 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004916 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004917
4918 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4919 DeclareImplicitCopyAssignment(BaseClassDecl);
4920
Douglas Gregor68e11362010-07-01 17:48:08 +00004921 if (CXXMethodDecl *CopyAssign
4922 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4923 ExceptSpec.CalledDecl(CopyAssign);
4924 }
4925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4926 FieldEnd = ClassDecl->field_end();
4927 Field != FieldEnd;
4928 ++Field) {
4929 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4930 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004931 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004932 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004933
4934 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4935 DeclareImplicitCopyAssignment(FieldClassDecl);
4936
Douglas Gregor68e11362010-07-01 17:48:08 +00004937 if (CXXMethodDecl *CopyAssign
4938 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4939 ExceptSpec.CalledDecl(CopyAssign);
4940 }
4941 }
4942
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004943 // An implicitly-declared copy assignment operator is an inline public
4944 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004945 FunctionProtoType::ExtProtoInfo EPI;
4946 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4947 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4948 EPI.NumExceptions = ExceptSpec.size();
4949 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004950 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004951 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004952 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004953 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004954 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004955 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004956 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004957 /*isInline=*/true);
4958 CopyAssignment->setAccess(AS_public);
4959 CopyAssignment->setImplicit();
4960 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004961
4962 // Add the parameter to the operator.
4963 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4964 ClassDecl->getLocation(),
4965 /*Id=*/0,
4966 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004967 SC_None,
4968 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004969 CopyAssignment->setParams(&FromParam, 1);
4970
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004971 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004972 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4973
Douglas Gregor0be31a22010-07-02 17:43:08 +00004974 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004975 PushOnScopeChains(CopyAssignment, S, false);
4976 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004977
4978 AddOverriddenMethods(ClassDecl, CopyAssignment);
4979 return CopyAssignment;
4980}
4981
Douglas Gregorb139cd52010-05-01 20:49:11 +00004982void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4983 CXXMethodDecl *CopyAssignOperator) {
4984 assert((CopyAssignOperator->isImplicit() &&
4985 CopyAssignOperator->isOverloadedOperator() &&
4986 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004987 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004988 "DefineImplicitCopyAssignment called for wrong function");
4989
4990 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4991
4992 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4993 CopyAssignOperator->setInvalidDecl();
4994 return;
4995 }
4996
4997 CopyAssignOperator->setUsed();
4998
4999 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005000 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005001
5002 // C++0x [class.copy]p30:
5003 // The implicitly-defined or explicitly-defaulted copy assignment operator
5004 // for a non-union class X performs memberwise copy assignment of its
5005 // subobjects. The direct base classes of X are assigned first, in the
5006 // order of their declaration in the base-specifier-list, and then the
5007 // immediate non-static data members of X are assigned, in the order in
5008 // which they were declared in the class definition.
5009
5010 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005011 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005012
5013 // The parameter for the "other" object, which we are copying from.
5014 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5015 Qualifiers OtherQuals = Other->getType().getQualifiers();
5016 QualType OtherRefType = Other->getType();
5017 if (const LValueReferenceType *OtherRef
5018 = OtherRefType->getAs<LValueReferenceType>()) {
5019 OtherRefType = OtherRef->getPointeeType();
5020 OtherQuals = OtherRefType.getQualifiers();
5021 }
5022
5023 // Our location for everything implicitly-generated.
5024 SourceLocation Loc = CopyAssignOperator->getLocation();
5025
5026 // Construct a reference to the "other" object. We'll be using this
5027 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005028 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005029 assert(OtherRef && "Reference to parameter cannot fail!");
5030
5031 // Construct the "this" pointer. We'll be using this throughout the generated
5032 // ASTs.
5033 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5034 assert(This && "Reference to this cannot fail!");
5035
5036 // Assign base classes.
5037 bool Invalid = false;
5038 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5039 E = ClassDecl->bases_end(); Base != E; ++Base) {
5040 // Form the assignment:
5041 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5042 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005043 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005044 Invalid = true;
5045 continue;
5046 }
5047
John McCallcf142162010-08-07 06:22:56 +00005048 CXXCastPath BasePath;
5049 BasePath.push_back(Base);
5050
Douglas Gregorb139cd52010-05-01 20:49:11 +00005051 // Construct the "from" expression, which is an implicit cast to the
5052 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005053 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005054 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005055 CK_UncheckedDerivedToBase,
5056 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005057
5058 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005059 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005060
5061 // Implicitly cast "this" to the appropriately-qualified base type.
5062 Expr *ToE = To.takeAs<Expr>();
5063 ImpCastExprToType(ToE,
5064 Context.getCVRQualifiedType(BaseType,
5065 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005066 CK_UncheckedDerivedToBase,
5067 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005068 To = Owned(ToE);
5069
5070 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005071 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005072 To.get(), From,
5073 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005074 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005075 Diag(CurrentLocation, diag::note_member_synthesized_at)
5076 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5077 CopyAssignOperator->setInvalidDecl();
5078 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005079 }
5080
5081 // Success! Record the copy.
5082 Statements.push_back(Copy.takeAs<Expr>());
5083 }
5084
5085 // \brief Reference to the __builtin_memcpy function.
5086 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005087 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005088 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005089
5090 // Assign non-static members.
5091 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5092 FieldEnd = ClassDecl->field_end();
5093 Field != FieldEnd; ++Field) {
5094 // Check for members of reference type; we can't copy those.
5095 if (Field->getType()->isReferenceType()) {
5096 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5097 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5098 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005099 Diag(CurrentLocation, diag::note_member_synthesized_at)
5100 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005101 Invalid = true;
5102 continue;
5103 }
5104
5105 // Check for members of const-qualified, non-class type.
5106 QualType BaseType = Context.getBaseElementType(Field->getType());
5107 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5108 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5109 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5110 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005111 Diag(CurrentLocation, diag::note_member_synthesized_at)
5112 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005113 Invalid = true;
5114 continue;
5115 }
5116
5117 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005118 if (FieldType->isIncompleteArrayType()) {
5119 assert(ClassDecl->hasFlexibleArrayMember() &&
5120 "Incomplete array type is not valid");
5121 continue;
5122 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005123
5124 // Build references to the field in the object we're copying from and to.
5125 CXXScopeSpec SS; // Intentionally empty
5126 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5127 LookupMemberName);
5128 MemberLookup.addDecl(*Field);
5129 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005130 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005131 Loc, /*IsArrow=*/false,
5132 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005133 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005134 Loc, /*IsArrow=*/true,
5135 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005136 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5137 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5138
5139 // If the field should be copied with __builtin_memcpy rather than via
5140 // explicit assignments, do so. This optimization only applies for arrays
5141 // of scalars and arrays of class type with trivial copy-assignment
5142 // operators.
5143 if (FieldType->isArrayType() &&
5144 (!BaseType->isRecordType() ||
5145 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5146 ->hasTrivialCopyAssignment())) {
5147 // Compute the size of the memory buffer to be copied.
5148 QualType SizeType = Context.getSizeType();
5149 llvm::APInt Size(Context.getTypeSize(SizeType),
5150 Context.getTypeSizeInChars(BaseType).getQuantity());
5151 for (const ConstantArrayType *Array
5152 = Context.getAsConstantArrayType(FieldType);
5153 Array;
5154 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005155 llvm::APInt ArraySize
5156 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005157 Size *= ArraySize;
5158 }
5159
5160 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005161 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5162 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005163
5164 bool NeedsCollectableMemCpy =
5165 (BaseType->isRecordType() &&
5166 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5167
5168 if (NeedsCollectableMemCpy) {
5169 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005170 // Create a reference to the __builtin_objc_memmove_collectable function.
5171 LookupResult R(*this,
5172 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005173 Loc, LookupOrdinaryName);
5174 LookupName(R, TUScope, true);
5175
5176 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5177 if (!CollectableMemCpy) {
5178 // Something went horribly wrong earlier, and we will have
5179 // complained about it.
5180 Invalid = true;
5181 continue;
5182 }
5183
5184 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5185 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005186 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005187 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5188 }
5189 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005190 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005191 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005192 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5193 LookupOrdinaryName);
5194 LookupName(R, TUScope, true);
5195
5196 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5197 if (!BuiltinMemCpy) {
5198 // Something went horribly wrong earlier, and we will have complained
5199 // about it.
5200 Invalid = true;
5201 continue;
5202 }
5203
5204 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5205 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005206 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005207 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5208 }
5209
John McCall37ad5512010-08-23 06:44:23 +00005210 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005211 CallArgs.push_back(To.takeAs<Expr>());
5212 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005213 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005214 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005215 if (NeedsCollectableMemCpy)
5216 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005217 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005218 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005219 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005220 else
5221 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005222 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005223 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005224 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005225
Douglas Gregorb139cd52010-05-01 20:49:11 +00005226 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5227 Statements.push_back(Call.takeAs<Expr>());
5228 continue;
5229 }
5230
5231 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005232 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005233 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005234 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005235 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005236 Diag(CurrentLocation, diag::note_member_synthesized_at)
5237 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5238 CopyAssignOperator->setInvalidDecl();
5239 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005240 }
5241
5242 // Success! Record the copy.
5243 Statements.push_back(Copy.takeAs<Stmt>());
5244 }
5245
5246 if (!Invalid) {
5247 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005248 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005249
John McCalldadc5752010-08-24 06:29:42 +00005250 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005251 if (Return.isInvalid())
5252 Invalid = true;
5253 else {
5254 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005255
5256 if (Trap.hasErrorOccurred()) {
5257 Diag(CurrentLocation, diag::note_member_synthesized_at)
5258 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5259 Invalid = true;
5260 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005261 }
5262 }
5263
5264 if (Invalid) {
5265 CopyAssignOperator->setInvalidDecl();
5266 return;
5267 }
5268
John McCalldadc5752010-08-24 06:29:42 +00005269 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005270 /*isStmtExpr=*/false);
5271 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5272 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005273}
5274
Douglas Gregor0be31a22010-07-02 17:43:08 +00005275CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5276 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005277 // C++ [class.copy]p4:
5278 // If the class definition does not explicitly declare a copy
5279 // constructor, one is declared implicitly.
5280
Douglas Gregor54be3392010-07-01 17:57:27 +00005281 // C++ [class.copy]p5:
5282 // The implicitly-declared copy constructor for a class X will
5283 // have the form
5284 //
5285 // X::X(const X&)
5286 //
5287 // if
5288 bool HasConstCopyConstructor = true;
5289
5290 // -- each direct or virtual base class B of X has a copy
5291 // constructor whose first parameter is of type const B& or
5292 // const volatile B&, and
5293 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5294 BaseEnd = ClassDecl->bases_end();
5295 HasConstCopyConstructor && Base != BaseEnd;
5296 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005297 // Virtual bases are handled below.
5298 if (Base->isVirtual())
5299 continue;
5300
Douglas Gregora6d69502010-07-02 23:41:54 +00005301 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005302 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005303 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5304 DeclareImplicitCopyConstructor(BaseClassDecl);
5305
Douglas Gregorcfe68222010-07-01 18:27:03 +00005306 HasConstCopyConstructor
5307 = BaseClassDecl->hasConstCopyConstructor(Context);
5308 }
5309
5310 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5311 BaseEnd = ClassDecl->vbases_end();
5312 HasConstCopyConstructor && Base != BaseEnd;
5313 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005314 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005315 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005316 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5317 DeclareImplicitCopyConstructor(BaseClassDecl);
5318
Douglas Gregor54be3392010-07-01 17:57:27 +00005319 HasConstCopyConstructor
5320 = BaseClassDecl->hasConstCopyConstructor(Context);
5321 }
5322
5323 // -- for all the nonstatic data members of X that are of a
5324 // class type M (or array thereof), each such class type
5325 // has a copy constructor whose first parameter is of type
5326 // const M& or const volatile M&.
5327 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5328 FieldEnd = ClassDecl->field_end();
5329 HasConstCopyConstructor && Field != FieldEnd;
5330 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005331 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005332 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005333 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005334 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005335 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5336 DeclareImplicitCopyConstructor(FieldClassDecl);
5337
Douglas Gregor54be3392010-07-01 17:57:27 +00005338 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005339 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005340 }
5341 }
5342
5343 // Otherwise, the implicitly declared copy constructor will have
5344 // the form
5345 //
5346 // X::X(X&)
5347 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5348 QualType ArgType = ClassType;
5349 if (HasConstCopyConstructor)
5350 ArgType = ArgType.withConst();
5351 ArgType = Context.getLValueReferenceType(ArgType);
5352
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005353 // C++ [except.spec]p14:
5354 // An implicitly declared special member function (Clause 12) shall have an
5355 // exception-specification. [...]
5356 ImplicitExceptionSpecification ExceptSpec(Context);
5357 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5358 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5359 BaseEnd = ClassDecl->bases_end();
5360 Base != BaseEnd;
5361 ++Base) {
5362 // Virtual bases are handled below.
5363 if (Base->isVirtual())
5364 continue;
5365
Douglas Gregora6d69502010-07-02 23:41:54 +00005366 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005367 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005368 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5369 DeclareImplicitCopyConstructor(BaseClassDecl);
5370
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005371 if (CXXConstructorDecl *CopyConstructor
5372 = BaseClassDecl->getCopyConstructor(Context, Quals))
5373 ExceptSpec.CalledDecl(CopyConstructor);
5374 }
5375 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5376 BaseEnd = ClassDecl->vbases_end();
5377 Base != BaseEnd;
5378 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005379 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005380 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005381 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5382 DeclareImplicitCopyConstructor(BaseClassDecl);
5383
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005384 if (CXXConstructorDecl *CopyConstructor
5385 = BaseClassDecl->getCopyConstructor(Context, Quals))
5386 ExceptSpec.CalledDecl(CopyConstructor);
5387 }
5388 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5389 FieldEnd = ClassDecl->field_end();
5390 Field != FieldEnd;
5391 ++Field) {
5392 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5393 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005394 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005395 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005396 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5397 DeclareImplicitCopyConstructor(FieldClassDecl);
5398
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005399 if (CXXConstructorDecl *CopyConstructor
5400 = FieldClassDecl->getCopyConstructor(Context, Quals))
5401 ExceptSpec.CalledDecl(CopyConstructor);
5402 }
5403 }
5404
Douglas Gregor54be3392010-07-01 17:57:27 +00005405 // An implicitly-declared copy constructor is an inline public
5406 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005407 FunctionProtoType::ExtProtoInfo EPI;
5408 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5409 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5410 EPI.NumExceptions = ExceptSpec.size();
5411 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005412 DeclarationName Name
5413 = Context.DeclarationNames.getCXXConstructorName(
5414 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005415 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005416 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005417 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005418 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005419 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005420 /*TInfo=*/0,
5421 /*isExplicit=*/false,
5422 /*isInline=*/true,
5423 /*isImplicitlyDeclared=*/true);
5424 CopyConstructor->setAccess(AS_public);
5425 CopyConstructor->setImplicit();
5426 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5427
Douglas Gregora6d69502010-07-02 23:41:54 +00005428 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005429 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5430
Douglas Gregor54be3392010-07-01 17:57:27 +00005431 // Add the parameter to the constructor.
5432 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5433 ClassDecl->getLocation(),
5434 /*IdentifierInfo=*/0,
5435 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005436 SC_None,
5437 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005438 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005439 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005440 PushOnScopeChains(CopyConstructor, S, false);
5441 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005442
5443 return CopyConstructor;
5444}
5445
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005446void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5447 CXXConstructorDecl *CopyConstructor,
5448 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005449 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005450 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005451 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005452 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005453
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005454 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005455 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005456
Douglas Gregora57478e2010-05-01 15:04:51 +00005457 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005458 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005459
Alexis Hunt1d792652011-01-08 20:30:50 +00005460 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005461 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005462 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005463 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005464 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005465 } else {
5466 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5467 CopyConstructor->getLocation(),
5468 MultiStmtArg(*this, 0, 0),
5469 /*isStmtExpr=*/false)
5470 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005471 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005472
5473 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005474}
5475
John McCalldadc5752010-08-24 06:29:42 +00005476ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005477Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005478 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005479 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005480 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005481 unsigned ConstructKind,
5482 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005483 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005484
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005485 // C++0x [class.copy]p34:
5486 // When certain criteria are met, an implementation is allowed to
5487 // omit the copy/move construction of a class object, even if the
5488 // copy/move constructor and/or destructor for the object have
5489 // side effects. [...]
5490 // - when a temporary class object that has not been bound to a
5491 // reference (12.2) would be copied/moved to a class object
5492 // with the same cv-unqualified type, the copy/move operation
5493 // can be omitted by constructing the temporary object
5494 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005495 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5496 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005497 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005498 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005499 }
Mike Stump11289f42009-09-09 15:08:12 +00005500
5501 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005502 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005503 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005504}
5505
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005506/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5507/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005508ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005509Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5510 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005511 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005512 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005513 unsigned ConstructKind,
5514 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005515 unsigned NumExprs = ExprArgs.size();
5516 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005517
Douglas Gregor27381f32009-11-23 12:27:39 +00005518 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005519 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005520 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005521 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005522 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5523 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005524}
5525
Mike Stump11289f42009-09-09 15:08:12 +00005526bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005527 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005528 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005529 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005530 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005531 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005532 move(Exprs), false, CXXConstructExpr::CK_Complete,
5533 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005534 if (TempResult.isInvalid())
5535 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005536
Anders Carlsson6eb55572009-08-25 05:12:04 +00005537 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005538 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005539 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005540 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005541 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005542
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005543 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005544}
5545
John McCall03c48482010-02-02 09:10:11 +00005546void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5547 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005548 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005549 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005550 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005551 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005552 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005553 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005554 << VD->getDeclName()
5555 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005556
John McCall386dfc72010-09-18 05:25:11 +00005557 // TODO: this should be re-enabled for static locals by !CXAAtExit
5558 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005559 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005560 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005561}
5562
Mike Stump11289f42009-09-09 15:08:12 +00005563/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005564/// ActOnDeclarator, when a C++ direct initializer is present.
5565/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005566void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005567 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005568 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005569 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005570 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005571
5572 // If there is no declaration, there was an error parsing it. Just ignore
5573 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005574 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005575 return;
Mike Stump11289f42009-09-09 15:08:12 +00005576
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005577 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5578 if (!VDecl) {
5579 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5580 RealDecl->setInvalidDecl();
5581 return;
5582 }
5583
Douglas Gregor402250f2009-08-26 21:14:46 +00005584 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005585 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005586 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5587 //
5588 // Clients that want to distinguish between the two forms, can check for
5589 // direct initializer using VarDecl::hasCXXDirectInitializer().
5590 // A major benefit is that clients that don't particularly care about which
5591 // exactly form was it (like the CodeGen) can handle both cases without
5592 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005593
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005594 // C++ 8.5p11:
5595 // The form of initialization (using parentheses or '=') is generally
5596 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005597 // class type.
5598
Douglas Gregor50dc2192010-02-11 22:55:30 +00005599 if (!VDecl->getType()->isDependentType() &&
5600 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005601 diag::err_typecheck_decl_incomplete_type)) {
5602 VDecl->setInvalidDecl();
5603 return;
5604 }
5605
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005606 // The variable can not have an abstract class type.
5607 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5608 diag::err_abstract_type_in_decl,
5609 AbstractVariableType))
5610 VDecl->setInvalidDecl();
5611
Sebastian Redl5ca79842010-02-01 20:16:42 +00005612 const VarDecl *Def;
5613 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005614 Diag(VDecl->getLocation(), diag::err_redefinition)
5615 << VDecl->getDeclName();
5616 Diag(Def->getLocation(), diag::note_previous_definition);
5617 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005618 return;
5619 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005620
Douglas Gregorf0f83692010-08-24 05:27:49 +00005621 // C++ [class.static.data]p4
5622 // If a static data member is of const integral or const
5623 // enumeration type, its declaration in the class definition can
5624 // specify a constant-initializer which shall be an integral
5625 // constant expression (5.19). In that case, the member can appear
5626 // in integral constant expressions. The member shall still be
5627 // defined in a namespace scope if it is used in the program and the
5628 // namespace scope definition shall not contain an initializer.
5629 //
5630 // We already performed a redefinition check above, but for static
5631 // data members we also need to check whether there was an in-class
5632 // declaration with an initializer.
5633 const VarDecl* PrevInit = 0;
5634 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5635 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5636 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5637 return;
5638 }
5639
Douglas Gregor71f39c92010-12-16 01:31:22 +00005640 bool IsDependent = false;
5641 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5642 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5643 VDecl->setInvalidDecl();
5644 return;
5645 }
5646
5647 if (Exprs.get()[I]->isTypeDependent())
5648 IsDependent = true;
5649 }
5650
Douglas Gregor50dc2192010-02-11 22:55:30 +00005651 // If either the declaration has a dependent type or if any of the
5652 // expressions is type-dependent, we represent the initialization
5653 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005654 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005655 // Let clients know that initialization was done with a direct initializer.
5656 VDecl->setCXXDirectInitializer(true);
5657
5658 // Store the initialization expressions as a ParenListExpr.
5659 unsigned NumExprs = Exprs.size();
5660 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5661 (Expr **)Exprs.release(),
5662 NumExprs, RParenLoc));
5663 return;
5664 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005665
5666 // Capture the variable that is being initialized and the style of
5667 // initialization.
5668 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5669
5670 // FIXME: Poor source location information.
5671 InitializationKind Kind
5672 = InitializationKind::CreateDirect(VDecl->getLocation(),
5673 LParenLoc, RParenLoc);
5674
5675 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005676 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005677 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005678 if (Result.isInvalid()) {
5679 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005680 return;
5681 }
John McCallacf0ee52010-10-08 02:01:28 +00005682
5683 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005684
Douglas Gregora40433a2010-12-07 00:41:46 +00005685 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005686 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005687 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005688
John McCall8b7fd8f12011-01-19 11:48:09 +00005689 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005690}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005691
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005692/// \brief Given a constructor and the set of arguments provided for the
5693/// constructor, convert the arguments and add any required default arguments
5694/// to form a proper call to this constructor.
5695///
5696/// \returns true if an error occurred, false otherwise.
5697bool
5698Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5699 MultiExprArg ArgsPtr,
5700 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005701 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005702 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5703 unsigned NumArgs = ArgsPtr.size();
5704 Expr **Args = (Expr **)ArgsPtr.get();
5705
5706 const FunctionProtoType *Proto
5707 = Constructor->getType()->getAs<FunctionProtoType>();
5708 assert(Proto && "Constructor without a prototype?");
5709 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005710
5711 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005712 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005713 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005714 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005715 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005716
5717 VariadicCallType CallType =
5718 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5719 llvm::SmallVector<Expr *, 8> AllArgs;
5720 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5721 Proto, 0, Args, NumArgs, AllArgs,
5722 CallType);
5723 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5724 ConvertedArgs.push_back(AllArgs[i]);
5725 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005726}
5727
Anders Carlssone363c8e2009-12-12 00:32:00 +00005728static inline bool
5729CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5730 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005731 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005732 if (isa<NamespaceDecl>(DC)) {
5733 return SemaRef.Diag(FnDecl->getLocation(),
5734 diag::err_operator_new_delete_declared_in_namespace)
5735 << FnDecl->getDeclName();
5736 }
5737
5738 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005739 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005740 return SemaRef.Diag(FnDecl->getLocation(),
5741 diag::err_operator_new_delete_declared_static)
5742 << FnDecl->getDeclName();
5743 }
5744
Anders Carlsson60659a82009-12-12 02:43:16 +00005745 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005746}
5747
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005748static inline bool
5749CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5750 CanQualType ExpectedResultType,
5751 CanQualType ExpectedFirstParamType,
5752 unsigned DependentParamTypeDiag,
5753 unsigned InvalidParamTypeDiag) {
5754 QualType ResultType =
5755 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5756
5757 // Check that the result type is not dependent.
5758 if (ResultType->isDependentType())
5759 return SemaRef.Diag(FnDecl->getLocation(),
5760 diag::err_operator_new_delete_dependent_result_type)
5761 << FnDecl->getDeclName() << ExpectedResultType;
5762
5763 // Check that the result type is what we expect.
5764 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5765 return SemaRef.Diag(FnDecl->getLocation(),
5766 diag::err_operator_new_delete_invalid_result_type)
5767 << FnDecl->getDeclName() << ExpectedResultType;
5768
5769 // A function template must have at least 2 parameters.
5770 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5771 return SemaRef.Diag(FnDecl->getLocation(),
5772 diag::err_operator_new_delete_template_too_few_parameters)
5773 << FnDecl->getDeclName();
5774
5775 // The function decl must have at least 1 parameter.
5776 if (FnDecl->getNumParams() == 0)
5777 return SemaRef.Diag(FnDecl->getLocation(),
5778 diag::err_operator_new_delete_too_few_parameters)
5779 << FnDecl->getDeclName();
5780
5781 // Check the the first parameter type is not dependent.
5782 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5783 if (FirstParamType->isDependentType())
5784 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5785 << FnDecl->getDeclName() << ExpectedFirstParamType;
5786
5787 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005788 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005789 ExpectedFirstParamType)
5790 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5791 << FnDecl->getDeclName() << ExpectedFirstParamType;
5792
5793 return false;
5794}
5795
Anders Carlsson12308f42009-12-11 23:23:22 +00005796static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005797CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005798 // C++ [basic.stc.dynamic.allocation]p1:
5799 // A program is ill-formed if an allocation function is declared in a
5800 // namespace scope other than global scope or declared static in global
5801 // scope.
5802 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5803 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005804
5805 CanQualType SizeTy =
5806 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5807
5808 // C++ [basic.stc.dynamic.allocation]p1:
5809 // The return type shall be void*. The first parameter shall have type
5810 // std::size_t.
5811 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5812 SizeTy,
5813 diag::err_operator_new_dependent_param_type,
5814 diag::err_operator_new_param_type))
5815 return true;
5816
5817 // C++ [basic.stc.dynamic.allocation]p1:
5818 // The first parameter shall not have an associated default argument.
5819 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005820 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005821 diag::err_operator_new_default_arg)
5822 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5823
5824 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005825}
5826
5827static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005828CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5829 // C++ [basic.stc.dynamic.deallocation]p1:
5830 // A program is ill-formed if deallocation functions are declared in a
5831 // namespace scope other than global scope or declared static in global
5832 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005833 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5834 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005835
5836 // C++ [basic.stc.dynamic.deallocation]p2:
5837 // Each deallocation function shall return void and its first parameter
5838 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005839 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5840 SemaRef.Context.VoidPtrTy,
5841 diag::err_operator_delete_dependent_param_type,
5842 diag::err_operator_delete_param_type))
5843 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005844
Anders Carlsson12308f42009-12-11 23:23:22 +00005845 return false;
5846}
5847
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005848/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5849/// of this overloaded operator is well-formed. If so, returns false;
5850/// otherwise, emits appropriate diagnostics and returns true.
5851bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005852 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005853 "Expected an overloaded operator declaration");
5854
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005855 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5856
Mike Stump11289f42009-09-09 15:08:12 +00005857 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005858 // The allocation and deallocation functions, operator new,
5859 // operator new[], operator delete and operator delete[], are
5860 // described completely in 3.7.3. The attributes and restrictions
5861 // found in the rest of this subclause do not apply to them unless
5862 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005863 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005864 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005865
Anders Carlsson22f443f2009-12-12 00:26:23 +00005866 if (Op == OO_New || Op == OO_Array_New)
5867 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005868
5869 // C++ [over.oper]p6:
5870 // An operator function shall either be a non-static member
5871 // function or be a non-member function and have at least one
5872 // parameter whose type is a class, a reference to a class, an
5873 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005874 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5875 if (MethodDecl->isStatic())
5876 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005877 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005878 } else {
5879 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005880 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5881 ParamEnd = FnDecl->param_end();
5882 Param != ParamEnd; ++Param) {
5883 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005884 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5885 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005886 ClassOrEnumParam = true;
5887 break;
5888 }
5889 }
5890
Douglas Gregord69246b2008-11-17 16:14:12 +00005891 if (!ClassOrEnumParam)
5892 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005893 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005894 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005895 }
5896
5897 // C++ [over.oper]p8:
5898 // An operator function cannot have default arguments (8.3.6),
5899 // except where explicitly stated below.
5900 //
Mike Stump11289f42009-09-09 15:08:12 +00005901 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005902 // (C++ [over.call]p1).
5903 if (Op != OO_Call) {
5904 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5905 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005906 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005907 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005908 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005909 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005910 }
5911 }
5912
Douglas Gregor6cf08062008-11-10 13:38:07 +00005913 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5914 { false, false, false }
5915#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5916 , { Unary, Binary, MemberOnly }
5917#include "clang/Basic/OperatorKinds.def"
5918 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005919
Douglas Gregor6cf08062008-11-10 13:38:07 +00005920 bool CanBeUnaryOperator = OperatorUses[Op][0];
5921 bool CanBeBinaryOperator = OperatorUses[Op][1];
5922 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005923
5924 // C++ [over.oper]p8:
5925 // [...] Operator functions cannot have more or fewer parameters
5926 // than the number required for the corresponding operator, as
5927 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005928 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005929 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005930 if (Op != OO_Call &&
5931 ((NumParams == 1 && !CanBeUnaryOperator) ||
5932 (NumParams == 2 && !CanBeBinaryOperator) ||
5933 (NumParams < 1) || (NumParams > 2))) {
5934 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005935 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005936 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005937 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005938 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005939 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005940 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005941 assert(CanBeBinaryOperator &&
5942 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005943 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005944 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005945
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005946 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005947 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005948 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005949
Douglas Gregord69246b2008-11-17 16:14:12 +00005950 // Overloaded operators other than operator() cannot be variadic.
5951 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005952 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005953 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005954 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005955 }
5956
5957 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005958 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5959 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005960 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005961 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005962 }
5963
5964 // C++ [over.inc]p1:
5965 // The user-defined function called operator++ implements the
5966 // prefix and postfix ++ operator. If this function is a member
5967 // function with no parameters, or a non-member function with one
5968 // parameter of class or enumeration type, it defines the prefix
5969 // increment operator ++ for objects of that type. If the function
5970 // is a member function with one parameter (which shall be of type
5971 // int) or a non-member function with two parameters (the second
5972 // of which shall be of type int), it defines the postfix
5973 // increment operator ++ for objects of that type.
5974 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5975 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5976 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005977 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005978 ParamIsInt = BT->getKind() == BuiltinType::Int;
5979
Chris Lattner2b786902008-11-21 07:50:02 +00005980 if (!ParamIsInt)
5981 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005982 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005983 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005984 }
5985
Douglas Gregord69246b2008-11-17 16:14:12 +00005986 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005987}
Chris Lattner3b024a32008-12-17 07:09:26 +00005988
Alexis Huntc88db062010-01-13 09:01:02 +00005989/// CheckLiteralOperatorDeclaration - Check whether the declaration
5990/// of this literal operator function is well-formed. If so, returns
5991/// false; otherwise, emits appropriate diagnostics and returns true.
5992bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5993 DeclContext *DC = FnDecl->getDeclContext();
5994 Decl::Kind Kind = DC->getDeclKind();
5995 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5996 Kind != Decl::LinkageSpec) {
5997 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5998 << FnDecl->getDeclName();
5999 return true;
6000 }
6001
6002 bool Valid = false;
6003
Alexis Hunt7dd26172010-04-07 23:11:06 +00006004 // template <char...> type operator "" name() is the only valid template
6005 // signature, and the only valid signature with no parameters.
6006 if (FnDecl->param_size() == 0) {
6007 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6008 // Must have only one template parameter
6009 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6010 if (Params->size() == 1) {
6011 NonTypeTemplateParmDecl *PmDecl =
6012 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006013
Alexis Hunt7dd26172010-04-07 23:11:06 +00006014 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006015 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6016 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6017 Valid = true;
6018 }
6019 }
6020 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006021 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006022 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6023
Alexis Huntc88db062010-01-13 09:01:02 +00006024 QualType T = (*Param)->getType();
6025
Alexis Hunt079a6f72010-04-07 22:57:35 +00006026 // unsigned long long int, long double, and any character type are allowed
6027 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006028 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6029 Context.hasSameType(T, Context.LongDoubleTy) ||
6030 Context.hasSameType(T, Context.CharTy) ||
6031 Context.hasSameType(T, Context.WCharTy) ||
6032 Context.hasSameType(T, Context.Char16Ty) ||
6033 Context.hasSameType(T, Context.Char32Ty)) {
6034 if (++Param == FnDecl->param_end())
6035 Valid = true;
6036 goto FinishedParams;
6037 }
6038
Alexis Hunt079a6f72010-04-07 22:57:35 +00006039 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006040 const PointerType *PT = T->getAs<PointerType>();
6041 if (!PT)
6042 goto FinishedParams;
6043 T = PT->getPointeeType();
6044 if (!T.isConstQualified())
6045 goto FinishedParams;
6046 T = T.getUnqualifiedType();
6047
6048 // Move on to the second parameter;
6049 ++Param;
6050
6051 // If there is no second parameter, the first must be a const char *
6052 if (Param == FnDecl->param_end()) {
6053 if (Context.hasSameType(T, Context.CharTy))
6054 Valid = true;
6055 goto FinishedParams;
6056 }
6057
6058 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6059 // are allowed as the first parameter to a two-parameter function
6060 if (!(Context.hasSameType(T, Context.CharTy) ||
6061 Context.hasSameType(T, Context.WCharTy) ||
6062 Context.hasSameType(T, Context.Char16Ty) ||
6063 Context.hasSameType(T, Context.Char32Ty)))
6064 goto FinishedParams;
6065
6066 // The second and final parameter must be an std::size_t
6067 T = (*Param)->getType().getUnqualifiedType();
6068 if (Context.hasSameType(T, Context.getSizeType()) &&
6069 ++Param == FnDecl->param_end())
6070 Valid = true;
6071 }
6072
6073 // FIXME: This diagnostic is absolutely terrible.
6074FinishedParams:
6075 if (!Valid) {
6076 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6077 << FnDecl->getDeclName();
6078 return true;
6079 }
6080
6081 return false;
6082}
6083
Douglas Gregor07665a62009-01-05 19:45:36 +00006084/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6085/// linkage specification, including the language and (if present)
6086/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6087/// the location of the language string literal, which is provided
6088/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6089/// the '{' brace. Otherwise, this linkage specification does not
6090/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006091Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6092 SourceLocation LangLoc,
6093 llvm::StringRef Lang,
6094 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006095 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006096 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006097 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006098 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006099 Language = LinkageSpecDecl::lang_cxx;
6100 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006101 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006102 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006103 }
Mike Stump11289f42009-09-09 15:08:12 +00006104
Chris Lattner438e5012008-12-17 07:13:27 +00006105 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006106
Douglas Gregor07665a62009-01-05 19:45:36 +00006107 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006108 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006109 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006110 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006111 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006112 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006113}
6114
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006115/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006116/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6117/// valid, it's the position of the closing '}' brace in a linkage
6118/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006119Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6120 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006121 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006122 if (LinkageSpec)
6123 PopDeclContext();
6124 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006125}
6126
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006127/// \brief Perform semantic analysis for the variable declaration that
6128/// occurs within a C++ catch clause, returning the newly-created
6129/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006130VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006131 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006132 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006133 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006134 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006135 QualType ExDeclType = TInfo->getType();
6136
Sebastian Redl54c04d42008-12-22 19:15:10 +00006137 // Arrays and functions decay.
6138 if (ExDeclType->isArrayType())
6139 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6140 else if (ExDeclType->isFunctionType())
6141 ExDeclType = Context.getPointerType(ExDeclType);
6142
6143 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6144 // The exception-declaration shall not denote a pointer or reference to an
6145 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006146 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006147 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006148 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006149 Invalid = true;
6150 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006151
Douglas Gregor104ee002010-03-08 01:47:36 +00006152 // GCC allows catching pointers and references to incomplete types
6153 // as an extension; so do we, but we warn by default.
6154
Sebastian Redl54c04d42008-12-22 19:15:10 +00006155 QualType BaseType = ExDeclType;
6156 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006157 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006158 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006159 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006160 BaseType = Ptr->getPointeeType();
6161 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006162 DK = diag::ext_catch_incomplete_ptr;
6163 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006164 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006165 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006166 BaseType = Ref->getPointeeType();
6167 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006168 DK = diag::ext_catch_incomplete_ref;
6169 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006170 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006171 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006172 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6173 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006174 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006175
Mike Stump11289f42009-09-09 15:08:12 +00006176 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006177 RequireNonAbstractType(Loc, ExDeclType,
6178 diag::err_abstract_type_in_decl,
6179 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006180 Invalid = true;
6181
John McCall2ca705e2010-07-24 00:37:23 +00006182 // Only the non-fragile NeXT runtime currently supports C++ catches
6183 // of ObjC types, and no runtime supports catching ObjC types by value.
6184 if (!Invalid && getLangOptions().ObjC1) {
6185 QualType T = ExDeclType;
6186 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6187 T = RT->getPointeeType();
6188
6189 if (T->isObjCObjectType()) {
6190 Diag(Loc, diag::err_objc_object_catch);
6191 Invalid = true;
6192 } else if (T->isObjCObjectPointerType()) {
6193 if (!getLangOptions().NeXTRuntime) {
6194 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6195 Invalid = true;
6196 } else if (!getLangOptions().ObjCNonFragileABI) {
6197 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6198 Invalid = true;
6199 }
6200 }
6201 }
6202
Mike Stump11289f42009-09-09 15:08:12 +00006203 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006204 Name, ExDeclType, TInfo, SC_None,
6205 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006206 ExDecl->setExceptionVariable(true);
6207
Douglas Gregor6de584c2010-03-05 23:38:39 +00006208 if (!Invalid) {
6209 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6210 // C++ [except.handle]p16:
6211 // The object declared in an exception-declaration or, if the
6212 // exception-declaration does not specify a name, a temporary (12.2) is
6213 // copy-initialized (8.5) from the exception object. [...]
6214 // The object is destroyed when the handler exits, after the destruction
6215 // of any automatic objects initialized within the handler.
6216 //
6217 // We just pretend to initialize the object with itself, then make sure
6218 // it can be destroyed later.
6219 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6220 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006221 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006222 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6223 SourceLocation());
6224 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006225 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006226 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006227 if (Result.isInvalid())
6228 Invalid = true;
6229 else
6230 FinalizeVarWithDestructor(ExDecl, RecordTy);
6231 }
6232 }
6233
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006234 if (Invalid)
6235 ExDecl->setInvalidDecl();
6236
6237 return ExDecl;
6238}
6239
6240/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6241/// handler.
John McCall48871652010-08-21 09:40:31 +00006242Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006243 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006244 bool Invalid = D.isInvalidType();
6245
6246 // Check for unexpanded parameter packs.
6247 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6248 UPPC_ExceptionType)) {
6249 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6250 D.getIdentifierLoc());
6251 Invalid = true;
6252 }
6253
Sebastian Redl54c04d42008-12-22 19:15:10 +00006254 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006255 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006256 LookupOrdinaryName,
6257 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006258 // The scope should be freshly made just for us. There is just no way
6259 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006260 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006261 if (PrevDecl->isTemplateParameter()) {
6262 // Maybe we will complain about the shadowed template parameter.
6263 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006264 }
6265 }
6266
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006267 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006268 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6269 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006270 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006271 }
6272
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006273 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006274 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006275 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006276
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006277 if (Invalid)
6278 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006279
Sebastian Redl54c04d42008-12-22 19:15:10 +00006280 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006281 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006282 PushOnScopeChains(ExDecl, S);
6283 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006284 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006285
Douglas Gregor758a8692009-06-17 21:51:59 +00006286 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006287 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006288}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006289
John McCall48871652010-08-21 09:40:31 +00006290Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006291 Expr *AssertExpr,
6292 Expr *AssertMessageExpr_) {
6293 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006294
Anders Carlsson54b26982009-03-14 00:33:21 +00006295 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6296 llvm::APSInt Value(32);
6297 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6298 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6299 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006300 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006301 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006302
Anders Carlsson54b26982009-03-14 00:33:21 +00006303 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006304 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006305 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006306 }
6307 }
Mike Stump11289f42009-09-09 15:08:12 +00006308
Douglas Gregoref68fee2010-12-15 23:55:21 +00006309 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6310 return 0;
6311
Mike Stump11289f42009-09-09 15:08:12 +00006312 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006313 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006314
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006315 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006316 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006317}
Sebastian Redlf769df52009-03-24 22:27:57 +00006318
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006319/// \brief Perform semantic analysis of the given friend type declaration.
6320///
6321/// \returns A friend declaration that.
6322FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6323 TypeSourceInfo *TSInfo) {
6324 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6325
6326 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006327 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006328
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006329 if (!getLangOptions().CPlusPlus0x) {
6330 // C++03 [class.friend]p2:
6331 // An elaborated-type-specifier shall be used in a friend declaration
6332 // for a class.*
6333 //
6334 // * The class-key of the elaborated-type-specifier is required.
6335 if (!ActiveTemplateInstantiations.empty()) {
6336 // Do not complain about the form of friend template types during
6337 // template instantiation; we will already have complained when the
6338 // template was declared.
6339 } else if (!T->isElaboratedTypeSpecifier()) {
6340 // If we evaluated the type to a record type, suggest putting
6341 // a tag in front.
6342 if (const RecordType *RT = T->getAs<RecordType>()) {
6343 RecordDecl *RD = RT->getDecl();
6344
6345 std::string InsertionText = std::string(" ") + RD->getKindName();
6346
6347 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6348 << (unsigned) RD->getTagKind()
6349 << T
6350 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6351 InsertionText);
6352 } else {
6353 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6354 << T
6355 << SourceRange(FriendLoc, TypeRange.getEnd());
6356 }
6357 } else if (T->getAs<EnumType>()) {
6358 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006359 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006360 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006361 }
6362 }
6363
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006364 // C++0x [class.friend]p3:
6365 // If the type specifier in a friend declaration designates a (possibly
6366 // cv-qualified) class type, that class is declared as a friend; otherwise,
6367 // the friend declaration is ignored.
6368
6369 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6370 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006371
6372 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6373}
6374
John McCallace48cd2010-10-19 01:40:49 +00006375/// Handle a friend tag declaration where the scope specifier was
6376/// templated.
6377Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6378 unsigned TagSpec, SourceLocation TagLoc,
6379 CXXScopeSpec &SS,
6380 IdentifierInfo *Name, SourceLocation NameLoc,
6381 AttributeList *Attr,
6382 MultiTemplateParamsArg TempParamLists) {
6383 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6384
6385 bool isExplicitSpecialization = false;
6386 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6387 bool Invalid = false;
6388
6389 if (TemplateParameterList *TemplateParams
6390 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6391 TempParamLists.get(),
6392 TempParamLists.size(),
6393 /*friend*/ true,
6394 isExplicitSpecialization,
6395 Invalid)) {
6396 --NumMatchedTemplateParamLists;
6397
6398 if (TemplateParams->size() > 0) {
6399 // This is a declaration of a class template.
6400 if (Invalid)
6401 return 0;
6402
6403 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6404 SS, Name, NameLoc, Attr,
6405 TemplateParams, AS_public).take();
6406 } else {
6407 // The "template<>" header is extraneous.
6408 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6409 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6410 isExplicitSpecialization = true;
6411 }
6412 }
6413
6414 if (Invalid) return 0;
6415
6416 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6417
6418 bool isAllExplicitSpecializations = true;
6419 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6420 if (TempParamLists.get()[I]->size()) {
6421 isAllExplicitSpecializations = false;
6422 break;
6423 }
6424 }
6425
6426 // FIXME: don't ignore attributes.
6427
6428 // If it's explicit specializations all the way down, just forget
6429 // about the template header and build an appropriate non-templated
6430 // friend. TODO: for source fidelity, remember the headers.
6431 if (isAllExplicitSpecializations) {
6432 ElaboratedTypeKeyword Keyword
6433 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6434 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6435 TagLoc, SS.getRange(), NameLoc);
6436 if (T.isNull())
6437 return 0;
6438
6439 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6440 if (isa<DependentNameType>(T)) {
6441 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6442 TL.setKeywordLoc(TagLoc);
6443 TL.setQualifierRange(SS.getRange());
6444 TL.setNameLoc(NameLoc);
6445 } else {
6446 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6447 TL.setKeywordLoc(TagLoc);
6448 TL.setQualifierRange(SS.getRange());
6449 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6450 }
6451
6452 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6453 TSI, FriendLoc);
6454 Friend->setAccess(AS_public);
6455 CurContext->addDecl(Friend);
6456 return Friend;
6457 }
6458
6459 // Handle the case of a templated-scope friend class. e.g.
6460 // template <class T> class A<T>::B;
6461 // FIXME: we don't support these right now.
6462 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6463 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6464 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6465 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6466 TL.setKeywordLoc(TagLoc);
6467 TL.setQualifierRange(SS.getRange());
6468 TL.setNameLoc(NameLoc);
6469
6470 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6471 TSI, FriendLoc);
6472 Friend->setAccess(AS_public);
6473 Friend->setUnsupportedFriend(true);
6474 CurContext->addDecl(Friend);
6475 return Friend;
6476}
6477
6478
John McCall11083da2009-09-16 22:47:08 +00006479/// Handle a friend type declaration. This works in tandem with
6480/// ActOnTag.
6481///
6482/// Notes on friend class templates:
6483///
6484/// We generally treat friend class declarations as if they were
6485/// declaring a class. So, for example, the elaborated type specifier
6486/// in a friend declaration is required to obey the restrictions of a
6487/// class-head (i.e. no typedefs in the scope chain), template
6488/// parameters are required to match up with simple template-ids, &c.
6489/// However, unlike when declaring a template specialization, it's
6490/// okay to refer to a template specialization without an empty
6491/// template parameter declaration, e.g.
6492/// friend class A<T>::B<unsigned>;
6493/// We permit this as a special case; if there are any template
6494/// parameters present at all, require proper matching, i.e.
6495/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006496Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006497 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006498 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006499
6500 assert(DS.isFriendSpecified());
6501 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6502
John McCall11083da2009-09-16 22:47:08 +00006503 // Try to convert the decl specifier to a type. This works for
6504 // friend templates because ActOnTag never produces a ClassTemplateDecl
6505 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006506 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006507 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6508 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006509 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006510 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006511
Douglas Gregor6c110f32010-12-16 01:14:37 +00006512 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6513 return 0;
6514
John McCall11083da2009-09-16 22:47:08 +00006515 // This is definitely an error in C++98. It's probably meant to
6516 // be forbidden in C++0x, too, but the specification is just
6517 // poorly written.
6518 //
6519 // The problem is with declarations like the following:
6520 // template <T> friend A<T>::foo;
6521 // where deciding whether a class C is a friend or not now hinges
6522 // on whether there exists an instantiation of A that causes
6523 // 'foo' to equal C. There are restrictions on class-heads
6524 // (which we declare (by fiat) elaborated friend declarations to
6525 // be) that makes this tractable.
6526 //
6527 // FIXME: handle "template <> friend class A<T>;", which
6528 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006529 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006530 Diag(Loc, diag::err_tagless_friend_type_template)
6531 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006532 return 0;
John McCall11083da2009-09-16 22:47:08 +00006533 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006534
John McCallaa74a0c2009-08-28 07:59:38 +00006535 // C++98 [class.friend]p1: A friend of a class is a function
6536 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006537 // This is fixed in DR77, which just barely didn't make the C++03
6538 // deadline. It's also a very silly restriction that seriously
6539 // affects inner classes and which nobody else seems to implement;
6540 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006541 //
6542 // But note that we could warn about it: it's always useless to
6543 // friend one of your own members (it's not, however, worthless to
6544 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006545
John McCall11083da2009-09-16 22:47:08 +00006546 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006547 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006548 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006549 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006550 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006551 TSI,
John McCall11083da2009-09-16 22:47:08 +00006552 DS.getFriendSpecLoc());
6553 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006554 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6555
6556 if (!D)
John McCall48871652010-08-21 09:40:31 +00006557 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006558
John McCall11083da2009-09-16 22:47:08 +00006559 D->setAccess(AS_public);
6560 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006561
John McCall48871652010-08-21 09:40:31 +00006562 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006563}
6564
John McCallde3fd222010-10-12 23:13:28 +00006565Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6566 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006567 const DeclSpec &DS = D.getDeclSpec();
6568
6569 assert(DS.isFriendSpecified());
6570 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6571
6572 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006573 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6574 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006575
6576 // C++ [class.friend]p1
6577 // A friend of a class is a function or class....
6578 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006579 // It *doesn't* see through dependent types, which is correct
6580 // according to [temp.arg.type]p3:
6581 // If a declaration acquires a function type through a
6582 // type dependent on a template-parameter and this causes
6583 // a declaration that does not use the syntactic form of a
6584 // function declarator to have a function type, the program
6585 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006586 if (!T->isFunctionType()) {
6587 Diag(Loc, diag::err_unexpected_friend);
6588
6589 // It might be worthwhile to try to recover by creating an
6590 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006591 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006592 }
6593
6594 // C++ [namespace.memdef]p3
6595 // - If a friend declaration in a non-local class first declares a
6596 // class or function, the friend class or function is a member
6597 // of the innermost enclosing namespace.
6598 // - The name of the friend is not found by simple name lookup
6599 // until a matching declaration is provided in that namespace
6600 // scope (either before or after the class declaration granting
6601 // friendship).
6602 // - If a friend function is called, its name may be found by the
6603 // name lookup that considers functions from namespaces and
6604 // classes associated with the types of the function arguments.
6605 // - When looking for a prior declaration of a class or a function
6606 // declared as a friend, scopes outside the innermost enclosing
6607 // namespace scope are not considered.
6608
John McCallde3fd222010-10-12 23:13:28 +00006609 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006610 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6611 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006612 assert(Name);
6613
Douglas Gregor6c110f32010-12-16 01:14:37 +00006614 // Check for unexpanded parameter packs.
6615 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6616 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6617 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6618 return 0;
6619
John McCall07e91c02009-08-06 02:15:43 +00006620 // The context we found the declaration in, or in which we should
6621 // create the declaration.
6622 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006623 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006624 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006625 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006626
John McCallde3fd222010-10-12 23:13:28 +00006627 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006628
John McCallde3fd222010-10-12 23:13:28 +00006629 // There are four cases here.
6630 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006631 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006632 // there as appropriate.
6633 // Recover from invalid scope qualifiers as if they just weren't there.
6634 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006635 // C++0x [namespace.memdef]p3:
6636 // If the name in a friend declaration is neither qualified nor
6637 // a template-id and the declaration is a function or an
6638 // elaborated-type-specifier, the lookup to determine whether
6639 // the entity has been previously declared shall not consider
6640 // any scopes outside the innermost enclosing namespace.
6641 // C++0x [class.friend]p11:
6642 // If a friend declaration appears in a local class and the name
6643 // specified is an unqualified name, a prior declaration is
6644 // looked up without considering scopes that are outside the
6645 // innermost enclosing non-class scope. For a friend function
6646 // declaration, if there is no prior declaration, the program is
6647 // ill-formed.
6648 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006649 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006650
John McCallf7cfb222010-10-13 05:45:15 +00006651 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006652 DC = CurContext;
6653 while (true) {
6654 // Skip class contexts. If someone can cite chapter and verse
6655 // for this behavior, that would be nice --- it's what GCC and
6656 // EDG do, and it seems like a reasonable intent, but the spec
6657 // really only says that checks for unqualified existing
6658 // declarations should stop at the nearest enclosing namespace,
6659 // not that they should only consider the nearest enclosing
6660 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006661 while (DC->isRecord())
6662 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006663
John McCall1f82f242009-11-18 22:49:29 +00006664 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006665
6666 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006667 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006668 break;
John McCallf7cfb222010-10-13 05:45:15 +00006669
John McCallf4776592010-10-14 22:22:28 +00006670 if (isTemplateId) {
6671 if (isa<TranslationUnitDecl>(DC)) break;
6672 } else {
6673 if (DC->isFileContext()) break;
6674 }
John McCall07e91c02009-08-06 02:15:43 +00006675 DC = DC->getParent();
6676 }
6677
6678 // C++ [class.friend]p1: A friend of a class is a function or
6679 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006680 // C++0x changes this for both friend types and functions.
6681 // Most C++ 98 compilers do seem to give an error here, so
6682 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006683 if (!Previous.empty() && DC->Equals(CurContext)
6684 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006685 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006686
John McCallccbc0322010-10-13 06:22:15 +00006687 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006688
John McCallde3fd222010-10-12 23:13:28 +00006689 // - There's a non-dependent scope specifier, in which case we
6690 // compute it and do a previous lookup there for a function
6691 // or function template.
6692 } else if (!SS.getScopeRep()->isDependent()) {
6693 DC = computeDeclContext(SS);
6694 if (!DC) return 0;
6695
6696 if (RequireCompleteDeclContext(SS, DC)) return 0;
6697
6698 LookupQualifiedName(Previous, DC);
6699
6700 // Ignore things found implicitly in the wrong scope.
6701 // TODO: better diagnostics for this case. Suggesting the right
6702 // qualified scope would be nice...
6703 LookupResult::Filter F = Previous.makeFilter();
6704 while (F.hasNext()) {
6705 NamedDecl *D = F.next();
6706 if (!DC->InEnclosingNamespaceSetOf(
6707 D->getDeclContext()->getRedeclContext()))
6708 F.erase();
6709 }
6710 F.done();
6711
6712 if (Previous.empty()) {
6713 D.setInvalidType();
6714 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6715 return 0;
6716 }
6717
6718 // C++ [class.friend]p1: A friend of a class is a function or
6719 // class that is not a member of the class . . .
6720 if (DC->Equals(CurContext))
6721 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6722
6723 // - There's a scope specifier that does not match any template
6724 // parameter lists, in which case we use some arbitrary context,
6725 // create a method or method template, and wait for instantiation.
6726 // - There's a scope specifier that does match some template
6727 // parameter lists, which we don't handle right now.
6728 } else {
6729 DC = CurContext;
6730 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006731 }
6732
John McCallf7cfb222010-10-13 05:45:15 +00006733 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006734 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006735 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6736 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6737 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006738 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006739 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6740 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006741 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006742 }
John McCall07e91c02009-08-06 02:15:43 +00006743 }
6744
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006745 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006746 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006747 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006748 IsDefinition,
6749 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006750 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006751
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006752 assert(ND->getDeclContext() == DC);
6753 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006754
John McCall759e32b2009-08-31 22:39:49 +00006755 // Add the function declaration to the appropriate lookup tables,
6756 // adjusting the redeclarations list as necessary. We don't
6757 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006758 //
John McCall759e32b2009-08-31 22:39:49 +00006759 // Also update the scope-based lookup if the target context's
6760 // lookup context is in lexical scope.
6761 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006762 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006763 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006764 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006765 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006766 }
John McCallaa74a0c2009-08-28 07:59:38 +00006767
6768 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006769 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006770 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006771 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006772 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006773
John McCallde3fd222010-10-12 23:13:28 +00006774 if (ND->isInvalidDecl())
6775 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006776 else {
6777 FunctionDecl *FD;
6778 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6779 FD = FTD->getTemplatedDecl();
6780 else
6781 FD = cast<FunctionDecl>(ND);
6782
6783 // Mark templated-scope function declarations as unsupported.
6784 if (FD->getNumTemplateParameterLists())
6785 FrD->setUnsupportedFriend(true);
6786 }
John McCallde3fd222010-10-12 23:13:28 +00006787
John McCall48871652010-08-21 09:40:31 +00006788 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006789}
6790
John McCall48871652010-08-21 09:40:31 +00006791void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6792 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006793
Sebastian Redlf769df52009-03-24 22:27:57 +00006794 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6795 if (!Fn) {
6796 Diag(DelLoc, diag::err_deleted_non_function);
6797 return;
6798 }
6799 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6800 Diag(DelLoc, diag::err_deleted_decl_not_first);
6801 Diag(Prev->getLocation(), diag::note_previous_declaration);
6802 // If the declaration wasn't the first, we delete the function anyway for
6803 // recovery.
6804 }
6805 Fn->setDeleted();
6806}
Sebastian Redl4c018662009-04-27 21:33:24 +00006807
6808static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6809 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6810 ++CI) {
6811 Stmt *SubStmt = *CI;
6812 if (!SubStmt)
6813 continue;
6814 if (isa<ReturnStmt>(SubStmt))
6815 Self.Diag(SubStmt->getSourceRange().getBegin(),
6816 diag::err_return_in_constructor_handler);
6817 if (!isa<Expr>(SubStmt))
6818 SearchForReturnInStmt(Self, SubStmt);
6819 }
6820}
6821
6822void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6823 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6824 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6825 SearchForReturnInStmt(*this, Handler);
6826 }
6827}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006828
Mike Stump11289f42009-09-09 15:08:12 +00006829bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006830 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006831 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6832 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006833
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006834 if (Context.hasSameType(NewTy, OldTy) ||
6835 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006836 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006837
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006838 // Check if the return types are covariant
6839 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006840
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006841 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006842 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6843 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006844 NewClassTy = NewPT->getPointeeType();
6845 OldClassTy = OldPT->getPointeeType();
6846 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006847 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6848 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6849 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6850 NewClassTy = NewRT->getPointeeType();
6851 OldClassTy = OldRT->getPointeeType();
6852 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006853 }
6854 }
Mike Stump11289f42009-09-09 15:08:12 +00006855
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006856 // The return types aren't either both pointers or references to a class type.
6857 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006858 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006859 diag::err_different_return_type_for_overriding_virtual_function)
6860 << New->getDeclName() << NewTy << OldTy;
6861 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006862
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006863 return true;
6864 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006865
Anders Carlssone60365b2009-12-31 18:34:24 +00006866 // C++ [class.virtual]p6:
6867 // If the return type of D::f differs from the return type of B::f, the
6868 // class type in the return type of D::f shall be complete at the point of
6869 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006870 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6871 if (!RT->isBeingDefined() &&
6872 RequireCompleteType(New->getLocation(), NewClassTy,
6873 PDiag(diag::err_covariant_return_incomplete)
6874 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006875 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006876 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006877
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006878 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006879 // Check if the new class derives from the old class.
6880 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6881 Diag(New->getLocation(),
6882 diag::err_covariant_return_not_derived)
6883 << New->getDeclName() << NewTy << OldTy;
6884 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6885 return true;
6886 }
Mike Stump11289f42009-09-09 15:08:12 +00006887
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006888 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006889 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006890 diag::err_covariant_return_inaccessible_base,
6891 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6892 // FIXME: Should this point to the return type?
6893 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006894 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6895 return true;
6896 }
6897 }
Mike Stump11289f42009-09-09 15:08:12 +00006898
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006899 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006900 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006901 Diag(New->getLocation(),
6902 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006903 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006904 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6905 return true;
6906 };
Mike Stump11289f42009-09-09 15:08:12 +00006907
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006908
6909 // The new class type must have the same or less qualifiers as the old type.
6910 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6911 Diag(New->getLocation(),
6912 diag::err_covariant_return_type_class_type_more_qualified)
6913 << New->getDeclName() << NewTy << OldTy;
6914 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6915 return true;
6916 };
Mike Stump11289f42009-09-09 15:08:12 +00006917
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006918 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006919}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006920
Alexis Hunt96d5c762009-11-21 08:43:09 +00006921bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6922 const CXXMethodDecl *Old)
6923{
6924 if (Old->hasAttr<FinalAttr>()) {
6925 Diag(New->getLocation(), diag::err_final_function_overridden)
6926 << New->getDeclName();
6927 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6928 return true;
6929 }
6930
6931 return false;
6932}
6933
Douglas Gregor21920e372009-12-01 17:24:26 +00006934/// \brief Mark the given method pure.
6935///
6936/// \param Method the method to be marked pure.
6937///
6938/// \param InitRange the source range that covers the "0" initializer.
6939bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6940 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6941 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006942 return false;
6943 }
6944
6945 if (!Method->isInvalidDecl())
6946 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6947 << Method->getDeclName() << InitRange;
6948 return true;
6949}
6950
John McCall1f4ee7b2009-12-19 09:28:58 +00006951/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6952/// an initializer for the out-of-line declaration 'Dcl'. The scope
6953/// is a fresh scope pushed for just this purpose.
6954///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006955/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6956/// static data member of class X, names should be looked up in the scope of
6957/// class X.
John McCall48871652010-08-21 09:40:31 +00006958void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006959 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006960 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006961
John McCall1f4ee7b2009-12-19 09:28:58 +00006962 // We should only get called for declarations with scope specifiers, like:
6963 // int foo::bar;
6964 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006965 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006966}
6967
6968/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006969/// initializer for the out-of-line declaration 'D'.
6970void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006971 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006972 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006973
John McCall1f4ee7b2009-12-19 09:28:58 +00006974 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006975 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006976}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006977
6978/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6979/// C++ if/switch/while/for statement.
6980/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006981DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006982 // C++ 6.4p2:
6983 // The declarator shall not specify a function or an array.
6984 // The type-specifier-seq shall not contain typedef and shall not declare a
6985 // new class or enumeration.
6986 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6987 "Parser allowed 'typedef' as storage class of condition decl.");
6988
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006989 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006990 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6991 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006992
6993 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6994 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6995 // would be created and CXXConditionDeclExpr wants a VarDecl.
6996 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6997 << D.getSourceRange();
6998 return DeclResult();
6999 } else if (OwnedTag && OwnedTag->isDefinition()) {
7000 // The type-specifier-seq shall not declare a new class or enumeration.
7001 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7002 }
7003
John McCall48871652010-08-21 09:40:31 +00007004 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007005 if (!Dcl)
7006 return DeclResult();
7007
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007008 return Dcl;
7009}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007010
Douglas Gregor88d292c2010-05-13 16:44:06 +00007011void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7012 bool DefinitionRequired) {
7013 // Ignore any vtable uses in unevaluated operands or for classes that do
7014 // not have a vtable.
7015 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7016 CurContext->isDependentContext() ||
7017 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007018 return;
7019
Douglas Gregor88d292c2010-05-13 16:44:06 +00007020 // Try to insert this class into the map.
7021 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7022 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7023 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7024 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007025 // If we already had an entry, check to see if we are promoting this vtable
7026 // to required a definition. If so, we need to reappend to the VTableUses
7027 // list, since we may have already processed the first entry.
7028 if (DefinitionRequired && !Pos.first->second) {
7029 Pos.first->second = true;
7030 } else {
7031 // Otherwise, we can early exit.
7032 return;
7033 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007034 }
7035
7036 // Local classes need to have their virtual members marked
7037 // immediately. For all other classes, we mark their virtual members
7038 // at the end of the translation unit.
7039 if (Class->isLocalClass())
7040 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007041 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007042 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007043}
7044
Douglas Gregor88d292c2010-05-13 16:44:06 +00007045bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007046 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007047 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007048
Douglas Gregor88d292c2010-05-13 16:44:06 +00007049 // Note: The VTableUses vector could grow as a result of marking
7050 // the members of a class as "used", so we check the size each
7051 // time through the loop and prefer indices (with are stable) to
7052 // iterators (which are not).
7053 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007054 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007055 if (!Class)
7056 continue;
7057
7058 SourceLocation Loc = VTableUses[I].second;
7059
7060 // If this class has a key function, but that key function is
7061 // defined in another translation unit, we don't need to emit the
7062 // vtable even though we're using it.
7063 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007064 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007065 switch (KeyFunction->getTemplateSpecializationKind()) {
7066 case TSK_Undeclared:
7067 case TSK_ExplicitSpecialization:
7068 case TSK_ExplicitInstantiationDeclaration:
7069 // The key function is in another translation unit.
7070 continue;
7071
7072 case TSK_ExplicitInstantiationDefinition:
7073 case TSK_ImplicitInstantiation:
7074 // We will be instantiating the key function.
7075 break;
7076 }
7077 } else if (!KeyFunction) {
7078 // If we have a class with no key function that is the subject
7079 // of an explicit instantiation declaration, suppress the
7080 // vtable; it will live with the explicit instantiation
7081 // definition.
7082 bool IsExplicitInstantiationDeclaration
7083 = Class->getTemplateSpecializationKind()
7084 == TSK_ExplicitInstantiationDeclaration;
7085 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7086 REnd = Class->redecls_end();
7087 R != REnd; ++R) {
7088 TemplateSpecializationKind TSK
7089 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7090 if (TSK == TSK_ExplicitInstantiationDeclaration)
7091 IsExplicitInstantiationDeclaration = true;
7092 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7093 IsExplicitInstantiationDeclaration = false;
7094 break;
7095 }
7096 }
7097
7098 if (IsExplicitInstantiationDeclaration)
7099 continue;
7100 }
7101
7102 // Mark all of the virtual members of this class as referenced, so
7103 // that we can build a vtable. Then, tell the AST consumer that a
7104 // vtable for this class is required.
7105 MarkVirtualMembersReferenced(Loc, Class);
7106 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7107 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7108
7109 // Optionally warn if we're emitting a weak vtable.
7110 if (Class->getLinkage() == ExternalLinkage &&
7111 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007112 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007113 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7114 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007115 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007116 VTableUses.clear();
7117
Anders Carlsson82fccd02009-12-07 08:24:59 +00007118 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007119}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007120
Rafael Espindola5b334082010-03-26 00:36:59 +00007121void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7122 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007123 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7124 e = RD->method_end(); i != e; ++i) {
7125 CXXMethodDecl *MD = *i;
7126
7127 // C++ [basic.def.odr]p2:
7128 // [...] A virtual member function is used if it is not pure. [...]
7129 if (MD->isVirtual() && !MD->isPure())
7130 MarkDeclarationReferenced(Loc, MD);
7131 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007132
7133 // Only classes that have virtual bases need a VTT.
7134 if (RD->getNumVBases() == 0)
7135 return;
7136
7137 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7138 e = RD->bases_end(); i != e; ++i) {
7139 const CXXRecordDecl *Base =
7140 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007141 if (Base->getNumVBases() == 0)
7142 continue;
7143 MarkVirtualMembersReferenced(Loc, Base);
7144 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007145}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007146
7147/// SetIvarInitializers - This routine builds initialization ASTs for the
7148/// Objective-C implementation whose ivars need be initialized.
7149void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7150 if (!getLangOptions().CPlusPlus)
7151 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007152 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007153 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7154 CollectIvarsToConstructOrDestruct(OID, ivars);
7155 if (ivars.empty())
7156 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007157 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007158 for (unsigned i = 0; i < ivars.size(); i++) {
7159 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007160 if (Field->isInvalidDecl())
7161 continue;
7162
Alexis Hunt1d792652011-01-08 20:30:50 +00007163 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007164 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7165 InitializationKind InitKind =
7166 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7167
7168 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007169 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007170 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007171 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007172 // Note, MemberInit could actually come back empty if no initialization
7173 // is required (e.g., because it would call a trivial default constructor)
7174 if (!MemberInit.get() || MemberInit.isInvalid())
7175 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007176
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007177 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007178 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7179 SourceLocation(),
7180 MemberInit.takeAs<Expr>(),
7181 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007182 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007183
7184 // Be sure that the destructor is accessible and is marked as referenced.
7185 if (const RecordType *RecordTy
7186 = Context.getBaseElementType(Field->getType())
7187 ->getAs<RecordType>()) {
7188 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007189 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007190 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7191 CheckDestructorAccess(Field->getLocation(), Destructor,
7192 PDiag(diag::err_access_dtor_ivar)
7193 << Context.getBaseElementType(Field->getType()));
7194 }
7195 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007196 }
7197 ObjCImplementation->setIvarInitializers(Context,
7198 AllToInit.data(), AllToInit.size());
7199 }
7200}