blob: 2f7640cd612068ee5c3bd232c55a133af80f4c55 [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
Anders Carlsson3f610c72011-01-20 16:25:36 +0000878/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
879/// function overrides a virtual member function marked 'final', according to
880/// C++0x [class.virtual]p3.
881bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
882 const CXXMethodDecl *Old) {
883 // FIXME: Get rid of FinalAttr here.
884 if (Old->hasAttr<FinalAttr>() || Old->isMarkedFinal()) {
885 Diag(New->getLocation(), diag::err_final_function_overridden)
886 << New->getDeclName();
887 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
888 return true;
889 }
890
891 return false;
892}
893
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
895/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
896/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000897/// any.
John McCall48871652010-08-21 09:40:31 +0000898Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000899Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000900 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000901 ExprTy *BW, const VirtSpecifiers &VS,
902 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000903 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000904 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000905 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
906 DeclarationName Name = NameInfo.getName();
907 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000908
909 // For anonymous bitfields, the location should point to the type.
910 if (Loc.isInvalid())
911 Loc = D.getSourceRange().getBegin();
912
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000913 Expr *BitWidth = static_cast<Expr*>(BW);
914 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915
John McCallb1cd7da2010-06-04 08:34:12 +0000916 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000917 assert(!DS.isFriendSpecified());
918
John McCallb1cd7da2010-06-04 08:34:12 +0000919 bool isFunc = false;
920 if (D.isFunctionDeclarator())
921 isFunc = true;
922 else if (D.getNumTypeObjects() == 0 &&
923 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000924 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000925 isFunc = TDType->isFunctionType();
926 }
927
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000928 // C++ 9.2p6: A member shall not be declared to have automatic storage
929 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000930 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
931 // data members and cannot be applied to names declared const or static,
932 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000933 switch (DS.getStorageClassSpec()) {
934 case DeclSpec::SCS_unspecified:
935 case DeclSpec::SCS_typedef:
936 case DeclSpec::SCS_static:
937 // FALL THROUGH.
938 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000939 case DeclSpec::SCS_mutable:
940 if (isFunc) {
941 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000942 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000943 else
Chris Lattner3b054132008-11-19 05:08:23 +0000944 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Sebastian Redl8071edb2008-11-17 23:24:37 +0000946 // FIXME: It would be nicer if the keyword was ignored only for this
947 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000948 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000949 }
950 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000951 default:
952 if (DS.getStorageClassSpecLoc().isValid())
953 Diag(DS.getStorageClassSpecLoc(),
954 diag::err_storageclass_invalid_for_member);
955 else
956 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
957 D.getMutableDeclSpec().ClearStorageClassSpecs();
958 }
959
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000960 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
961 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000962 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000963
964 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000965 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000966 CXXScopeSpec &SS = D.getCXXScopeSpec();
967
968
969 if (SS.isSet() && !SS.isInvalid()) {
970 // The user provided a superfluous scope specifier inside a class
971 // definition:
972 //
973 // class X {
974 // int X::member;
975 // };
976 DeclContext *DC = 0;
977 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
978 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
979 << Name << FixItHint::CreateRemoval(SS.getRange());
980 else
981 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
982 << Name << SS.getRange();
983
984 SS.clear();
985 }
986
Douglas Gregor3447e762009-08-20 22:52:58 +0000987 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000988 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000989 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
990 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000991 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000992 } else {
John McCall48871652010-08-21 09:40:31 +0000993 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000994 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000995 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000996 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000997
998 // Non-instance-fields can't have a bitfield.
999 if (BitWidth) {
1000 if (Member->isInvalidDecl()) {
1001 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001002 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001003 // C++ 9.6p3: A bit-field shall not be a static member.
1004 // "static member 'A' cannot be a bit-field"
1005 Diag(Loc, diag::err_static_not_bitfield)
1006 << Name << BitWidth->getSourceRange();
1007 } else if (isa<TypedefDecl>(Member)) {
1008 // "typedef member 'x' cannot be a bit-field"
1009 Diag(Loc, diag::err_typedef_not_bitfield)
1010 << Name << BitWidth->getSourceRange();
1011 } else {
1012 // A function typedef ("typedef int f(); f a;").
1013 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1014 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001015 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001016 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattnerd26760a2009-03-05 23:01:03 +00001019 BitWidth = 0;
1020 Member->setInvalidDecl();
1021 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001022
1023 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregor3447e762009-08-20 22:52:58 +00001025 // If we have declared a member function template, set the access of the
1026 // templated declaration as well.
1027 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1028 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001029 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001030
Anders Carlsson13a69102011-01-20 04:34:22 +00001031 if (VS.isOverrideSpecified()) {
1032 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1033 if (!MD || !MD->isVirtual()) {
1034 Diag(Member->getLocStart(),
1035 diag::override_keyword_only_allowed_on_virtual_member_functions)
1036 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001037 } else
1038 MD->setIsMarkedOverride(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001039 }
1040 if (VS.isFinalSpecified()) {
1041 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1042 if (!MD || !MD->isVirtual()) {
1043 Diag(Member->getLocStart(),
1044 diag::override_keyword_only_allowed_on_virtual_member_functions)
1045 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001046 } else
1047 MD->setIsMarkedFinal(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001048 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001049
Anders Carlssonc87f8612011-01-20 06:29:02 +00001050 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001051
Douglas Gregor92751d42008-11-17 22:58:34 +00001052 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001053
Douglas Gregor0c880302009-03-11 23:00:04 +00001054 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001055 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001056 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001057 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001058
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001059 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001060 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001061 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001062 }
John McCall48871652010-08-21 09:40:31 +00001063 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001064}
1065
Douglas Gregor15e77a22009-12-31 09:10:24 +00001066/// \brief Find the direct and/or virtual base specifiers that
1067/// correspond to the given base type, for use in base initialization
1068/// within a constructor.
1069static bool FindBaseInitializer(Sema &SemaRef,
1070 CXXRecordDecl *ClassDecl,
1071 QualType BaseType,
1072 const CXXBaseSpecifier *&DirectBaseSpec,
1073 const CXXBaseSpecifier *&VirtualBaseSpec) {
1074 // First, check for a direct base class.
1075 DirectBaseSpec = 0;
1076 for (CXXRecordDecl::base_class_const_iterator Base
1077 = ClassDecl->bases_begin();
1078 Base != ClassDecl->bases_end(); ++Base) {
1079 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1080 // We found a direct base of this type. That's what we're
1081 // initializing.
1082 DirectBaseSpec = &*Base;
1083 break;
1084 }
1085 }
1086
1087 // Check for a virtual base class.
1088 // FIXME: We might be able to short-circuit this if we know in advance that
1089 // there are no virtual bases.
1090 VirtualBaseSpec = 0;
1091 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1092 // We haven't found a base yet; search the class hierarchy for a
1093 // virtual base class.
1094 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1095 /*DetectVirtual=*/false);
1096 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1097 BaseType, Paths)) {
1098 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1099 Path != Paths.end(); ++Path) {
1100 if (Path->back().Base->isVirtual()) {
1101 VirtualBaseSpec = Path->back().Base;
1102 break;
1103 }
1104 }
1105 }
1106 }
1107
1108 return DirectBaseSpec || VirtualBaseSpec;
1109}
1110
Douglas Gregore8381c02008-11-05 04:29:56 +00001111/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001112MemInitResult
John McCall48871652010-08-21 09:40:31 +00001113Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001114 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001115 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001116 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001117 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001118 SourceLocation IdLoc,
1119 SourceLocation LParenLoc,
1120 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001121 SourceLocation RParenLoc,
1122 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001123 if (!ConstructorD)
1124 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001125
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001126 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001127
1128 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001129 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001130 if (!Constructor) {
1131 // The user wrote a constructor initializer on a function that is
1132 // not a C++ constructor. Ignore the error for now, because we may
1133 // have more member initializers coming; we'll diagnose it just
1134 // once in ActOnMemInitializers.
1135 return true;
1136 }
1137
1138 CXXRecordDecl *ClassDecl = Constructor->getParent();
1139
1140 // C++ [class.base.init]p2:
1141 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001142 // constructor's class and, if not found in that scope, are looked
1143 // up in the scope containing the constructor's definition.
1144 // [Note: if the constructor's class contains a member with the
1145 // same name as a direct or virtual base class of the class, a
1146 // mem-initializer-id naming the member or base class and composed
1147 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001148 // mem-initializer-id for the hidden base class may be specified
1149 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001150 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001151 // Look for a member, first.
1152 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001153 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001154 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001155 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001156 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001157
Douglas Gregor44e7df62011-01-04 00:32:56 +00001158 if (Member) {
1159 if (EllipsisLoc.isValid())
1160 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1161 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1162
Francois Pichetd583da02010-12-04 09:14:42 +00001163 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001164 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001165 }
1166
Francois Pichetd583da02010-12-04 09:14:42 +00001167 // Handle anonymous union case.
1168 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001169 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1170 if (EllipsisLoc.isValid())
1171 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1172 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1173
Francois Pichetd583da02010-12-04 09:14:42 +00001174 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1175 NumArgs, IdLoc,
1176 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001177 }
Francois Pichetd583da02010-12-04 09:14:42 +00001178 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001179 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001180 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001181 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001182 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001183
1184 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001185 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001186 } else {
1187 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1188 LookupParsedName(R, S, &SS);
1189
1190 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1191 if (!TyD) {
1192 if (R.isAmbiguous()) return true;
1193
John McCallda6841b2010-04-09 19:01:14 +00001194 // We don't want access-control diagnostics here.
1195 R.suppressDiagnostics();
1196
Douglas Gregora3b624a2010-01-19 06:46:48 +00001197 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1198 bool NotUnknownSpecialization = false;
1199 DeclContext *DC = computeDeclContext(SS, false);
1200 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1201 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1202
1203 if (!NotUnknownSpecialization) {
1204 // When the scope specifier can refer to a member of an unknown
1205 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001206 BaseType = CheckTypenameType(ETK_None,
1207 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001208 *MemberOrBase, SourceLocation(),
1209 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001210 if (BaseType.isNull())
1211 return true;
1212
Douglas Gregora3b624a2010-01-19 06:46:48 +00001213 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001214 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001215 }
1216 }
1217
Douglas Gregor15e77a22009-12-31 09:10:24 +00001218 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001219 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001220 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1221 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001222 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001223 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001224 // We have found a non-static data member with a similar
1225 // name to what was typed; complain and initialize that
1226 // member.
1227 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1228 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001229 << FixItHint::CreateReplacement(R.getNameLoc(),
1230 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001231 Diag(Member->getLocation(), diag::note_previous_decl)
1232 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001233
1234 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1235 LParenLoc, RParenLoc);
1236 }
1237 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1238 const CXXBaseSpecifier *DirectBaseSpec;
1239 const CXXBaseSpecifier *VirtualBaseSpec;
1240 if (FindBaseInitializer(*this, ClassDecl,
1241 Context.getTypeDeclType(Type),
1242 DirectBaseSpec, VirtualBaseSpec)) {
1243 // We have found a direct or virtual base class with a
1244 // similar name to what was typed; complain and initialize
1245 // that base class.
1246 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1247 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001248 << FixItHint::CreateReplacement(R.getNameLoc(),
1249 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001250
1251 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1252 : VirtualBaseSpec;
1253 Diag(BaseSpec->getSourceRange().getBegin(),
1254 diag::note_base_class_specified_here)
1255 << BaseSpec->getType()
1256 << BaseSpec->getSourceRange();
1257
Douglas Gregor15e77a22009-12-31 09:10:24 +00001258 TyD = Type;
1259 }
1260 }
1261 }
1262
Douglas Gregora3b624a2010-01-19 06:46:48 +00001263 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001264 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1265 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1266 return true;
1267 }
John McCallb5a0d312009-12-21 10:41:20 +00001268 }
1269
Douglas Gregora3b624a2010-01-19 06:46:48 +00001270 if (BaseType.isNull()) {
1271 BaseType = Context.getTypeDeclType(TyD);
1272 if (SS.isSet()) {
1273 NestedNameSpecifier *Qualifier =
1274 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001275
Douglas Gregora3b624a2010-01-19 06:46:48 +00001276 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001277 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001278 }
John McCallb5a0d312009-12-21 10:41:20 +00001279 }
1280 }
Mike Stump11289f42009-09-09 15:08:12 +00001281
John McCallbcd03502009-12-07 02:54:59 +00001282 if (!TInfo)
1283 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001284
John McCallbcd03502009-12-07 02:54:59 +00001285 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001286 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001287}
1288
John McCalle22a04a2009-11-04 23:02:40 +00001289/// Checks an initializer expression for use of uninitialized fields, such as
1290/// containing the field that is being initialized. Returns true if there is an
1291/// uninitialized field was used an updates the SourceLocation parameter; false
1292/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001293static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001294 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001295 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001296 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1297
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001298 if (isa<CallExpr>(S)) {
1299 // Do not descend into function calls or constructors, as the use
1300 // of an uninitialized field may be valid. One would have to inspect
1301 // the contents of the function/ctor to determine if it is safe or not.
1302 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1303 // may be safe, depending on what the function/ctor does.
1304 return false;
1305 }
1306 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1307 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001308
1309 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1310 // The member expression points to a static data member.
1311 assert(VD->isStaticDataMember() &&
1312 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001313 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001314 return false;
1315 }
1316
1317 if (isa<EnumConstantDecl>(RhsField)) {
1318 // The member expression points to an enum.
1319 return false;
1320 }
1321
John McCalle22a04a2009-11-04 23:02:40 +00001322 if (RhsField == LhsField) {
1323 // Initializing a field with itself. Throw a warning.
1324 // But wait; there are exceptions!
1325 // Exception #1: The field may not belong to this record.
1326 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001327 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001328 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1329 // Even though the field matches, it does not belong to this record.
1330 return false;
1331 }
1332 // None of the exceptions triggered; return true to indicate an
1333 // uninitialized field was used.
1334 *L = ME->getMemberLoc();
1335 return true;
1336 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001337 } else if (isa<SizeOfAlignOfExpr>(S)) {
1338 // sizeof/alignof doesn't reference contents, do not warn.
1339 return false;
1340 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1341 // address-of doesn't reference contents (the pointer may be dereferenced
1342 // in the same expression but it would be rare; and weird).
1343 if (UOE->getOpcode() == UO_AddrOf)
1344 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001345 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001346 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1347 it != e; ++it) {
1348 if (!*it) {
1349 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001350 continue;
1351 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001352 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1353 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001354 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001355 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001356}
1357
John McCallfaf5fb42010-08-26 23:41:50 +00001358MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001359Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001360 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001361 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001362 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001363 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1364 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1365 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001366 "Member must be a FieldDecl or IndirectFieldDecl");
1367
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001368 if (Member->isInvalidDecl())
1369 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001370
John McCalle22a04a2009-11-04 23:02:40 +00001371 // Diagnose value-uses of fields to initialize themselves, e.g.
1372 // foo(foo)
1373 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001374 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001375 for (unsigned i = 0; i < NumArgs; ++i) {
1376 SourceLocation L;
1377 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1378 // FIXME: Return true in the case when other fields are used before being
1379 // uninitialized. For example, let this field be the i'th field. When
1380 // initializing the i'th field, throw a warning if any of the >= i'th
1381 // fields are used, as they are not yet initialized.
1382 // Right now we are only handling the case where the i'th field uses
1383 // itself in its initializer.
1384 Diag(L, diag::warn_field_is_uninit);
1385 }
1386 }
1387
Eli Friedman8e1433b2009-07-29 19:44:27 +00001388 bool HasDependentArg = false;
1389 for (unsigned i = 0; i < NumArgs; i++)
1390 HasDependentArg |= Args[i]->isTypeDependent();
1391
Chandler Carruthd44c3102010-12-06 09:23:57 +00001392 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001393 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001394 // Can't check initialization for a member of dependent type or when
1395 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001396 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1397 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001398
1399 // Erase any temporaries within this evaluation context; we're not
1400 // going to track them in the AST, since we'll be rebuilding the
1401 // ASTs during template instantiation.
1402 ExprTemporaries.erase(
1403 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1404 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001405 } else {
1406 // Initialize the member.
1407 InitializedEntity MemberEntity =
1408 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1409 : InitializedEntity::InitializeMember(IndirectMember, 0);
1410 InitializationKind Kind =
1411 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001412
Chandler Carruthd44c3102010-12-06 09:23:57 +00001413 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1414
1415 ExprResult MemberInit =
1416 InitSeq.Perform(*this, MemberEntity, Kind,
1417 MultiExprArg(*this, Args, NumArgs), 0);
1418 if (MemberInit.isInvalid())
1419 return true;
1420
1421 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1422
1423 // C++0x [class.base.init]p7:
1424 // The initialization of each base and member constitutes a
1425 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001426 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001427 if (MemberInit.isInvalid())
1428 return true;
1429
1430 // If we are in a dependent context, template instantiation will
1431 // perform this type-checking again. Just save the arguments that we
1432 // received in a ParenListExpr.
1433 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1434 // of the information that we have about the member
1435 // initializer. However, deconstructing the ASTs is a dicey process,
1436 // and this approach is far more likely to get the corner cases right.
1437 if (CurContext->isDependentContext())
1438 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1439 RParenLoc);
1440 else
1441 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001442 }
1443
Chandler Carruthd44c3102010-12-06 09:23:57 +00001444 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001445 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001446 IdLoc, LParenLoc, Init,
1447 RParenLoc);
1448 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001449 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001450 IdLoc, LParenLoc, Init,
1451 RParenLoc);
1452 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001453}
1454
John McCallfaf5fb42010-08-26 23:41:50 +00001455MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001456Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1457 Expr **Args, unsigned NumArgs,
1458 SourceLocation LParenLoc,
1459 SourceLocation RParenLoc,
1460 CXXRecordDecl *ClassDecl,
1461 SourceLocation EllipsisLoc) {
1462 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1463 if (!LangOpts.CPlusPlus0x)
1464 return Diag(Loc, diag::err_delegation_0x_only)
1465 << TInfo->getTypeLoc().getLocalSourceRange();
1466
1467 return Diag(Loc, diag::err_delegation_unimplemented)
1468 << TInfo->getTypeLoc().getLocalSourceRange();
1469}
1470
1471MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001472Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001473 Expr **Args, unsigned NumArgs,
1474 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001475 CXXRecordDecl *ClassDecl,
1476 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001477 bool HasDependentArg = false;
1478 for (unsigned i = 0; i < NumArgs; i++)
1479 HasDependentArg |= Args[i]->isTypeDependent();
1480
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001481 SourceLocation BaseLoc
1482 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1483
1484 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1485 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1486 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1487
1488 // C++ [class.base.init]p2:
1489 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001490 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001491 // of that class, the mem-initializer is ill-formed. A
1492 // mem-initializer-list can initialize a base class using any
1493 // name that denotes that base class type.
1494 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1495
Douglas Gregor44e7df62011-01-04 00:32:56 +00001496 if (EllipsisLoc.isValid()) {
1497 // This is a pack expansion.
1498 if (!BaseType->containsUnexpandedParameterPack()) {
1499 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1500 << SourceRange(BaseLoc, RParenLoc);
1501
1502 EllipsisLoc = SourceLocation();
1503 }
1504 } else {
1505 // Check for any unexpanded parameter packs.
1506 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1507 return true;
1508
1509 for (unsigned I = 0; I != NumArgs; ++I)
1510 if (DiagnoseUnexpandedParameterPack(Args[I]))
1511 return true;
1512 }
1513
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001514 // Check for direct and virtual base classes.
1515 const CXXBaseSpecifier *DirectBaseSpec = 0;
1516 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1517 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001518 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1519 BaseType))
1520 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1521 LParenLoc, RParenLoc, ClassDecl,
1522 EllipsisLoc);
1523
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001524 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1525 VirtualBaseSpec);
1526
1527 // C++ [base.class.init]p2:
1528 // Unless the mem-initializer-id names a nonstatic data member of the
1529 // constructor's class or a direct or virtual base of that class, the
1530 // mem-initializer is ill-formed.
1531 if (!DirectBaseSpec && !VirtualBaseSpec) {
1532 // If the class has any dependent bases, then it's possible that
1533 // one of those types will resolve to the same type as
1534 // BaseType. Therefore, just treat this as a dependent base
1535 // class initialization. FIXME: Should we try to check the
1536 // initialization anyway? It seems odd.
1537 if (ClassDecl->hasAnyDependentBases())
1538 Dependent = true;
1539 else
1540 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1541 << BaseType << Context.getTypeDeclType(ClassDecl)
1542 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1543 }
1544 }
1545
1546 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001547 // Can't check initialization for a base of dependent type or when
1548 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001549 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001550 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1551 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001552
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001553 // Erase any temporaries within this evaluation context; we're not
1554 // going to track them in the AST, since we'll be rebuilding the
1555 // ASTs during template instantiation.
1556 ExprTemporaries.erase(
1557 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1558 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001559
Alexis Hunt1d792652011-01-08 20:30:50 +00001560 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001561 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001562 LParenLoc,
1563 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001564 RParenLoc,
1565 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001566 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001567
1568 // C++ [base.class.init]p2:
1569 // If a mem-initializer-id is ambiguous because it designates both
1570 // a direct non-virtual base class and an inherited virtual base
1571 // class, the mem-initializer is ill-formed.
1572 if (DirectBaseSpec && VirtualBaseSpec)
1573 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001574 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001575
1576 CXXBaseSpecifier *BaseSpec
1577 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1578 if (!BaseSpec)
1579 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1580
1581 // Initialize the base.
1582 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001583 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001584 InitializationKind Kind =
1585 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1586
1587 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1588
John McCalldadc5752010-08-24 06:29:42 +00001589 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001590 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001591 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001592 if (BaseInit.isInvalid())
1593 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001594
1595 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001596
1597 // C++0x [class.base.init]p7:
1598 // The initialization of each base and member constitutes a
1599 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001600 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001601 if (BaseInit.isInvalid())
1602 return true;
1603
1604 // If we are in a dependent context, template instantiation will
1605 // perform this type-checking again. Just save the arguments that we
1606 // received in a ParenListExpr.
1607 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1608 // of the information that we have about the base
1609 // initializer. However, deconstructing the ASTs is a dicey process,
1610 // and this approach is far more likely to get the corner cases right.
1611 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001612 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001613 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1614 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001615 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001616 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001617 LParenLoc,
1618 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001619 RParenLoc,
1620 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001621 }
1622
Alexis Hunt1d792652011-01-08 20:30:50 +00001623 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001624 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001625 LParenLoc,
1626 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001627 RParenLoc,
1628 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001629}
1630
Anders Carlsson1b00e242010-04-23 03:10:23 +00001631/// ImplicitInitializerKind - How an implicit base or member initializer should
1632/// initialize its base or member.
1633enum ImplicitInitializerKind {
1634 IIK_Default,
1635 IIK_Copy,
1636 IIK_Move
1637};
1638
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001639static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001640BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001641 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001642 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001643 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001644 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001645 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001646 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1647 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001648
John McCalldadc5752010-08-24 06:29:42 +00001649 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001650
1651 switch (ImplicitInitKind) {
1652 case IIK_Default: {
1653 InitializationKind InitKind
1654 = InitializationKind::CreateDefault(Constructor->getLocation());
1655 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1656 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001657 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001658 break;
1659 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001660
Anders Carlsson1b00e242010-04-23 03:10:23 +00001661 case IIK_Copy: {
1662 ParmVarDecl *Param = Constructor->getParamDecl(0);
1663 QualType ParamType = Param->getType().getNonReferenceType();
1664
1665 Expr *CopyCtorArg =
1666 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001667 Constructor->getLocation(), ParamType,
1668 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001669
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001670 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001671 QualType ArgTy =
1672 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1673 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001674
1675 CXXCastPath BasePath;
1676 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001677 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001678 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001679 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001680
Anders Carlsson1b00e242010-04-23 03:10:23 +00001681 InitializationKind InitKind
1682 = InitializationKind::CreateDirect(Constructor->getLocation(),
1683 SourceLocation(), SourceLocation());
1684 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1685 &CopyCtorArg, 1);
1686 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001687 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001688 break;
1689 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001690
Anders Carlsson1b00e242010-04-23 03:10:23 +00001691 case IIK_Move:
1692 assert(false && "Unhandled initializer kind!");
1693 }
John McCallb268a282010-08-23 23:25:46 +00001694
Douglas Gregora40433a2010-12-07 00:41:46 +00001695 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001696 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001697 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001698
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001699 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001700 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001701 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1702 SourceLocation()),
1703 BaseSpec->isVirtual(),
1704 SourceLocation(),
1705 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001706 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001707 SourceLocation());
1708
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001709 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001710}
1711
Anders Carlsson3c1db572010-04-23 02:15:47 +00001712static bool
1713BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001714 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001715 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001716 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001717 if (Field->isInvalidDecl())
1718 return true;
1719
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001720 SourceLocation Loc = Constructor->getLocation();
1721
Anders Carlsson423f5d82010-04-23 16:04:08 +00001722 if (ImplicitInitKind == IIK_Copy) {
1723 ParmVarDecl *Param = Constructor->getParamDecl(0);
1724 QualType ParamType = Param->getType().getNonReferenceType();
1725
1726 Expr *MemberExprBase =
1727 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001728 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001729
1730 // Build a reference to this field within the parameter.
1731 CXXScopeSpec SS;
1732 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1733 Sema::LookupMemberName);
1734 MemberLookup.addDecl(Field, AS_public);
1735 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001736 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001737 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001738 ParamType, Loc,
1739 /*IsArrow=*/false,
1740 SS,
1741 /*FirstQualifierInScope=*/0,
1742 MemberLookup,
1743 /*TemplateArgs=*/0);
1744 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001745 return true;
1746
Douglas Gregor94f9a482010-05-05 05:51:00 +00001747 // When the field we are copying is an array, create index variables for
1748 // each dimension of the array. We use these index variables to subscript
1749 // the source array, and other clients (e.g., CodeGen) will perform the
1750 // necessary iteration with these index variables.
1751 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1752 QualType BaseType = Field->getType();
1753 QualType SizeType = SemaRef.Context.getSizeType();
1754 while (const ConstantArrayType *Array
1755 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1756 // Create the iteration variable for this array index.
1757 IdentifierInfo *IterationVarName = 0;
1758 {
1759 llvm::SmallString<8> Str;
1760 llvm::raw_svector_ostream OS(Str);
1761 OS << "__i" << IndexVariables.size();
1762 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1763 }
1764 VarDecl *IterationVar
1765 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1766 IterationVarName, SizeType,
1767 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001768 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001769 IndexVariables.push_back(IterationVar);
1770
1771 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001772 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001773 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001774 assert(!IterationVarRef.isInvalid() &&
1775 "Reference to invented variable cannot fail!");
1776
1777 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001778 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001779 Loc,
John McCallb268a282010-08-23 23:25:46 +00001780 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001781 Loc);
1782 if (CopyCtorArg.isInvalid())
1783 return true;
1784
1785 BaseType = Array->getElementType();
1786 }
1787
1788 // Construct the entity that we will be initializing. For an array, this
1789 // will be first element in the array, which may require several levels
1790 // of array-subscript entities.
1791 llvm::SmallVector<InitializedEntity, 4> Entities;
1792 Entities.reserve(1 + IndexVariables.size());
1793 Entities.push_back(InitializedEntity::InitializeMember(Field));
1794 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1795 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1796 0,
1797 Entities.back()));
1798
1799 // Direct-initialize to use the copy constructor.
1800 InitializationKind InitKind =
1801 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1802
1803 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1804 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1805 &CopyCtorArgE, 1);
1806
John McCalldadc5752010-08-24 06:29:42 +00001807 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001808 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001809 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001810 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001811 if (MemberInit.isInvalid())
1812 return true;
1813
1814 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001815 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001816 MemberInit.takeAs<Expr>(), Loc,
1817 IndexVariables.data(),
1818 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001819 return false;
1820 }
1821
Anders Carlsson423f5d82010-04-23 16:04:08 +00001822 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1823
Anders Carlsson3c1db572010-04-23 02:15:47 +00001824 QualType FieldBaseElementType =
1825 SemaRef.Context.getBaseElementType(Field->getType());
1826
Anders Carlsson3c1db572010-04-23 02:15:47 +00001827 if (FieldBaseElementType->isRecordType()) {
1828 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001829 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001830 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001831
1832 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001833 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001834 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001835
Douglas Gregora40433a2010-12-07 00:41:46 +00001836 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001837 if (MemberInit.isInvalid())
1838 return true;
1839
1840 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001841 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001842 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001843 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001844 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001845 return false;
1846 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001847
1848 if (FieldBaseElementType->isReferenceType()) {
1849 SemaRef.Diag(Constructor->getLocation(),
1850 diag::err_uninitialized_member_in_ctor)
1851 << (int)Constructor->isImplicit()
1852 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1853 << 0 << Field->getDeclName();
1854 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1855 return true;
1856 }
1857
1858 if (FieldBaseElementType.isConstQualified()) {
1859 SemaRef.Diag(Constructor->getLocation(),
1860 diag::err_uninitialized_member_in_ctor)
1861 << (int)Constructor->isImplicit()
1862 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1863 << 1 << Field->getDeclName();
1864 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1865 return true;
1866 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001867
1868 // Nothing to initialize.
1869 CXXMemberInit = 0;
1870 return false;
1871}
John McCallbc83b3f2010-05-20 23:23:51 +00001872
1873namespace {
1874struct BaseAndFieldInfo {
1875 Sema &S;
1876 CXXConstructorDecl *Ctor;
1877 bool AnyErrorsInInits;
1878 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001879 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1880 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001881
1882 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1883 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1884 // FIXME: Handle implicit move constructors.
1885 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1886 IIK = IIK_Copy;
1887 else
1888 IIK = IIK_Default;
1889 }
1890};
1891}
1892
1893static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1894 FieldDecl *Top, FieldDecl *Field) {
1895
Chandler Carruth139e9622010-06-30 02:59:29 +00001896 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001897 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001898 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001899 return false;
1900 }
1901
1902 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1903 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1904 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001905 CXXRecordDecl *FieldClassDecl
1906 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001907
1908 // Even though union members never have non-trivial default
1909 // constructions in C++03, we still build member initializers for aggregate
1910 // record types which can be union members, and C++0x allows non-trivial
1911 // default constructors for union members, so we ensure that only one
1912 // member is initialized for these.
1913 if (FieldClassDecl->isUnion()) {
1914 // First check for an explicit initializer for one field.
1915 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1916 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001917 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001918 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001919
1920 // Once we've initialized a field of an anonymous union, the union
1921 // field in the class is also initialized, so exit immediately.
1922 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001923 } else if ((*FA)->isAnonymousStructOrUnion()) {
1924 if (CollectFieldInitializer(Info, Top, *FA))
1925 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001926 }
1927 }
1928
1929 // Fallthrough and construct a default initializer for the union as
1930 // a whole, which can call its default constructor if such a thing exists
1931 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1932 // behavior going forward with C++0x, when anonymous unions there are
1933 // finalized, we should revisit this.
1934 } else {
1935 // For structs, we simply descend through to initialize all members where
1936 // necessary.
1937 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1938 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1939 if (CollectFieldInitializer(Info, Top, *FA))
1940 return true;
1941 }
1942 }
John McCallbc83b3f2010-05-20 23:23:51 +00001943 }
1944
1945 // Don't try to build an implicit initializer if there were semantic
1946 // errors in any of the initializers (and therefore we might be
1947 // missing some that the user actually wrote).
1948 if (Info.AnyErrorsInInits)
1949 return false;
1950
Alexis Hunt1d792652011-01-08 20:30:50 +00001951 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001952 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1953 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001954
Francois Pichetd583da02010-12-04 09:14:42 +00001955 if (Init)
1956 Info.AllToInit.push_back(Init);
1957
John McCallbc83b3f2010-05-20 23:23:51 +00001958 return false;
1959}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001960
Eli Friedman9cf6b592009-11-09 19:20:36 +00001961bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001962Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1963 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001964 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001965 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001966 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001967 // Just store the initializers as written, they will be checked during
1968 // instantiation.
1969 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001970 Constructor->setNumCtorInitializers(NumInitializers);
1971 CXXCtorInitializer **baseOrMemberInitializers =
1972 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001973 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001974 NumInitializers * sizeof(CXXCtorInitializer*));
1975 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001976 }
1977
1978 return false;
1979 }
1980
John McCallbc83b3f2010-05-20 23:23:51 +00001981 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001982
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001983 // We need to build the initializer AST according to order of construction
1984 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001985 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001986 if (!ClassDecl)
1987 return true;
1988
Eli Friedman9cf6b592009-11-09 19:20:36 +00001989 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001990
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001991 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001992 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001993
1994 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001995 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001996 else
Francois Pichetd583da02010-12-04 09:14:42 +00001997 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001998 }
1999
Anders Carlsson43c64af2010-04-21 19:52:01 +00002000 // Keep track of the direct virtual bases.
2001 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2002 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2003 E = ClassDecl->bases_end(); I != E; ++I) {
2004 if (I->isVirtual())
2005 DirectVBases.insert(I);
2006 }
2007
Anders Carlssondb0a9652010-04-02 06:26:44 +00002008 // Push virtual bases before others.
2009 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2010 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2011
Alexis Hunt1d792652011-01-08 20:30:50 +00002012 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002013 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2014 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002015 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002016 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002017 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002018 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002019 VBase, IsInheritedVirtualBase,
2020 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002021 HadError = true;
2022 continue;
2023 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002024
John McCallbc83b3f2010-05-20 23:23:51 +00002025 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002026 }
2027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
John McCallbc83b3f2010-05-20 23:23:51 +00002029 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002030 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2031 E = ClassDecl->bases_end(); Base != E; ++Base) {
2032 // Virtuals are in the virtual base list and already constructed.
2033 if (Base->isVirtual())
2034 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002035
Alexis Hunt1d792652011-01-08 20:30:50 +00002036 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002037 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2038 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002039 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002040 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002041 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002042 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002043 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002044 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002045 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002046 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002047
John McCallbc83b3f2010-05-20 23:23:51 +00002048 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002049 }
2050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051
John McCallbc83b3f2010-05-20 23:23:51 +00002052 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002053 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002054 E = ClassDecl->field_end(); Field != E; ++Field) {
2055 if ((*Field)->getType()->isIncompleteArrayType()) {
2056 assert(ClassDecl->hasFlexibleArrayMember() &&
2057 "Incomplete array type is not valid");
2058 continue;
2059 }
John McCallbc83b3f2010-05-20 23:23:51 +00002060 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002061 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002062 }
Mike Stump11289f42009-09-09 15:08:12 +00002063
John McCallbc83b3f2010-05-20 23:23:51 +00002064 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002065 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002066 Constructor->setNumCtorInitializers(NumInitializers);
2067 CXXCtorInitializer **baseOrMemberInitializers =
2068 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002069 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002070 NumInitializers * sizeof(CXXCtorInitializer*));
2071 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002072
John McCalla6309952010-03-16 21:39:52 +00002073 // Constructors implicitly reference the base and member
2074 // destructors.
2075 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2076 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002077 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002078
2079 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002080}
2081
Eli Friedman952c15d2009-07-21 19:28:10 +00002082static void *GetKeyForTopLevelField(FieldDecl *Field) {
2083 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002085 if (RT->getDecl()->isAnonymousStructOrUnion())
2086 return static_cast<void *>(RT->getDecl());
2087 }
2088 return static_cast<void *>(Field);
2089}
2090
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002091static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002092 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002093}
2094
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002095static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002096 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002097 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002098 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002099
Eli Friedman952c15d2009-07-21 19:28:10 +00002100 // For fields injected into the class via declaration of an anonymous union,
2101 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002102 FieldDecl *Field = Member->getAnyMember();
2103
John McCall23eebd92010-04-10 09:28:51 +00002104 // If the field is a member of an anonymous struct or union, our key
2105 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002106 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002107 if (RD->isAnonymousStructOrUnion()) {
2108 while (true) {
2109 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2110 if (Parent->isAnonymousStructOrUnion())
2111 RD = Parent;
2112 else
2113 break;
2114 }
2115
Anders Carlsson83ac3122010-03-30 16:19:37 +00002116 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Anders Carlssona942dcd2010-03-30 15:39:27 +00002119 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002120}
2121
Anders Carlssone857b292010-04-02 03:37:03 +00002122static void
2123DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002124 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002125 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002126 unsigned NumInits) {
2127 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002128 return;
Mike Stump11289f42009-09-09 15:08:12 +00002129
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002130 // Don't check initializers order unless the warning is enabled at the
2131 // location of at least one initializer.
2132 bool ShouldCheckOrder = false;
2133 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002134 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002135 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2136 Init->getSourceLocation())
2137 != Diagnostic::Ignored) {
2138 ShouldCheckOrder = true;
2139 break;
2140 }
2141 }
2142 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002143 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002144
John McCallbb7b6582010-04-10 07:37:23 +00002145 // Build the list of bases and members in the order that they'll
2146 // actually be initialized. The explicit initializers should be in
2147 // this same order but may be missing things.
2148 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002150 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2151
John McCallbb7b6582010-04-10 07:37:23 +00002152 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002153 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002154 ClassDecl->vbases_begin(),
2155 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002156 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002157
John McCallbb7b6582010-04-10 07:37:23 +00002158 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002159 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002160 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002161 if (Base->isVirtual())
2162 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002163 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
John McCallbb7b6582010-04-10 07:37:23 +00002166 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002167 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2168 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002169 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002170
John McCallbb7b6582010-04-10 07:37:23 +00002171 unsigned NumIdealInits = IdealInitKeys.size();
2172 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002173
Alexis Hunt1d792652011-01-08 20:30:50 +00002174 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002175 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002176 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002177 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002178
2179 // Scan forward to try to find this initializer in the idealized
2180 // initializers list.
2181 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2182 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002183 break;
John McCallbb7b6582010-04-10 07:37:23 +00002184
2185 // If we didn't find this initializer, it must be because we
2186 // scanned past it on a previous iteration. That can only
2187 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002188 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002189 Sema::SemaDiagnosticBuilder D =
2190 SemaRef.Diag(PrevInit->getSourceLocation(),
2191 diag::warn_initializer_out_of_order);
2192
Francois Pichetd583da02010-12-04 09:14:42 +00002193 if (PrevInit->isAnyMemberInitializer())
2194 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002195 else
2196 D << 1 << PrevInit->getBaseClassInfo()->getType();
2197
Francois Pichetd583da02010-12-04 09:14:42 +00002198 if (Init->isAnyMemberInitializer())
2199 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002200 else
2201 D << 1 << Init->getBaseClassInfo()->getType();
2202
2203 // Move back to the initializer's location in the ideal list.
2204 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2205 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002206 break;
John McCallbb7b6582010-04-10 07:37:23 +00002207
2208 assert(IdealIndex != NumIdealInits &&
2209 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002210 }
John McCallbb7b6582010-04-10 07:37:23 +00002211
2212 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002213 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002214}
2215
John McCall23eebd92010-04-10 09:28:51 +00002216namespace {
2217bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002218 CXXCtorInitializer *Init,
2219 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002220 if (!PrevInit) {
2221 PrevInit = Init;
2222 return false;
2223 }
2224
2225 if (FieldDecl *Field = Init->getMember())
2226 S.Diag(Init->getSourceLocation(),
2227 diag::err_multiple_mem_initialization)
2228 << Field->getDeclName()
2229 << Init->getSourceRange();
2230 else {
John McCall424cec92011-01-19 06:33:43 +00002231 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002232 assert(BaseClass && "neither field nor base");
2233 S.Diag(Init->getSourceLocation(),
2234 diag::err_multiple_base_initialization)
2235 << QualType(BaseClass, 0)
2236 << Init->getSourceRange();
2237 }
2238 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2239 << 0 << PrevInit->getSourceRange();
2240
2241 return true;
2242}
2243
Alexis Hunt1d792652011-01-08 20:30:50 +00002244typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002245typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2246
2247bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002248 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002249 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002250 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002251 RecordDecl *Parent = Field->getParent();
2252 if (!Parent->isAnonymousStructOrUnion())
2253 return false;
2254
2255 NamedDecl *Child = Field;
2256 do {
2257 if (Parent->isUnion()) {
2258 UnionEntry &En = Unions[Parent];
2259 if (En.first && En.first != Child) {
2260 S.Diag(Init->getSourceLocation(),
2261 diag::err_multiple_mem_union_initialization)
2262 << Field->getDeclName()
2263 << Init->getSourceRange();
2264 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2265 << 0 << En.second->getSourceRange();
2266 return true;
2267 } else if (!En.first) {
2268 En.first = Child;
2269 En.second = Init;
2270 }
2271 }
2272
2273 Child = Parent;
2274 Parent = cast<RecordDecl>(Parent->getDeclContext());
2275 } while (Parent->isAnonymousStructOrUnion());
2276
2277 return false;
2278}
2279}
2280
Anders Carlssone857b292010-04-02 03:37:03 +00002281/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002282void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002283 SourceLocation ColonLoc,
2284 MemInitTy **meminits, unsigned NumMemInits,
2285 bool AnyErrors) {
2286 if (!ConstructorDecl)
2287 return;
2288
2289 AdjustDeclIfTemplate(ConstructorDecl);
2290
2291 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002292 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002293
2294 if (!Constructor) {
2295 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2296 return;
2297 }
2298
Alexis Hunt1d792652011-01-08 20:30:50 +00002299 CXXCtorInitializer **MemInits =
2300 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002301
2302 // Mapping for the duplicate initializers check.
2303 // For member initializers, this is keyed with a FieldDecl*.
2304 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002305 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002306
2307 // Mapping for the inconsistent anonymous-union initializers check.
2308 RedundantUnionMap MemberUnions;
2309
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002310 bool HadError = false;
2311 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002312 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002313
Abramo Bagnara341d7832010-05-26 18:09:23 +00002314 // Set the source order index.
2315 Init->setSourceOrder(i);
2316
Francois Pichetd583da02010-12-04 09:14:42 +00002317 if (Init->isAnyMemberInitializer()) {
2318 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002319 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2320 CheckRedundantUnionInit(*this, Init, MemberUnions))
2321 HadError = true;
2322 } else {
2323 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2324 if (CheckRedundantInit(*this, Init, Members[Key]))
2325 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002326 }
Anders Carlssone857b292010-04-02 03:37:03 +00002327 }
2328
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002329 if (HadError)
2330 return;
2331
Anders Carlssone857b292010-04-02 03:37:03 +00002332 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002333
Alexis Hunt1d792652011-01-08 20:30:50 +00002334 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002335}
2336
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002337void
John McCalla6309952010-03-16 21:39:52 +00002338Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2339 CXXRecordDecl *ClassDecl) {
2340 // Ignore dependent contexts.
2341 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002342 return;
John McCall1064d7e2010-03-16 05:22:47 +00002343
2344 // FIXME: all the access-control diagnostics are positioned on the
2345 // field/base declaration. That's probably good; that said, the
2346 // user might reasonably want to know why the destructor is being
2347 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002348
Anders Carlssondee9a302009-11-17 04:44:12 +00002349 // Non-static data members.
2350 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2351 E = ClassDecl->field_end(); I != E; ++I) {
2352 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002353 if (Field->isInvalidDecl())
2354 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002355 QualType FieldType = Context.getBaseElementType(Field->getType());
2356
2357 const RecordType* RT = FieldType->getAs<RecordType>();
2358 if (!RT)
2359 continue;
2360
2361 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2362 if (FieldClassDecl->hasTrivialDestructor())
2363 continue;
2364
Douglas Gregore71edda2010-07-01 22:47:18 +00002365 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002366 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002367 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002368 << Field->getDeclName()
2369 << FieldType);
2370
John McCalla6309952010-03-16 21:39:52 +00002371 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002372 }
2373
John McCall1064d7e2010-03-16 05:22:47 +00002374 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2375
Anders Carlssondee9a302009-11-17 04:44:12 +00002376 // Bases.
2377 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2378 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002379 // Bases are always records in a well-formed non-dependent class.
2380 const RecordType *RT = Base->getType()->getAs<RecordType>();
2381
2382 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002383 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002384 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002385
2386 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002387 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002388 if (BaseClassDecl->hasTrivialDestructor())
2389 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002390
Douglas Gregore71edda2010-07-01 22:47:18 +00002391 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002392
2393 // FIXME: caret should be on the start of the class name
2394 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002395 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002396 << Base->getType()
2397 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002398
John McCalla6309952010-03-16 21:39:52 +00002399 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002400 }
2401
2402 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002403 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2404 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002405
2406 // Bases are always records in a well-formed non-dependent class.
2407 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2408
2409 // Ignore direct virtual bases.
2410 if (DirectVirtualBases.count(RT))
2411 continue;
2412
Anders Carlssondee9a302009-11-17 04:44:12 +00002413 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002414 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002415 if (BaseClassDecl->hasTrivialDestructor())
2416 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002417
Douglas Gregore71edda2010-07-01 22:47:18 +00002418 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002419 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002420 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002421 << VBase->getType());
2422
John McCalla6309952010-03-16 21:39:52 +00002423 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002424 }
2425}
2426
John McCall48871652010-08-21 09:40:31 +00002427void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002428 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002429 return;
Mike Stump11289f42009-09-09 15:08:12 +00002430
Mike Stump11289f42009-09-09 15:08:12 +00002431 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002432 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002433 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002434}
2435
Mike Stump11289f42009-09-09 15:08:12 +00002436bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002437 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002438 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002439 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002440 else
John McCall02db245d2010-08-18 09:41:07 +00002441 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002442}
2443
Anders Carlssoneabf7702009-08-27 00:13:57 +00002444bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002445 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002446 if (!getLangOptions().CPlusPlus)
2447 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002448
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002449 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002450 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002451
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002452 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002453 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002454 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002455 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002456
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002457 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002458 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002461 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002462 if (!RT)
2463 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002464
John McCall67da35c2010-02-04 22:26:26 +00002465 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002466
John McCall02db245d2010-08-18 09:41:07 +00002467 // We can't answer whether something is abstract until it has a
2468 // definition. If it's currently being defined, we'll walk back
2469 // over all the declarations when we have a full definition.
2470 const CXXRecordDecl *Def = RD->getDefinition();
2471 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002472 return false;
2473
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002474 if (!RD->isAbstract())
2475 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002476
Anders Carlssoneabf7702009-08-27 00:13:57 +00002477 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002478 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002479
John McCall02db245d2010-08-18 09:41:07 +00002480 return true;
2481}
2482
2483void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2484 // Check if we've already emitted the list of pure virtual functions
2485 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002486 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002487 return;
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregor4165bd62010-03-23 23:47:56 +00002489 CXXFinalOverriderMap FinalOverriders;
2490 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Anders Carlssona2f74f32010-06-03 01:00:02 +00002492 // Keep a set of seen pure methods so we won't diagnose the same method
2493 // more than once.
2494 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2495
Douglas Gregor4165bd62010-03-23 23:47:56 +00002496 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2497 MEnd = FinalOverriders.end();
2498 M != MEnd;
2499 ++M) {
2500 for (OverridingMethods::iterator SO = M->second.begin(),
2501 SOEnd = M->second.end();
2502 SO != SOEnd; ++SO) {
2503 // C++ [class.abstract]p4:
2504 // A class is abstract if it contains or inherits at least one
2505 // pure virtual function for which the final overrider is pure
2506 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002507
Douglas Gregor4165bd62010-03-23 23:47:56 +00002508 //
2509 if (SO->second.size() != 1)
2510 continue;
2511
2512 if (!SO->second.front().Method->isPure())
2513 continue;
2514
Anders Carlssona2f74f32010-06-03 01:00:02 +00002515 if (!SeenPureMethods.insert(SO->second.front().Method))
2516 continue;
2517
Douglas Gregor4165bd62010-03-23 23:47:56 +00002518 Diag(SO->second.front().Method->getLocation(),
2519 diag::note_pure_virtual_function)
2520 << SO->second.front().Method->getDeclName();
2521 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002522 }
2523
2524 if (!PureVirtualClassDiagSet)
2525 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2526 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002527}
2528
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002529namespace {
John McCall02db245d2010-08-18 09:41:07 +00002530struct AbstractUsageInfo {
2531 Sema &S;
2532 CXXRecordDecl *Record;
2533 CanQualType AbstractType;
2534 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002535
John McCall02db245d2010-08-18 09:41:07 +00002536 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2537 : S(S), Record(Record),
2538 AbstractType(S.Context.getCanonicalType(
2539 S.Context.getTypeDeclType(Record))),
2540 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002541
John McCall02db245d2010-08-18 09:41:07 +00002542 void DiagnoseAbstractType() {
2543 if (Invalid) return;
2544 S.DiagnoseAbstractType(Record);
2545 Invalid = true;
2546 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002547
John McCall02db245d2010-08-18 09:41:07 +00002548 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2549};
2550
2551struct CheckAbstractUsage {
2552 AbstractUsageInfo &Info;
2553 const NamedDecl *Ctx;
2554
2555 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2556 : Info(Info), Ctx(Ctx) {}
2557
2558 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2559 switch (TL.getTypeLocClass()) {
2560#define ABSTRACT_TYPELOC(CLASS, PARENT)
2561#define TYPELOC(CLASS, PARENT) \
2562 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2563#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002564 }
John McCall02db245d2010-08-18 09:41:07 +00002565 }
Mike Stump11289f42009-09-09 15:08:12 +00002566
John McCall02db245d2010-08-18 09:41:07 +00002567 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2568 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2569 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2570 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2571 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002572 }
John McCall02db245d2010-08-18 09:41:07 +00002573 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002574
John McCall02db245d2010-08-18 09:41:07 +00002575 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2576 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578
John McCall02db245d2010-08-18 09:41:07 +00002579 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2580 // Visit the type parameters from a permissive context.
2581 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2582 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2583 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2584 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2585 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2586 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002587 }
John McCall02db245d2010-08-18 09:41:07 +00002588 }
Mike Stump11289f42009-09-09 15:08:12 +00002589
John McCall02db245d2010-08-18 09:41:07 +00002590 // Visit pointee types from a permissive context.
2591#define CheckPolymorphic(Type) \
2592 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2593 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2594 }
2595 CheckPolymorphic(PointerTypeLoc)
2596 CheckPolymorphic(ReferenceTypeLoc)
2597 CheckPolymorphic(MemberPointerTypeLoc)
2598 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002599
John McCall02db245d2010-08-18 09:41:07 +00002600 /// Handle all the types we haven't given a more specific
2601 /// implementation for above.
2602 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2603 // Every other kind of type that we haven't called out already
2604 // that has an inner type is either (1) sugar or (2) contains that
2605 // inner type in some way as a subobject.
2606 if (TypeLoc Next = TL.getNextTypeLoc())
2607 return Visit(Next, Sel);
2608
2609 // If there's no inner type and we're in a permissive context,
2610 // don't diagnose.
2611 if (Sel == Sema::AbstractNone) return;
2612
2613 // Check whether the type matches the abstract type.
2614 QualType T = TL.getType();
2615 if (T->isArrayType()) {
2616 Sel = Sema::AbstractArrayType;
2617 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002618 }
John McCall02db245d2010-08-18 09:41:07 +00002619 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2620 if (CT != Info.AbstractType) return;
2621
2622 // It matched; do some magic.
2623 if (Sel == Sema::AbstractArrayType) {
2624 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2625 << T << TL.getSourceRange();
2626 } else {
2627 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2628 << Sel << T << TL.getSourceRange();
2629 }
2630 Info.DiagnoseAbstractType();
2631 }
2632};
2633
2634void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2635 Sema::AbstractDiagSelID Sel) {
2636 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2637}
2638
2639}
2640
2641/// Check for invalid uses of an abstract type in a method declaration.
2642static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2643 CXXMethodDecl *MD) {
2644 // No need to do the check on definitions, which require that
2645 // the return/param types be complete.
2646 if (MD->isThisDeclarationADefinition())
2647 return;
2648
2649 // For safety's sake, just ignore it if we don't have type source
2650 // information. This should never happen for non-implicit methods,
2651 // but...
2652 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2653 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2654}
2655
2656/// Check for invalid uses of an abstract type within a class definition.
2657static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2658 CXXRecordDecl *RD) {
2659 for (CXXRecordDecl::decl_iterator
2660 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2661 Decl *D = *I;
2662 if (D->isImplicit()) continue;
2663
2664 // Methods and method templates.
2665 if (isa<CXXMethodDecl>(D)) {
2666 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2667 } else if (isa<FunctionTemplateDecl>(D)) {
2668 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2669 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2670
2671 // Fields and static variables.
2672 } else if (isa<FieldDecl>(D)) {
2673 FieldDecl *FD = cast<FieldDecl>(D);
2674 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2675 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2676 } else if (isa<VarDecl>(D)) {
2677 VarDecl *VD = cast<VarDecl>(D);
2678 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2679 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2680
2681 // Nested classes and class templates.
2682 } else if (isa<CXXRecordDecl>(D)) {
2683 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2684 } else if (isa<ClassTemplateDecl>(D)) {
2685 CheckAbstractClassUsage(Info,
2686 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2687 }
2688 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002689}
2690
Douglas Gregorc99f1552009-12-03 18:33:45 +00002691/// \brief Perform semantic checks on a class definition that has been
2692/// completing, introducing implicitly-declared members, checking for
2693/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002694void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002695 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002696 return;
2697
John McCall02db245d2010-08-18 09:41:07 +00002698 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2699 AbstractUsageInfo Info(*this, Record);
2700 CheckAbstractClassUsage(Info, Record);
2701 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002702
2703 // If this is not an aggregate type and has no user-declared constructor,
2704 // complain about any non-static data members of reference or const scalar
2705 // type, since they will never get initializers.
2706 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2707 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2708 bool Complained = false;
2709 for (RecordDecl::field_iterator F = Record->field_begin(),
2710 FEnd = Record->field_end();
2711 F != FEnd; ++F) {
2712 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002713 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002714 if (!Complained) {
2715 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2716 << Record->getTagKind() << Record;
2717 Complained = true;
2718 }
2719
2720 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2721 << F->getType()->isReferenceType()
2722 << F->getDeclName();
2723 }
2724 }
2725 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002726
2727 if (Record->isDynamicClass())
2728 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002729
2730 if (Record->getIdentifier()) {
2731 // C++ [class.mem]p13:
2732 // If T is the name of a class, then each of the following shall have a
2733 // name different from T:
2734 // - every member of every anonymous union that is a member of class T.
2735 //
2736 // C++ [class.mem]p14:
2737 // In addition, if class T has a user-declared constructor (12.1), every
2738 // non-static data member of class T shall have a name different from T.
2739 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002740 R.first != R.second; ++R.first) {
2741 NamedDecl *D = *R.first;
2742 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2743 isa<IndirectFieldDecl>(D)) {
2744 Diag(D->getLocation(), diag::err_member_name_of_class)
2745 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002746 break;
2747 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002748 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002749 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002750}
2751
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002752void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002753 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002754 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002755 SourceLocation RBrac,
2756 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002757 if (!TagDecl)
2758 return;
Mike Stump11289f42009-09-09 15:08:12 +00002759
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002760 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002761
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002762 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002763 // strict aliasing violation!
2764 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002765 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002766
Douglas Gregor0be31a22010-07-02 17:43:08 +00002767 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002768 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002769}
2770
Douglas Gregor95755162010-07-01 05:10:53 +00002771namespace {
2772 /// \brief Helper class that collects exception specifications for
2773 /// implicitly-declared special member functions.
2774 class ImplicitExceptionSpecification {
2775 ASTContext &Context;
2776 bool AllowsAllExceptions;
2777 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2778 llvm::SmallVector<QualType, 4> Exceptions;
2779
2780 public:
2781 explicit ImplicitExceptionSpecification(ASTContext &Context)
2782 : Context(Context), AllowsAllExceptions(false) { }
2783
2784 /// \brief Whether the special member function should have any
2785 /// exception specification at all.
2786 bool hasExceptionSpecification() const {
2787 return !AllowsAllExceptions;
2788 }
2789
2790 /// \brief Whether the special member function should have a
2791 /// throw(...) exception specification (a Microsoft extension).
2792 bool hasAnyExceptionSpecification() const {
2793 return false;
2794 }
2795
2796 /// \brief The number of exceptions in the exception specification.
2797 unsigned size() const { return Exceptions.size(); }
2798
2799 /// \brief The set of exceptions in the exception specification.
2800 const QualType *data() const { return Exceptions.data(); }
2801
2802 /// \brief Note that
2803 void CalledDecl(CXXMethodDecl *Method) {
2804 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002805 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002806 return;
2807
2808 const FunctionProtoType *Proto
2809 = Method->getType()->getAs<FunctionProtoType>();
2810
2811 // If this function can throw any exceptions, make a note of that.
2812 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2813 AllowsAllExceptions = true;
2814 ExceptionsSeen.clear();
2815 Exceptions.clear();
2816 return;
2817 }
2818
2819 // Record the exceptions in this function's exception specification.
2820 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2821 EEnd = Proto->exception_end();
2822 E != EEnd; ++E)
2823 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2824 Exceptions.push_back(*E);
2825 }
2826 };
2827}
2828
2829
Douglas Gregor05379422008-11-03 17:51:48 +00002830/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2831/// special functions, such as the default constructor, copy
2832/// constructor, or destructor, to the given C++ class (C++
2833/// [special]p1). This routine can only be executed just before the
2834/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002835void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002836 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002837 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002838
Douglas Gregor54be3392010-07-01 17:57:27 +00002839 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002840 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002841
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002842 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2843 ++ASTContext::NumImplicitCopyAssignmentOperators;
2844
2845 // If we have a dynamic class, then the copy assignment operator may be
2846 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2847 // it shows up in the right place in the vtable and that we diagnose
2848 // problems with the implicit exception specification.
2849 if (ClassDecl->isDynamicClass())
2850 DeclareImplicitCopyAssignment(ClassDecl);
2851 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002852
Douglas Gregor7454c562010-07-02 20:37:36 +00002853 if (!ClassDecl->hasUserDeclaredDestructor()) {
2854 ++ASTContext::NumImplicitDestructors;
2855
2856 // If we have a dynamic class, then the destructor may be virtual, so we
2857 // have to declare the destructor immediately. This ensures that, e.g., it
2858 // shows up in the right place in the vtable and that we diagnose problems
2859 // with the implicit exception specification.
2860 if (ClassDecl->isDynamicClass())
2861 DeclareImplicitDestructor(ClassDecl);
2862 }
Douglas Gregor05379422008-11-03 17:51:48 +00002863}
2864
John McCall48871652010-08-21 09:40:31 +00002865void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002866 if (!D)
2867 return;
2868
2869 TemplateParameterList *Params = 0;
2870 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2871 Params = Template->getTemplateParameters();
2872 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2873 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2874 Params = PartialSpec->getTemplateParameters();
2875 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002876 return;
2877
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002878 for (TemplateParameterList::iterator Param = Params->begin(),
2879 ParamEnd = Params->end();
2880 Param != ParamEnd; ++Param) {
2881 NamedDecl *Named = cast<NamedDecl>(*Param);
2882 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002883 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002884 IdResolver.AddDecl(Named);
2885 }
2886 }
2887}
2888
John McCall48871652010-08-21 09:40:31 +00002889void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002890 if (!RecordD) return;
2891 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002892 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002893 PushDeclContext(S, Record);
2894}
2895
John McCall48871652010-08-21 09:40:31 +00002896void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002897 if (!RecordD) return;
2898 PopDeclContext();
2899}
2900
Douglas Gregor4d87df52008-12-16 21:30:33 +00002901/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2902/// parsing a top-level (non-nested) C++ class, and we are now
2903/// parsing those parts of the given Method declaration that could
2904/// not be parsed earlier (C++ [class.mem]p2), such as default
2905/// arguments. This action should enter the scope of the given
2906/// Method declaration as if we had just parsed the qualified method
2907/// name. However, it should not bring the parameters into scope;
2908/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002909void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002910}
2911
2912/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2913/// C++ method declaration. We're (re-)introducing the given
2914/// function parameter into scope for use in parsing later parts of
2915/// the method declaration. For example, we could see an
2916/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002917void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002918 if (!ParamD)
2919 return;
Mike Stump11289f42009-09-09 15:08:12 +00002920
John McCall48871652010-08-21 09:40:31 +00002921 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002922
2923 // If this parameter has an unparsed default argument, clear it out
2924 // to make way for the parsed default argument.
2925 if (Param->hasUnparsedDefaultArg())
2926 Param->setDefaultArg(0);
2927
John McCall48871652010-08-21 09:40:31 +00002928 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002929 if (Param->getDeclName())
2930 IdResolver.AddDecl(Param);
2931}
2932
2933/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2934/// processing the delayed method declaration for Method. The method
2935/// declaration is now considered finished. There may be a separate
2936/// ActOnStartOfFunctionDef action later (not necessarily
2937/// immediately!) for this method, if it was also defined inside the
2938/// class body.
John McCall48871652010-08-21 09:40:31 +00002939void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002940 if (!MethodD)
2941 return;
Mike Stump11289f42009-09-09 15:08:12 +00002942
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002943 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002944
John McCall48871652010-08-21 09:40:31 +00002945 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002946
2947 // Now that we have our default arguments, check the constructor
2948 // again. It could produce additional diagnostics or affect whether
2949 // the class has implicitly-declared destructors, among other
2950 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002951 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2952 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002953
2954 // Check the default arguments, which we may have added.
2955 if (!Method->isInvalidDecl())
2956 CheckCXXDefaultArguments(Method);
2957}
2958
Douglas Gregor831c93f2008-11-05 20:51:48 +00002959/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002960/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002961/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002962/// emit diagnostics and set the invalid bit to true. In any case, the type
2963/// will be updated to reflect a well-formed type for the constructor and
2964/// returned.
2965QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002966 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002967 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002968
2969 // C++ [class.ctor]p3:
2970 // A constructor shall not be virtual (10.3) or static (9.4). A
2971 // constructor can be invoked for a const, volatile or const
2972 // volatile object. A constructor shall not be declared const,
2973 // volatile, or const volatile (9.3.2).
2974 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002975 if (!D.isInvalidType())
2976 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2977 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2978 << SourceRange(D.getIdentifierLoc());
2979 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002980 }
John McCall8e7d6562010-08-26 03:08:43 +00002981 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002982 if (!D.isInvalidType())
2983 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2984 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2985 << SourceRange(D.getIdentifierLoc());
2986 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002987 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002988 }
Mike Stump11289f42009-09-09 15:08:12 +00002989
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002990 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002991 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002992 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2994 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002995 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002996 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2997 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002998 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3000 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003001 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
Douglas Gregor831c93f2008-11-05 20:51:48 +00003004 // Rebuild the function type "R" without any type qualifiers (in
3005 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003006 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003007 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003008 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3009 return R;
3010
3011 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3012 EPI.TypeQuals = 0;
3013
Chris Lattner38378bf2009-04-25 08:28:21 +00003014 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003015 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003016}
3017
Douglas Gregor4d87df52008-12-16 21:30:33 +00003018/// CheckConstructor - Checks a fully-formed constructor for
3019/// well-formedness, issuing any diagnostics required. Returns true if
3020/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003021void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003022 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003023 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3024 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003025 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003026
3027 // C++ [class.copy]p3:
3028 // A declaration of a constructor for a class X is ill-formed if
3029 // its first parameter is of type (optionally cv-qualified) X and
3030 // either there are no other parameters or else all other
3031 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003032 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003033 ((Constructor->getNumParams() == 1) ||
3034 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003035 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3036 Constructor->getTemplateSpecializationKind()
3037 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003038 QualType ParamType = Constructor->getParamDecl(0)->getType();
3039 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3040 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003041 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003042 const char *ConstRef
3043 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3044 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003045 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003046 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003047
3048 // FIXME: Rather that making the constructor invalid, we should endeavor
3049 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003050 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003051 }
3052 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003053}
3054
John McCalldeb646e2010-08-04 01:04:25 +00003055/// CheckDestructor - Checks a fully-formed destructor definition for
3056/// well-formedness, issuing any diagnostics required. Returns true
3057/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003058bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003059 CXXRecordDecl *RD = Destructor->getParent();
3060
3061 if (Destructor->isVirtual()) {
3062 SourceLocation Loc;
3063
3064 if (!Destructor->isImplicit())
3065 Loc = Destructor->getLocation();
3066 else
3067 Loc = RD->getLocation();
3068
3069 // If we have a virtual destructor, look up the deallocation function
3070 FunctionDecl *OperatorDelete = 0;
3071 DeclarationName Name =
3072 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003073 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003074 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003075
3076 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003077
3078 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003079 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003080
3081 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003082}
3083
Mike Stump11289f42009-09-09 15:08:12 +00003084static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003085FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3086 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3087 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003088 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003089}
3090
Douglas Gregor831c93f2008-11-05 20:51:48 +00003091/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3092/// the well-formednes of the destructor declarator @p D with type @p
3093/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003094/// emit diagnostics and set the declarator to invalid. Even if this happens,
3095/// will be updated to reflect a well-formed type for the destructor and
3096/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003097QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003098 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003099 // C++ [class.dtor]p1:
3100 // [...] A typedef-name that names a class is a class-name
3101 // (7.1.3); however, a typedef-name that names a class shall not
3102 // be used as the identifier in the declarator for a destructor
3103 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003104 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003105 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003106 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003107 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003108
3109 // C++ [class.dtor]p2:
3110 // A destructor is used to destroy objects of its class type. A
3111 // destructor takes no parameters, and no return type can be
3112 // specified for it (not even void). The address of a destructor
3113 // shall not be taken. A destructor shall not be static. A
3114 // destructor can be invoked for a const, volatile or const
3115 // volatile object. A destructor shall not be declared const,
3116 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003117 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003118 if (!D.isInvalidType())
3119 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3120 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003121 << SourceRange(D.getIdentifierLoc())
3122 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3123
John McCall8e7d6562010-08-26 03:08:43 +00003124 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003125 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003126 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003127 // Destructors don't have return types, but the parser will
3128 // happily parse something like:
3129 //
3130 // class X {
3131 // float ~X();
3132 // };
3133 //
3134 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003135 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3136 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3137 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003138 }
Mike Stump11289f42009-09-09 15:08:12 +00003139
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003140 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003141 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003142 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003143 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3144 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003145 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003146 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3147 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003148 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003149 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3150 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003151 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003152 }
3153
3154 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003155 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003156 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3157
3158 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003159 FTI.freeArgs();
3160 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003161 }
3162
Mike Stump11289f42009-09-09 15:08:12 +00003163 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003164 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003165 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003166 D.setInvalidType();
3167 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003168
3169 // Rebuild the function type "R" without any type qualifiers or
3170 // parameters (in case any of the errors above fired) and with
3171 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003172 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003173 if (!D.isInvalidType())
3174 return R;
3175
Douglas Gregor95755162010-07-01 05:10:53 +00003176 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003177 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3178 EPI.Variadic = false;
3179 EPI.TypeQuals = 0;
3180 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003181}
3182
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003183/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3184/// well-formednes of the conversion function declarator @p D with
3185/// type @p R. If there are any errors in the declarator, this routine
3186/// will emit diagnostics and return true. Otherwise, it will return
3187/// false. Either way, the type @p R will be updated to reflect a
3188/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003189void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003190 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003191 // C++ [class.conv.fct]p1:
3192 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003193 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003194 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003195 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003196 if (!D.isInvalidType())
3197 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3198 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3199 << SourceRange(D.getIdentifierLoc());
3200 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003201 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003202 }
John McCall212fa2e2010-04-13 00:04:31 +00003203
3204 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3205
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003206 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003207 // Conversion functions don't have return types, but the parser will
3208 // happily parse something like:
3209 //
3210 // class X {
3211 // float operator bool();
3212 // };
3213 //
3214 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003215 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3216 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3217 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003218 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003219 }
3220
John McCall212fa2e2010-04-13 00:04:31 +00003221 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3222
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003223 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003224 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003225 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3226
3227 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003228 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003229 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003230 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003231 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003232 D.setInvalidType();
3233 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003234
John McCall212fa2e2010-04-13 00:04:31 +00003235 // Diagnose "&operator bool()" and other such nonsense. This
3236 // is actually a gcc extension which we don't support.
3237 if (Proto->getResultType() != ConvType) {
3238 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3239 << Proto->getResultType();
3240 D.setInvalidType();
3241 ConvType = Proto->getResultType();
3242 }
3243
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003244 // C++ [class.conv.fct]p4:
3245 // The conversion-type-id shall not represent a function type nor
3246 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003247 if (ConvType->isArrayType()) {
3248 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3249 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003250 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003251 } else if (ConvType->isFunctionType()) {
3252 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3253 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003254 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003255 }
3256
3257 // Rebuild the function type "R" without any parameters (in case any
3258 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003259 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003260 if (D.isInvalidType())
3261 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003262
Douglas Gregor5fb53972009-01-14 15:45:31 +00003263 // C++0x explicit conversion operators.
3264 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003265 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003266 diag::warn_explicit_conversion_functions)
3267 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003268}
3269
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003270/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3271/// the declaration of the given C++ conversion function. This routine
3272/// is responsible for recording the conversion function in the C++
3273/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003274Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003275 assert(Conversion && "Expected to receive a conversion function declaration");
3276
Douglas Gregor4287b372008-12-12 08:25:50 +00003277 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003278
3279 // Make sure we aren't redeclaring the conversion function.
3280 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003281
3282 // C++ [class.conv.fct]p1:
3283 // [...] A conversion function is never used to convert a
3284 // (possibly cv-qualified) object to the (possibly cv-qualified)
3285 // same object type (or a reference to it), to a (possibly
3286 // cv-qualified) base class of that type (or a reference to it),
3287 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003288 // FIXME: Suppress this warning if the conversion function ends up being a
3289 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003290 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003291 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003292 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003293 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003294 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3295 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003296 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003297 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003298 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3299 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003300 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003301 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003302 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003303 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003304 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003305 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003306 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003307 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003308 }
3309
Douglas Gregor457104e2010-09-29 04:25:11 +00003310 if (FunctionTemplateDecl *ConversionTemplate
3311 = Conversion->getDescribedFunctionTemplate())
3312 return ConversionTemplate;
3313
John McCall48871652010-08-21 09:40:31 +00003314 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003315}
3316
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003317//===----------------------------------------------------------------------===//
3318// Namespace Handling
3319//===----------------------------------------------------------------------===//
3320
John McCallb1be5232010-08-26 09:15:37 +00003321
3322
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003323/// ActOnStartNamespaceDef - This is called at the start of a namespace
3324/// definition.
John McCall48871652010-08-21 09:40:31 +00003325Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003326 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003327 SourceLocation IdentLoc,
3328 IdentifierInfo *II,
3329 SourceLocation LBrace,
3330 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003331 // anonymous namespace starts at its left brace
3332 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3333 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003334 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003335 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003336
3337 Scope *DeclRegionScope = NamespcScope->getParent();
3338
Anders Carlssona7bcade2010-02-07 01:09:23 +00003339 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3340
John McCall2faf32c2010-12-10 02:59:44 +00003341 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3342 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003343
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003344 if (II) {
3345 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003346 // The identifier in an original-namespace-definition shall not
3347 // have been previously defined in the declarative region in
3348 // which the original-namespace-definition appears. The
3349 // identifier in an original-namespace-definition is the name of
3350 // the namespace. Subsequently in that declarative region, it is
3351 // treated as an original-namespace-name.
3352 //
3353 // Since namespace names are unique in their scope, and we don't
3354 // look through using directives, just
3355 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3356 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003357
Douglas Gregor91f84212008-12-11 16:49:14 +00003358 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3359 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003360 if (Namespc->isInline() != OrigNS->isInline()) {
3361 // inline-ness must match
3362 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3363 << Namespc->isInline();
3364 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3365 Namespc->setInvalidDecl();
3366 // Recover by ignoring the new namespace's inline status.
3367 Namespc->setInline(OrigNS->isInline());
3368 }
3369
Douglas Gregor91f84212008-12-11 16:49:14 +00003370 // Attach this namespace decl to the chain of extended namespace
3371 // definitions.
3372 OrigNS->setNextNamespace(Namespc);
3373 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003374
Mike Stump11289f42009-09-09 15:08:12 +00003375 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003376 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003377 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003378 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003379 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003380 } else if (PrevDecl) {
3381 // This is an invalid name redefinition.
3382 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3383 << Namespc->getDeclName();
3384 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3385 Namespc->setInvalidDecl();
3386 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003387 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003388 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003389 // This is the first "real" definition of the namespace "std", so update
3390 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003391 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003392 // We had already defined a dummy namespace "std". Link this new
3393 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003394 StdNS->setNextNamespace(Namespc);
3395 StdNS->setLocation(IdentLoc);
3396 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003397 }
3398
3399 // Make our StdNamespace cache point at the first real definition of the
3400 // "std" namespace.
3401 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003402 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003403
3404 PushOnScopeChains(Namespc, DeclRegionScope);
3405 } else {
John McCall4fa53422009-10-01 00:25:31 +00003406 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003407 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003408
3409 // Link the anonymous namespace into its parent.
3410 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003411 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003412 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3413 PrevDecl = TU->getAnonymousNamespace();
3414 TU->setAnonymousNamespace(Namespc);
3415 } else {
3416 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3417 PrevDecl = ND->getAnonymousNamespace();
3418 ND->setAnonymousNamespace(Namespc);
3419 }
3420
3421 // Link the anonymous namespace with its previous declaration.
3422 if (PrevDecl) {
3423 assert(PrevDecl->isAnonymousNamespace());
3424 assert(!PrevDecl->getNextNamespace());
3425 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3426 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003427
3428 if (Namespc->isInline() != PrevDecl->isInline()) {
3429 // inline-ness must match
3430 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3431 << Namespc->isInline();
3432 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3433 Namespc->setInvalidDecl();
3434 // Recover by ignoring the new namespace's inline status.
3435 Namespc->setInline(PrevDecl->isInline());
3436 }
John McCall0db42252009-12-16 02:06:49 +00003437 }
John McCall4fa53422009-10-01 00:25:31 +00003438
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003439 CurContext->addDecl(Namespc);
3440
John McCall4fa53422009-10-01 00:25:31 +00003441 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3442 // behaves as if it were replaced by
3443 // namespace unique { /* empty body */ }
3444 // using namespace unique;
3445 // namespace unique { namespace-body }
3446 // where all occurrences of 'unique' in a translation unit are
3447 // replaced by the same identifier and this identifier differs
3448 // from all other identifiers in the entire program.
3449
3450 // We just create the namespace with an empty name and then add an
3451 // implicit using declaration, just like the standard suggests.
3452 //
3453 // CodeGen enforces the "universally unique" aspect by giving all
3454 // declarations semantically contained within an anonymous
3455 // namespace internal linkage.
3456
John McCall0db42252009-12-16 02:06:49 +00003457 if (!PrevDecl) {
3458 UsingDirectiveDecl* UD
3459 = UsingDirectiveDecl::Create(Context, CurContext,
3460 /* 'using' */ LBrace,
3461 /* 'namespace' */ SourceLocation(),
3462 /* qualifier */ SourceRange(),
3463 /* NNS */ NULL,
3464 /* identifier */ SourceLocation(),
3465 Namespc,
3466 /* Ancestor */ CurContext);
3467 UD->setImplicit();
3468 CurContext->addDecl(UD);
3469 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003470 }
3471
3472 // Although we could have an invalid decl (i.e. the namespace name is a
3473 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003474 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3475 // for the namespace has the declarations that showed up in that particular
3476 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003477 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003478 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003479}
3480
Sebastian Redla6602e92009-11-23 15:34:23 +00003481/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3482/// is a namespace alias, returns the namespace it points to.
3483static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3484 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3485 return AD->getNamespace();
3486 return dyn_cast_or_null<NamespaceDecl>(D);
3487}
3488
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003489/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3490/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003491void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003492 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3493 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3494 Namespc->setRBracLoc(RBrace);
3495 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003496 if (Namespc->hasAttr<VisibilityAttr>())
3497 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003498}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003499
John McCall28a0cf72010-08-25 07:42:41 +00003500CXXRecordDecl *Sema::getStdBadAlloc() const {
3501 return cast_or_null<CXXRecordDecl>(
3502 StdBadAlloc.get(Context.getExternalSource()));
3503}
3504
3505NamespaceDecl *Sema::getStdNamespace() const {
3506 return cast_or_null<NamespaceDecl>(
3507 StdNamespace.get(Context.getExternalSource()));
3508}
3509
Douglas Gregorcdf87022010-06-29 17:53:46 +00003510/// \brief Retrieve the special "std" namespace, which may require us to
3511/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003512NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003513 if (!StdNamespace) {
3514 // The "std" namespace has not yet been defined, so build one implicitly.
3515 StdNamespace = NamespaceDecl::Create(Context,
3516 Context.getTranslationUnitDecl(),
3517 SourceLocation(),
3518 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003519 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003520 }
3521
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003522 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003523}
3524
John McCall48871652010-08-21 09:40:31 +00003525Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003526 SourceLocation UsingLoc,
3527 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003528 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003529 SourceLocation IdentLoc,
3530 IdentifierInfo *NamespcName,
3531 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003532 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3533 assert(NamespcName && "Invalid NamespcName.");
3534 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003535
3536 // This can only happen along a recovery path.
3537 while (S->getFlags() & Scope::TemplateParamScope)
3538 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003539 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003540
Douglas Gregor889ceb72009-02-03 19:21:40 +00003541 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003542 NestedNameSpecifier *Qualifier = 0;
3543 if (SS.isSet())
3544 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3545
Douglas Gregor34074322009-01-14 22:20:51 +00003546 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003547 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3548 LookupParsedName(R, S, &SS);
3549 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003550 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003551
Douglas Gregorcdf87022010-06-29 17:53:46 +00003552 if (R.empty()) {
3553 // Allow "using namespace std;" or "using namespace ::std;" even if
3554 // "std" hasn't been defined yet, for GCC compatibility.
3555 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3556 NamespcName->isStr("std")) {
3557 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003558 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003559 R.resolveKind();
3560 }
3561 // Otherwise, attempt typo correction.
3562 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3563 CTC_NoKeywords, 0)) {
3564 if (R.getAsSingle<NamespaceDecl>() ||
3565 R.getAsSingle<NamespaceAliasDecl>()) {
3566 if (DeclContext *DC = computeDeclContext(SS, false))
3567 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3568 << NamespcName << DC << Corrected << SS.getRange()
3569 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3570 else
3571 Diag(IdentLoc, diag::err_using_directive_suggest)
3572 << NamespcName << Corrected
3573 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3574 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3575 << Corrected;
3576
3577 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003578 } else {
3579 R.clear();
3580 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003581 }
3582 }
3583 }
3584
John McCall9f3059a2009-10-09 21:13:30 +00003585 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003586 NamedDecl *Named = R.getFoundDecl();
3587 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3588 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003589 // C++ [namespace.udir]p1:
3590 // A using-directive specifies that the names in the nominated
3591 // namespace can be used in the scope in which the
3592 // using-directive appears after the using-directive. During
3593 // unqualified name lookup (3.4.1), the names appear as if they
3594 // were declared in the nearest enclosing namespace which
3595 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003596 // namespace. [Note: in this context, "contains" means "contains
3597 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003598
3599 // Find enclosing context containing both using-directive and
3600 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003601 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003602 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3603 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3604 CommonAncestor = CommonAncestor->getParent();
3605
Sebastian Redla6602e92009-11-23 15:34:23 +00003606 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003607 SS.getRange(),
3608 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003609 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003610 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003611 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003612 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003613 }
3614
Douglas Gregor889ceb72009-02-03 19:21:40 +00003615 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003616 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003617}
3618
3619void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3620 // If scope has associated entity, then using directive is at namespace
3621 // or translation unit scope. We add UsingDirectiveDecls, into
3622 // it's lookup structure.
3623 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003624 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003625 else
3626 // Otherwise it is block-sope. using-directives will affect lookup
3627 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003628 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003629}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003630
Douglas Gregorfec52632009-06-20 00:51:54 +00003631
John McCall48871652010-08-21 09:40:31 +00003632Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003633 AccessSpecifier AS,
3634 bool HasUsingKeyword,
3635 SourceLocation UsingLoc,
3636 CXXScopeSpec &SS,
3637 UnqualifiedId &Name,
3638 AttributeList *AttrList,
3639 bool IsTypeName,
3640 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003641 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregor220f4272009-11-04 16:30:06 +00003643 switch (Name.getKind()) {
3644 case UnqualifiedId::IK_Identifier:
3645 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003646 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003647 case UnqualifiedId::IK_ConversionFunctionId:
3648 break;
3649
3650 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003651 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003652 // C++0x inherited constructors.
3653 if (getLangOptions().CPlusPlus0x) break;
3654
Douglas Gregor220f4272009-11-04 16:30:06 +00003655 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3656 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003657 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003658
3659 case UnqualifiedId::IK_DestructorName:
3660 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3661 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003662 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003663
3664 case UnqualifiedId::IK_TemplateId:
3665 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3666 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003667 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003668 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003669
3670 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3671 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003672 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003673 return 0;
John McCall3969e302009-12-08 07:46:18 +00003674
John McCalla0097262009-12-11 02:10:03 +00003675 // Warn about using declarations.
3676 // TODO: store that the declaration was written without 'using' and
3677 // talk about access decls instead of using decls in the
3678 // diagnostics.
3679 if (!HasUsingKeyword) {
3680 UsingLoc = Name.getSourceRange().getBegin();
3681
3682 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003683 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003684 }
3685
Douglas Gregorc4356532010-12-16 00:46:58 +00003686 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3687 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3688 return 0;
3689
John McCall3f746822009-11-17 05:59:44 +00003690 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003691 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003692 /* IsInstantiation */ false,
3693 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003694 if (UD)
3695 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003696
John McCall48871652010-08-21 09:40:31 +00003697 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003698}
3699
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003700/// \brief Determine whether a using declaration considers the given
3701/// declarations as "equivalent", e.g., if they are redeclarations of
3702/// the same entity or are both typedefs of the same type.
3703static bool
3704IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3705 bool &SuppressRedeclaration) {
3706 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3707 SuppressRedeclaration = false;
3708 return true;
3709 }
3710
3711 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3712 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3713 SuppressRedeclaration = true;
3714 return Context.hasSameType(TD1->getUnderlyingType(),
3715 TD2->getUnderlyingType());
3716 }
3717
3718 return false;
3719}
3720
3721
John McCall84d87672009-12-10 09:41:52 +00003722/// Determines whether to create a using shadow decl for a particular
3723/// decl, given the set of decls existing prior to this using lookup.
3724bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3725 const LookupResult &Previous) {
3726 // Diagnose finding a decl which is not from a base class of the
3727 // current class. We do this now because there are cases where this
3728 // function will silently decide not to build a shadow decl, which
3729 // will pre-empt further diagnostics.
3730 //
3731 // We don't need to do this in C++0x because we do the check once on
3732 // the qualifier.
3733 //
3734 // FIXME: diagnose the following if we care enough:
3735 // struct A { int foo; };
3736 // struct B : A { using A::foo; };
3737 // template <class T> struct C : A {};
3738 // template <class T> struct D : C<T> { using B::foo; } // <---
3739 // This is invalid (during instantiation) in C++03 because B::foo
3740 // resolves to the using decl in B, which is not a base class of D<T>.
3741 // We can't diagnose it immediately because C<T> is an unknown
3742 // specialization. The UsingShadowDecl in D<T> then points directly
3743 // to A::foo, which will look well-formed when we instantiate.
3744 // The right solution is to not collapse the shadow-decl chain.
3745 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3746 DeclContext *OrigDC = Orig->getDeclContext();
3747
3748 // Handle enums and anonymous structs.
3749 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3750 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3751 while (OrigRec->isAnonymousStructOrUnion())
3752 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3753
3754 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3755 if (OrigDC == CurContext) {
3756 Diag(Using->getLocation(),
3757 diag::err_using_decl_nested_name_specifier_is_current_class)
3758 << Using->getNestedNameRange();
3759 Diag(Orig->getLocation(), diag::note_using_decl_target);
3760 return true;
3761 }
3762
3763 Diag(Using->getNestedNameRange().getBegin(),
3764 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3765 << Using->getTargetNestedNameDecl()
3766 << cast<CXXRecordDecl>(CurContext)
3767 << Using->getNestedNameRange();
3768 Diag(Orig->getLocation(), diag::note_using_decl_target);
3769 return true;
3770 }
3771 }
3772
3773 if (Previous.empty()) return false;
3774
3775 NamedDecl *Target = Orig;
3776 if (isa<UsingShadowDecl>(Target))
3777 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3778
John McCalla17e83e2009-12-11 02:33:26 +00003779 // If the target happens to be one of the previous declarations, we
3780 // don't have a conflict.
3781 //
3782 // FIXME: but we might be increasing its access, in which case we
3783 // should redeclare it.
3784 NamedDecl *NonTag = 0, *Tag = 0;
3785 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3786 I != E; ++I) {
3787 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003788 bool Result;
3789 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3790 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003791
3792 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3793 }
3794
John McCall84d87672009-12-10 09:41:52 +00003795 if (Target->isFunctionOrFunctionTemplate()) {
3796 FunctionDecl *FD;
3797 if (isa<FunctionTemplateDecl>(Target))
3798 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3799 else
3800 FD = cast<FunctionDecl>(Target);
3801
3802 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003803 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003804 case Ovl_Overload:
3805 return false;
3806
3807 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003808 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003809 break;
3810
3811 // We found a decl with the exact signature.
3812 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003813 // If we're in a record, we want to hide the target, so we
3814 // return true (without a diagnostic) to tell the caller not to
3815 // build a shadow decl.
3816 if (CurContext->isRecord())
3817 return true;
3818
3819 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003820 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003821 break;
3822 }
3823
3824 Diag(Target->getLocation(), diag::note_using_decl_target);
3825 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3826 return true;
3827 }
3828
3829 // Target is not a function.
3830
John McCall84d87672009-12-10 09:41:52 +00003831 if (isa<TagDecl>(Target)) {
3832 // No conflict between a tag and a non-tag.
3833 if (!Tag) return false;
3834
John McCalle29c5cd2009-12-10 19:51:03 +00003835 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003836 Diag(Target->getLocation(), diag::note_using_decl_target);
3837 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3838 return true;
3839 }
3840
3841 // No conflict between a tag and a non-tag.
3842 if (!NonTag) return false;
3843
John McCalle29c5cd2009-12-10 19:51:03 +00003844 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003845 Diag(Target->getLocation(), diag::note_using_decl_target);
3846 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3847 return true;
3848}
3849
John McCall3f746822009-11-17 05:59:44 +00003850/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003851UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003852 UsingDecl *UD,
3853 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003854
3855 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003856 NamedDecl *Target = Orig;
3857 if (isa<UsingShadowDecl>(Target)) {
3858 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3859 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003860 }
3861
3862 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003863 = UsingShadowDecl::Create(Context, CurContext,
3864 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003865 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003866
3867 Shadow->setAccess(UD->getAccess());
3868 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3869 Shadow->setInvalidDecl();
3870
John McCall3f746822009-11-17 05:59:44 +00003871 if (S)
John McCall3969e302009-12-08 07:46:18 +00003872 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003873 else
John McCall3969e302009-12-08 07:46:18 +00003874 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003875
John McCall3969e302009-12-08 07:46:18 +00003876
John McCall84d87672009-12-10 09:41:52 +00003877 return Shadow;
3878}
John McCall3969e302009-12-08 07:46:18 +00003879
John McCall84d87672009-12-10 09:41:52 +00003880/// Hides a using shadow declaration. This is required by the current
3881/// using-decl implementation when a resolvable using declaration in a
3882/// class is followed by a declaration which would hide or override
3883/// one or more of the using decl's targets; for example:
3884///
3885/// struct Base { void foo(int); };
3886/// struct Derived : Base {
3887/// using Base::foo;
3888/// void foo(int);
3889/// };
3890///
3891/// The governing language is C++03 [namespace.udecl]p12:
3892///
3893/// When a using-declaration brings names from a base class into a
3894/// derived class scope, member functions in the derived class
3895/// override and/or hide member functions with the same name and
3896/// parameter types in a base class (rather than conflicting).
3897///
3898/// There are two ways to implement this:
3899/// (1) optimistically create shadow decls when they're not hidden
3900/// by existing declarations, or
3901/// (2) don't create any shadow decls (or at least don't make them
3902/// visible) until we've fully parsed/instantiated the class.
3903/// The problem with (1) is that we might have to retroactively remove
3904/// a shadow decl, which requires several O(n) operations because the
3905/// decl structures are (very reasonably) not designed for removal.
3906/// (2) avoids this but is very fiddly and phase-dependent.
3907void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003908 if (Shadow->getDeclName().getNameKind() ==
3909 DeclarationName::CXXConversionFunctionName)
3910 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3911
John McCall84d87672009-12-10 09:41:52 +00003912 // Remove it from the DeclContext...
3913 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003914
John McCall84d87672009-12-10 09:41:52 +00003915 // ...and the scope, if applicable...
3916 if (S) {
John McCall48871652010-08-21 09:40:31 +00003917 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003918 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003919 }
3920
John McCall84d87672009-12-10 09:41:52 +00003921 // ...and the using decl.
3922 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3923
3924 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003925 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003926}
3927
John McCalle61f2ba2009-11-18 02:36:19 +00003928/// Builds a using declaration.
3929///
3930/// \param IsInstantiation - Whether this call arises from an
3931/// instantiation of an unresolved using declaration. We treat
3932/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003933NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3934 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003935 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003936 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003937 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003938 bool IsInstantiation,
3939 bool IsTypeName,
3940 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003941 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003942 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003943 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003944
Anders Carlssonf038fc22009-08-28 05:49:21 +00003945 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003946
Anders Carlsson59140b32009-08-28 03:16:11 +00003947 if (SS.isEmpty()) {
3948 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003949 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003950 }
Mike Stump11289f42009-09-09 15:08:12 +00003951
John McCall84d87672009-12-10 09:41:52 +00003952 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003953 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003954 ForRedeclaration);
3955 Previous.setHideTags(false);
3956 if (S) {
3957 LookupName(Previous, S);
3958
3959 // It is really dumb that we have to do this.
3960 LookupResult::Filter F = Previous.makeFilter();
3961 while (F.hasNext()) {
3962 NamedDecl *D = F.next();
3963 if (!isDeclInScope(D, CurContext, S))
3964 F.erase();
3965 }
3966 F.done();
3967 } else {
3968 assert(IsInstantiation && "no scope in non-instantiation");
3969 assert(CurContext->isRecord() && "scope not record in instantiation");
3970 LookupQualifiedName(Previous, CurContext);
3971 }
3972
Mike Stump11289f42009-09-09 15:08:12 +00003973 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003974 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3975
John McCall84d87672009-12-10 09:41:52 +00003976 // Check for invalid redeclarations.
3977 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3978 return 0;
3979
3980 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003981 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3982 return 0;
3983
John McCall84c16cf2009-11-12 03:15:40 +00003984 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003985 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003986 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003987 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003988 // FIXME: not all declaration name kinds are legal here
3989 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3990 UsingLoc, TypenameLoc,
3991 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003992 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003993 } else {
3994 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003995 UsingLoc, SS.getRange(),
3996 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003997 }
John McCallb96ec562009-12-04 22:46:56 +00003998 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003999 D = UsingDecl::Create(Context, CurContext,
4000 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00004001 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004002 }
John McCallb96ec562009-12-04 22:46:56 +00004003 D->setAccess(AS);
4004 CurContext->addDecl(D);
4005
4006 if (!LookupContext) return D;
4007 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004008
John McCall0b66eb32010-05-01 00:40:08 +00004009 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004010 UD->setInvalidDecl();
4011 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004012 }
4013
John McCall3969e302009-12-08 07:46:18 +00004014 // Look up the target name.
4015
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004016 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004017
John McCall3969e302009-12-08 07:46:18 +00004018 // Unlike most lookups, we don't always want to hide tag
4019 // declarations: tag names are visible through the using declaration
4020 // even if hidden by ordinary names, *except* in a dependent context
4021 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004022 if (!IsInstantiation)
4023 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004024
John McCall27b18f82009-11-17 02:14:36 +00004025 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004026
John McCall9f3059a2009-10-09 21:13:30 +00004027 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004028 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004029 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004030 UD->setInvalidDecl();
4031 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004032 }
4033
John McCallb96ec562009-12-04 22:46:56 +00004034 if (R.isAmbiguous()) {
4035 UD->setInvalidDecl();
4036 return UD;
4037 }
Mike Stump11289f42009-09-09 15:08:12 +00004038
John McCalle61f2ba2009-11-18 02:36:19 +00004039 if (IsTypeName) {
4040 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004041 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004042 Diag(IdentLoc, diag::err_using_typename_non_type);
4043 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4044 Diag((*I)->getUnderlyingDecl()->getLocation(),
4045 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004046 UD->setInvalidDecl();
4047 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004048 }
4049 } else {
4050 // If we asked for a non-typename and we got a type, error out,
4051 // but only if this is an instantiation of an unresolved using
4052 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004053 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004054 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4055 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004056 UD->setInvalidDecl();
4057 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004058 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004059 }
4060
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004061 // C++0x N2914 [namespace.udecl]p6:
4062 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004063 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004064 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4065 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004066 UD->setInvalidDecl();
4067 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004068 }
Mike Stump11289f42009-09-09 15:08:12 +00004069
John McCall84d87672009-12-10 09:41:52 +00004070 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4071 if (!CheckUsingShadowDecl(UD, *I, Previous))
4072 BuildUsingShadowDecl(S, UD, *I);
4073 }
John McCall3f746822009-11-17 05:59:44 +00004074
4075 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004076}
4077
John McCall84d87672009-12-10 09:41:52 +00004078/// Checks that the given using declaration is not an invalid
4079/// redeclaration. Note that this is checking only for the using decl
4080/// itself, not for any ill-formedness among the UsingShadowDecls.
4081bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4082 bool isTypeName,
4083 const CXXScopeSpec &SS,
4084 SourceLocation NameLoc,
4085 const LookupResult &Prev) {
4086 // C++03 [namespace.udecl]p8:
4087 // C++0x [namespace.udecl]p10:
4088 // A using-declaration is a declaration and can therefore be used
4089 // repeatedly where (and only where) multiple declarations are
4090 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004091 //
John McCall032092f2010-11-29 18:01:58 +00004092 // That's in non-member contexts.
4093 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004094 return false;
4095
4096 NestedNameSpecifier *Qual
4097 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4098
4099 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4100 NamedDecl *D = *I;
4101
4102 bool DTypename;
4103 NestedNameSpecifier *DQual;
4104 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4105 DTypename = UD->isTypeName();
4106 DQual = UD->getTargetNestedNameDecl();
4107 } else if (UnresolvedUsingValueDecl *UD
4108 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4109 DTypename = false;
4110 DQual = UD->getTargetNestedNameSpecifier();
4111 } else if (UnresolvedUsingTypenameDecl *UD
4112 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4113 DTypename = true;
4114 DQual = UD->getTargetNestedNameSpecifier();
4115 } else continue;
4116
4117 // using decls differ if one says 'typename' and the other doesn't.
4118 // FIXME: non-dependent using decls?
4119 if (isTypeName != DTypename) continue;
4120
4121 // using decls differ if they name different scopes (but note that
4122 // template instantiation can cause this check to trigger when it
4123 // didn't before instantiation).
4124 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4125 Context.getCanonicalNestedNameSpecifier(DQual))
4126 continue;
4127
4128 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004129 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004130 return true;
4131 }
4132
4133 return false;
4134}
4135
John McCall3969e302009-12-08 07:46:18 +00004136
John McCallb96ec562009-12-04 22:46:56 +00004137/// Checks that the given nested-name qualifier used in a using decl
4138/// in the current context is appropriately related to the current
4139/// scope. If an error is found, diagnoses it and returns true.
4140bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4141 const CXXScopeSpec &SS,
4142 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004143 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004144
John McCall3969e302009-12-08 07:46:18 +00004145 if (!CurContext->isRecord()) {
4146 // C++03 [namespace.udecl]p3:
4147 // C++0x [namespace.udecl]p8:
4148 // A using-declaration for a class member shall be a member-declaration.
4149
4150 // If we weren't able to compute a valid scope, it must be a
4151 // dependent class scope.
4152 if (!NamedContext || NamedContext->isRecord()) {
4153 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4154 << SS.getRange();
4155 return true;
4156 }
4157
4158 // Otherwise, everything is known to be fine.
4159 return false;
4160 }
4161
4162 // The current scope is a record.
4163
4164 // If the named context is dependent, we can't decide much.
4165 if (!NamedContext) {
4166 // FIXME: in C++0x, we can diagnose if we can prove that the
4167 // nested-name-specifier does not refer to a base class, which is
4168 // still possible in some cases.
4169
4170 // Otherwise we have to conservatively report that things might be
4171 // okay.
4172 return false;
4173 }
4174
4175 if (!NamedContext->isRecord()) {
4176 // Ideally this would point at the last name in the specifier,
4177 // but we don't have that level of source info.
4178 Diag(SS.getRange().getBegin(),
4179 diag::err_using_decl_nested_name_specifier_is_not_class)
4180 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4181 return true;
4182 }
4183
Douglas Gregor7c842292010-12-21 07:41:49 +00004184 if (!NamedContext->isDependentContext() &&
4185 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4186 return true;
4187
John McCall3969e302009-12-08 07:46:18 +00004188 if (getLangOptions().CPlusPlus0x) {
4189 // C++0x [namespace.udecl]p3:
4190 // In a using-declaration used as a member-declaration, the
4191 // nested-name-specifier shall name a base class of the class
4192 // being defined.
4193
4194 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4195 cast<CXXRecordDecl>(NamedContext))) {
4196 if (CurContext == NamedContext) {
4197 Diag(NameLoc,
4198 diag::err_using_decl_nested_name_specifier_is_current_class)
4199 << SS.getRange();
4200 return true;
4201 }
4202
4203 Diag(SS.getRange().getBegin(),
4204 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4205 << (NestedNameSpecifier*) SS.getScopeRep()
4206 << cast<CXXRecordDecl>(CurContext)
4207 << SS.getRange();
4208 return true;
4209 }
4210
4211 return false;
4212 }
4213
4214 // C++03 [namespace.udecl]p4:
4215 // A using-declaration used as a member-declaration shall refer
4216 // to a member of a base class of the class being defined [etc.].
4217
4218 // Salient point: SS doesn't have to name a base class as long as
4219 // lookup only finds members from base classes. Therefore we can
4220 // diagnose here only if we can prove that that can't happen,
4221 // i.e. if the class hierarchies provably don't intersect.
4222
4223 // TODO: it would be nice if "definitely valid" results were cached
4224 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4225 // need to be repeated.
4226
4227 struct UserData {
4228 llvm::DenseSet<const CXXRecordDecl*> Bases;
4229
4230 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4231 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4232 Data->Bases.insert(Base);
4233 return true;
4234 }
4235
4236 bool hasDependentBases(const CXXRecordDecl *Class) {
4237 return !Class->forallBases(collect, this);
4238 }
4239
4240 /// Returns true if the base is dependent or is one of the
4241 /// accumulated base classes.
4242 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4243 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4244 return !Data->Bases.count(Base);
4245 }
4246
4247 bool mightShareBases(const CXXRecordDecl *Class) {
4248 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4249 }
4250 };
4251
4252 UserData Data;
4253
4254 // Returns false if we find a dependent base.
4255 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4256 return false;
4257
4258 // Returns false if the class has a dependent base or if it or one
4259 // of its bases is present in the base set of the current context.
4260 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4261 return false;
4262
4263 Diag(SS.getRange().getBegin(),
4264 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4265 << (NestedNameSpecifier*) SS.getScopeRep()
4266 << cast<CXXRecordDecl>(CurContext)
4267 << SS.getRange();
4268
4269 return true;
John McCallb96ec562009-12-04 22:46:56 +00004270}
4271
John McCall48871652010-08-21 09:40:31 +00004272Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004273 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004274 SourceLocation AliasLoc,
4275 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004276 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004277 SourceLocation IdentLoc,
4278 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004279
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004280 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004281 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4282 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004283
Anders Carlssondca83c42009-03-28 06:23:46 +00004284 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004285 NamedDecl *PrevDecl
4286 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4287 ForRedeclaration);
4288 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4289 PrevDecl = 0;
4290
4291 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004292 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004293 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004294 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004295 // FIXME: At some point, we'll want to create the (redundant)
4296 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004297 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004298 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004299 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004300 }
Mike Stump11289f42009-09-09 15:08:12 +00004301
Anders Carlssondca83c42009-03-28 06:23:46 +00004302 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4303 diag::err_redefinition_different_kind;
4304 Diag(AliasLoc, DiagID) << Alias;
4305 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004306 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004307 }
4308
John McCall27b18f82009-11-17 02:14:36 +00004309 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004310 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004311
John McCall9f3059a2009-10-09 21:13:30 +00004312 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004313 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4314 CTC_NoKeywords, 0)) {
4315 if (R.getAsSingle<NamespaceDecl>() ||
4316 R.getAsSingle<NamespaceAliasDecl>()) {
4317 if (DeclContext *DC = computeDeclContext(SS, false))
4318 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4319 << Ident << DC << Corrected << SS.getRange()
4320 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4321 else
4322 Diag(IdentLoc, diag::err_using_directive_suggest)
4323 << Ident << Corrected
4324 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4325
4326 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4327 << Corrected;
4328
4329 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004330 } else {
4331 R.clear();
4332 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004333 }
4334 }
4335
4336 if (R.empty()) {
4337 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004338 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004339 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004340 }
Mike Stump11289f42009-09-09 15:08:12 +00004341
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004342 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004343 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4344 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004345 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004346 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004347
John McCalld8d0d432010-02-16 06:53:13 +00004348 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004349 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004350}
4351
Douglas Gregora57478e2010-05-01 15:04:51 +00004352namespace {
4353 /// \brief Scoped object used to handle the state changes required in Sema
4354 /// to implicitly define the body of a C++ member function;
4355 class ImplicitlyDefinedFunctionScope {
4356 Sema &S;
4357 DeclContext *PreviousContext;
4358
4359 public:
4360 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4361 : S(S), PreviousContext(S.CurContext)
4362 {
4363 S.CurContext = Method;
4364 S.PushFunctionScope();
4365 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4366 }
4367
4368 ~ImplicitlyDefinedFunctionScope() {
4369 S.PopExpressionEvaluationContext();
4370 S.PopFunctionOrBlockScope();
4371 S.CurContext = PreviousContext;
4372 }
4373 };
4374}
4375
Sebastian Redlc15c3262010-09-13 22:02:47 +00004376static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4377 CXXRecordDecl *D) {
4378 ASTContext &Context = Self.Context;
4379 QualType ClassType = Context.getTypeDeclType(D);
4380 DeclarationName ConstructorName
4381 = Context.DeclarationNames.getCXXConstructorName(
4382 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4383
4384 DeclContext::lookup_const_iterator Con, ConEnd;
4385 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4386 Con != ConEnd; ++Con) {
4387 // FIXME: In C++0x, a constructor template can be a default constructor.
4388 if (isa<FunctionTemplateDecl>(*Con))
4389 continue;
4390
4391 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4392 if (Constructor->isDefaultConstructor())
4393 return Constructor;
4394 }
4395 return 0;
4396}
4397
Douglas Gregor0be31a22010-07-02 17:43:08 +00004398CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4399 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004400 // C++ [class.ctor]p5:
4401 // A default constructor for a class X is a constructor of class X
4402 // that can be called without an argument. If there is no
4403 // user-declared constructor for class X, a default constructor is
4404 // implicitly declared. An implicitly-declared default constructor
4405 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004406 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4407 "Should not build implicit default constructor!");
4408
Douglas Gregor6d880b12010-07-01 22:31:05 +00004409 // C++ [except.spec]p14:
4410 // An implicitly declared special member function (Clause 12) shall have an
4411 // exception-specification. [...]
4412 ImplicitExceptionSpecification ExceptSpec(Context);
4413
4414 // Direct base-class destructors.
4415 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4416 BEnd = ClassDecl->bases_end();
4417 B != BEnd; ++B) {
4418 if (B->isVirtual()) // Handled below.
4419 continue;
4420
Douglas Gregor9672f922010-07-03 00:47:00 +00004421 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4422 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4423 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4424 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004425 else if (CXXConstructorDecl *Constructor
4426 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004427 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004428 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004429 }
4430
4431 // Virtual base-class destructors.
4432 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4433 BEnd = ClassDecl->vbases_end();
4434 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004435 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4436 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4437 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4438 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4439 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004440 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
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 }
4444
4445 // Field destructors.
4446 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4447 FEnd = ClassDecl->field_end();
4448 F != FEnd; ++F) {
4449 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004450 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4451 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4452 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4453 ExceptSpec.CalledDecl(
4454 DeclareImplicitDefaultConstructor(FieldClassDecl));
4455 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004456 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004457 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004458 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004459 }
John McCalldb40c7f2010-12-14 08:05:40 +00004460
4461 FunctionProtoType::ExtProtoInfo EPI;
4462 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4463 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4464 EPI.NumExceptions = ExceptSpec.size();
4465 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004466
4467 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004468 CanQualType ClassType
4469 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4470 DeclarationName Name
4471 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004472 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004473 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004474 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004475 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004476 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004477 /*TInfo=*/0,
4478 /*isExplicit=*/false,
4479 /*isInline=*/true,
4480 /*isImplicitlyDeclared=*/true);
4481 DefaultCon->setAccess(AS_public);
4482 DefaultCon->setImplicit();
4483 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004484
4485 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004486 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4487
Douglas Gregor0be31a22010-07-02 17:43:08 +00004488 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004489 PushOnScopeChains(DefaultCon, S, false);
4490 ClassDecl->addDecl(DefaultCon);
4491
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004492 return DefaultCon;
4493}
4494
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004495void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4496 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004497 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004498 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004499 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004500
Anders Carlsson423f5d82010-04-23 16:04:08 +00004501 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004502 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004503
Douglas Gregora57478e2010-05-01 15:04:51 +00004504 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004505 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004506 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004507 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004508 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004509 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004510 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004511 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004512 }
Douglas Gregor73193272010-09-20 16:48:21 +00004513
4514 SourceLocation Loc = Constructor->getLocation();
4515 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4516
4517 Constructor->setUsed();
4518 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004519}
4520
Douglas Gregor0be31a22010-07-02 17:43:08 +00004521CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004522 // C++ [class.dtor]p2:
4523 // If a class has no user-declared destructor, a destructor is
4524 // declared implicitly. An implicitly-declared destructor is an
4525 // inline public member of its class.
4526
4527 // C++ [except.spec]p14:
4528 // An implicitly declared special member function (Clause 12) shall have
4529 // an exception-specification.
4530 ImplicitExceptionSpecification ExceptSpec(Context);
4531
4532 // Direct base-class destructors.
4533 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4534 BEnd = ClassDecl->bases_end();
4535 B != BEnd; ++B) {
4536 if (B->isVirtual()) // Handled below.
4537 continue;
4538
4539 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4540 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004541 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004542 }
4543
4544 // Virtual base-class destructors.
4545 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4546 BEnd = ClassDecl->vbases_end();
4547 B != BEnd; ++B) {
4548 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4549 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004550 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004551 }
4552
4553 // Field destructors.
4554 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4555 FEnd = ClassDecl->field_end();
4556 F != FEnd; ++F) {
4557 if (const RecordType *RecordTy
4558 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4559 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004560 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004561 }
4562
Douglas Gregor7454c562010-07-02 20:37:36 +00004563 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004564 FunctionProtoType::ExtProtoInfo EPI;
4565 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4566 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4567 EPI.NumExceptions = ExceptSpec.size();
4568 EPI.Exceptions = ExceptSpec.data();
4569 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004570
4571 CanQualType ClassType
4572 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4573 DeclarationName Name
4574 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004575 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004576 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004577 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004578 /*isInline=*/true,
4579 /*isImplicitlyDeclared=*/true);
4580 Destructor->setAccess(AS_public);
4581 Destructor->setImplicit();
4582 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004583
4584 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004585 ++ASTContext::NumImplicitDestructorsDeclared;
4586
4587 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004588 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004589 PushOnScopeChains(Destructor, S, false);
4590 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004591
4592 // This could be uniqued if it ever proves significant.
4593 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4594
4595 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004596
Douglas Gregorf1203042010-07-01 19:09:28 +00004597 return Destructor;
4598}
4599
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004600void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004601 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004602 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004603 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004604 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004605 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004606
Douglas Gregor54818f02010-05-12 16:39:35 +00004607 if (Destructor->isInvalidDecl())
4608 return;
4609
Douglas Gregora57478e2010-05-01 15:04:51 +00004610 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004611
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004612 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004613 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4614 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004615
Douglas Gregor54818f02010-05-12 16:39:35 +00004616 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004617 Diag(CurrentLocation, diag::note_member_synthesized_at)
4618 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4619
4620 Destructor->setInvalidDecl();
4621 return;
4622 }
4623
Douglas Gregor73193272010-09-20 16:48:21 +00004624 SourceLocation Loc = Destructor->getLocation();
4625 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4626
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004627 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004628 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004629}
4630
Douglas Gregorb139cd52010-05-01 20:49:11 +00004631/// \brief Builds a statement that copies the given entity from \p From to
4632/// \c To.
4633///
4634/// This routine is used to copy the members of a class with an
4635/// implicitly-declared copy assignment operator. When the entities being
4636/// copied are arrays, this routine builds for loops to copy them.
4637///
4638/// \param S The Sema object used for type-checking.
4639///
4640/// \param Loc The location where the implicit copy is being generated.
4641///
4642/// \param T The type of the expressions being copied. Both expressions must
4643/// have this type.
4644///
4645/// \param To The expression we are copying to.
4646///
4647/// \param From The expression we are copying from.
4648///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004649/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4650/// Otherwise, it's a non-static member subobject.
4651///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004652/// \param Depth Internal parameter recording the depth of the recursion.
4653///
4654/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004655static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004656BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004657 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004658 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004659 // C++0x [class.copy]p30:
4660 // Each subobject is assigned in the manner appropriate to its type:
4661 //
4662 // - if the subobject is of class type, the copy assignment operator
4663 // for the class is used (as if by explicit qualification; that is,
4664 // ignoring any possible virtual overriding functions in more derived
4665 // classes);
4666 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4667 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4668
4669 // Look for operator=.
4670 DeclarationName Name
4671 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4672 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4673 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4674
4675 // Filter out any result that isn't a copy-assignment operator.
4676 LookupResult::Filter F = OpLookup.makeFilter();
4677 while (F.hasNext()) {
4678 NamedDecl *D = F.next();
4679 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4680 if (Method->isCopyAssignmentOperator())
4681 continue;
4682
4683 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004684 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004685 F.done();
4686
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004687 // Suppress the protected check (C++ [class.protected]) for each of the
4688 // assignment operators we found. This strange dance is required when
4689 // we're assigning via a base classes's copy-assignment operator. To
4690 // ensure that we're getting the right base class subobject (without
4691 // ambiguities), we need to cast "this" to that subobject type; to
4692 // ensure that we don't go through the virtual call mechanism, we need
4693 // to qualify the operator= name with the base class (see below). However,
4694 // this means that if the base class has a protected copy assignment
4695 // operator, the protected member access check will fail. So, we
4696 // rewrite "protected" access to "public" access in this case, since we
4697 // know by construction that we're calling from a derived class.
4698 if (CopyingBaseSubobject) {
4699 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4700 L != LEnd; ++L) {
4701 if (L.getAccess() == AS_protected)
4702 L.setAccess(AS_public);
4703 }
4704 }
4705
Douglas Gregorb139cd52010-05-01 20:49:11 +00004706 // Create the nested-name-specifier that will be used to qualify the
4707 // reference to operator=; this is required to suppress the virtual
4708 // call mechanism.
4709 CXXScopeSpec SS;
4710 SS.setRange(Loc);
4711 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4712 T.getTypePtr()));
4713
4714 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004715 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004716 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004717 /*FirstQualifierInScope=*/0, OpLookup,
4718 /*TemplateArgs=*/0,
4719 /*SuppressQualifierCheck=*/true);
4720 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004721 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004722
4723 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004724
John McCalldadc5752010-08-24 06:29:42 +00004725 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004726 OpEqualRef.takeAs<Expr>(),
4727 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004728 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004729 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004730
4731 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004732 }
John McCallab8c2732010-03-16 06:11:48 +00004733
Douglas Gregorb139cd52010-05-01 20:49:11 +00004734 // - if the subobject is of scalar type, the built-in assignment
4735 // operator is used.
4736 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4737 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004738 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004739 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004740 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004741
4742 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004743 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004744
4745 // - if the subobject is an array, each element is assigned, in the
4746 // manner appropriate to the element type;
4747
4748 // Construct a loop over the array bounds, e.g.,
4749 //
4750 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4751 //
4752 // that will copy each of the array elements.
4753 QualType SizeType = S.Context.getSizeType();
4754
4755 // Create the iteration variable.
4756 IdentifierInfo *IterationVarName = 0;
4757 {
4758 llvm::SmallString<8> Str;
4759 llvm::raw_svector_ostream OS(Str);
4760 OS << "__i" << Depth;
4761 IterationVarName = &S.Context.Idents.get(OS.str());
4762 }
4763 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4764 IterationVarName, SizeType,
4765 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004766 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004767
4768 // Initialize the iteration variable to zero.
4769 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004770 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004771
4772 // Create a reference to the iteration variable; we'll use this several
4773 // times throughout.
4774 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004775 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004776 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4777
4778 // Create the DeclStmt that holds the iteration variable.
4779 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4780
4781 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004782 llvm::APInt Upper
4783 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004784 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004785 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004786 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4787 BO_NE, S.Context.BoolTy,
4788 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004789
4790 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004791 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004792 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4793 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004794
4795 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004796 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4797 IterationVarRef, Loc));
4798 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4799 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004800
4801 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004802 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4803 To, From, CopyingBaseSubobject,
4804 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004805 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004806 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004807
4808 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004809 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004810 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004811 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004812 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004813}
4814
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004815/// \brief Determine whether the given class has a copy assignment operator
4816/// that accepts a const-qualified argument.
4817static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4818 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4819
4820 if (!Class->hasDeclaredCopyAssignment())
4821 S.DeclareImplicitCopyAssignment(Class);
4822
4823 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4824 DeclarationName OpName
4825 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4826
4827 DeclContext::lookup_const_iterator Op, OpEnd;
4828 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4829 // C++ [class.copy]p9:
4830 // A user-declared copy assignment operator is a non-static non-template
4831 // member function of class X with exactly one parameter of type X, X&,
4832 // const X&, volatile X& or const volatile X&.
4833 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4834 if (!Method)
4835 continue;
4836
4837 if (Method->isStatic())
4838 continue;
4839 if (Method->getPrimaryTemplate())
4840 continue;
4841 const FunctionProtoType *FnType =
4842 Method->getType()->getAs<FunctionProtoType>();
4843 assert(FnType && "Overloaded operator has no prototype.");
4844 // Don't assert on this; an invalid decl might have been left in the AST.
4845 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4846 continue;
4847 bool AcceptsConst = true;
4848 QualType ArgType = FnType->getArgType(0);
4849 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4850 ArgType = Ref->getPointeeType();
4851 // Is it a non-const lvalue reference?
4852 if (!ArgType.isConstQualified())
4853 AcceptsConst = false;
4854 }
4855 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4856 continue;
4857
4858 // We have a single argument of type cv X or cv X&, i.e. we've found the
4859 // copy assignment operator. Return whether it accepts const arguments.
4860 return AcceptsConst;
4861 }
4862 assert(Class->isInvalidDecl() &&
4863 "No copy assignment operator declared in valid code.");
4864 return false;
4865}
4866
Douglas Gregor0be31a22010-07-02 17:43:08 +00004867CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004868 // Note: The following rules are largely analoguous to the copy
4869 // constructor rules. Note that virtual bases are not taken into account
4870 // for determining the argument type of the operator. Note also that
4871 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004872
4873
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004874 // C++ [class.copy]p10:
4875 // If the class definition does not explicitly declare a copy
4876 // assignment operator, one is declared implicitly.
4877 // The implicitly-defined copy assignment operator for a class X
4878 // will have the form
4879 //
4880 // X& X::operator=(const X&)
4881 //
4882 // if
4883 bool HasConstCopyAssignment = true;
4884
4885 // -- each direct base class B of X has a copy assignment operator
4886 // whose parameter is of type const B&, const volatile B& or B,
4887 // and
4888 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4889 BaseEnd = ClassDecl->bases_end();
4890 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4891 assert(!Base->getType()->isDependentType() &&
4892 "Cannot generate implicit members for class with dependent bases.");
4893 const CXXRecordDecl *BaseClassDecl
4894 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004895 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004896 }
4897
4898 // -- for all the nonstatic data members of X that are of a class
4899 // type M (or array thereof), each such class type has a copy
4900 // assignment operator whose parameter is of type const M&,
4901 // const volatile M& or M.
4902 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4903 FieldEnd = ClassDecl->field_end();
4904 HasConstCopyAssignment && Field != FieldEnd;
4905 ++Field) {
4906 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4907 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4908 const CXXRecordDecl *FieldClassDecl
4909 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004910 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004911 }
4912 }
4913
4914 // Otherwise, the implicitly declared copy assignment operator will
4915 // have the form
4916 //
4917 // X& X::operator=(X&)
4918 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4919 QualType RetType = Context.getLValueReferenceType(ArgType);
4920 if (HasConstCopyAssignment)
4921 ArgType = ArgType.withConst();
4922 ArgType = Context.getLValueReferenceType(ArgType);
4923
Douglas Gregor68e11362010-07-01 17:48:08 +00004924 // C++ [except.spec]p14:
4925 // An implicitly declared special member function (Clause 12) shall have an
4926 // exception-specification. [...]
4927 ImplicitExceptionSpecification ExceptSpec(Context);
4928 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4929 BaseEnd = ClassDecl->bases_end();
4930 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004931 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004932 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004933
4934 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4935 DeclareImplicitCopyAssignment(BaseClassDecl);
4936
Douglas Gregor68e11362010-07-01 17:48:08 +00004937 if (CXXMethodDecl *CopyAssign
4938 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4939 ExceptSpec.CalledDecl(CopyAssign);
4940 }
4941 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4942 FieldEnd = ClassDecl->field_end();
4943 Field != FieldEnd;
4944 ++Field) {
4945 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4946 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004947 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004948 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004949
4950 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4951 DeclareImplicitCopyAssignment(FieldClassDecl);
4952
Douglas Gregor68e11362010-07-01 17:48:08 +00004953 if (CXXMethodDecl *CopyAssign
4954 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4955 ExceptSpec.CalledDecl(CopyAssign);
4956 }
4957 }
4958
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004959 // An implicitly-declared copy assignment operator is an inline public
4960 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004961 FunctionProtoType::ExtProtoInfo EPI;
4962 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4963 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4964 EPI.NumExceptions = ExceptSpec.size();
4965 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004966 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004967 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004968 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004969 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004970 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004971 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004972 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004973 /*isInline=*/true);
4974 CopyAssignment->setAccess(AS_public);
4975 CopyAssignment->setImplicit();
4976 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004977
4978 // Add the parameter to the operator.
4979 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4980 ClassDecl->getLocation(),
4981 /*Id=*/0,
4982 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004983 SC_None,
4984 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004985 CopyAssignment->setParams(&FromParam, 1);
4986
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004987 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004988 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4989
Douglas Gregor0be31a22010-07-02 17:43:08 +00004990 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004991 PushOnScopeChains(CopyAssignment, S, false);
4992 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004993
4994 AddOverriddenMethods(ClassDecl, CopyAssignment);
4995 return CopyAssignment;
4996}
4997
Douglas Gregorb139cd52010-05-01 20:49:11 +00004998void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4999 CXXMethodDecl *CopyAssignOperator) {
5000 assert((CopyAssignOperator->isImplicit() &&
5001 CopyAssignOperator->isOverloadedOperator() &&
5002 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005003 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005004 "DefineImplicitCopyAssignment called for wrong function");
5005
5006 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5007
5008 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5009 CopyAssignOperator->setInvalidDecl();
5010 return;
5011 }
5012
5013 CopyAssignOperator->setUsed();
5014
5015 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005016 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005017
5018 // C++0x [class.copy]p30:
5019 // The implicitly-defined or explicitly-defaulted copy assignment operator
5020 // for a non-union class X performs memberwise copy assignment of its
5021 // subobjects. The direct base classes of X are assigned first, in the
5022 // order of their declaration in the base-specifier-list, and then the
5023 // immediate non-static data members of X are assigned, in the order in
5024 // which they were declared in the class definition.
5025
5026 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005027 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005028
5029 // The parameter for the "other" object, which we are copying from.
5030 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5031 Qualifiers OtherQuals = Other->getType().getQualifiers();
5032 QualType OtherRefType = Other->getType();
5033 if (const LValueReferenceType *OtherRef
5034 = OtherRefType->getAs<LValueReferenceType>()) {
5035 OtherRefType = OtherRef->getPointeeType();
5036 OtherQuals = OtherRefType.getQualifiers();
5037 }
5038
5039 // Our location for everything implicitly-generated.
5040 SourceLocation Loc = CopyAssignOperator->getLocation();
5041
5042 // Construct a reference to the "other" object. We'll be using this
5043 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005044 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005045 assert(OtherRef && "Reference to parameter cannot fail!");
5046
5047 // Construct the "this" pointer. We'll be using this throughout the generated
5048 // ASTs.
5049 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5050 assert(This && "Reference to this cannot fail!");
5051
5052 // Assign base classes.
5053 bool Invalid = false;
5054 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5055 E = ClassDecl->bases_end(); Base != E; ++Base) {
5056 // Form the assignment:
5057 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5058 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005059 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005060 Invalid = true;
5061 continue;
5062 }
5063
John McCallcf142162010-08-07 06:22:56 +00005064 CXXCastPath BasePath;
5065 BasePath.push_back(Base);
5066
Douglas Gregorb139cd52010-05-01 20:49:11 +00005067 // Construct the "from" expression, which is an implicit cast to the
5068 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005069 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005070 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005071 CK_UncheckedDerivedToBase,
5072 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005073
5074 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005075 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005076
5077 // Implicitly cast "this" to the appropriately-qualified base type.
5078 Expr *ToE = To.takeAs<Expr>();
5079 ImpCastExprToType(ToE,
5080 Context.getCVRQualifiedType(BaseType,
5081 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005082 CK_UncheckedDerivedToBase,
5083 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005084 To = Owned(ToE);
5085
5086 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005087 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005088 To.get(), From,
5089 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005090 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005091 Diag(CurrentLocation, diag::note_member_synthesized_at)
5092 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5093 CopyAssignOperator->setInvalidDecl();
5094 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005095 }
5096
5097 // Success! Record the copy.
5098 Statements.push_back(Copy.takeAs<Expr>());
5099 }
5100
5101 // \brief Reference to the __builtin_memcpy function.
5102 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005103 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005104 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005105
5106 // Assign non-static members.
5107 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5108 FieldEnd = ClassDecl->field_end();
5109 Field != FieldEnd; ++Field) {
5110 // Check for members of reference type; we can't copy those.
5111 if (Field->getType()->isReferenceType()) {
5112 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5113 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5114 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005115 Diag(CurrentLocation, diag::note_member_synthesized_at)
5116 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005117 Invalid = true;
5118 continue;
5119 }
5120
5121 // Check for members of const-qualified, non-class type.
5122 QualType BaseType = Context.getBaseElementType(Field->getType());
5123 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5124 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5125 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5126 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005127 Diag(CurrentLocation, diag::note_member_synthesized_at)
5128 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005129 Invalid = true;
5130 continue;
5131 }
5132
5133 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005134 if (FieldType->isIncompleteArrayType()) {
5135 assert(ClassDecl->hasFlexibleArrayMember() &&
5136 "Incomplete array type is not valid");
5137 continue;
5138 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005139
5140 // Build references to the field in the object we're copying from and to.
5141 CXXScopeSpec SS; // Intentionally empty
5142 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5143 LookupMemberName);
5144 MemberLookup.addDecl(*Field);
5145 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005146 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005147 Loc, /*IsArrow=*/false,
5148 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005149 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005150 Loc, /*IsArrow=*/true,
5151 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005152 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5153 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5154
5155 // If the field should be copied with __builtin_memcpy rather than via
5156 // explicit assignments, do so. This optimization only applies for arrays
5157 // of scalars and arrays of class type with trivial copy-assignment
5158 // operators.
5159 if (FieldType->isArrayType() &&
5160 (!BaseType->isRecordType() ||
5161 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5162 ->hasTrivialCopyAssignment())) {
5163 // Compute the size of the memory buffer to be copied.
5164 QualType SizeType = Context.getSizeType();
5165 llvm::APInt Size(Context.getTypeSize(SizeType),
5166 Context.getTypeSizeInChars(BaseType).getQuantity());
5167 for (const ConstantArrayType *Array
5168 = Context.getAsConstantArrayType(FieldType);
5169 Array;
5170 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005171 llvm::APInt ArraySize
5172 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005173 Size *= ArraySize;
5174 }
5175
5176 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005177 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5178 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005179
5180 bool NeedsCollectableMemCpy =
5181 (BaseType->isRecordType() &&
5182 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5183
5184 if (NeedsCollectableMemCpy) {
5185 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005186 // Create a reference to the __builtin_objc_memmove_collectable function.
5187 LookupResult R(*this,
5188 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005189 Loc, LookupOrdinaryName);
5190 LookupName(R, TUScope, true);
5191
5192 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5193 if (!CollectableMemCpy) {
5194 // Something went horribly wrong earlier, and we will have
5195 // complained about it.
5196 Invalid = true;
5197 continue;
5198 }
5199
5200 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5201 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005202 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005203 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5204 }
5205 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005206 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005207 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005208 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5209 LookupOrdinaryName);
5210 LookupName(R, TUScope, true);
5211
5212 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5213 if (!BuiltinMemCpy) {
5214 // Something went horribly wrong earlier, and we will have complained
5215 // about it.
5216 Invalid = true;
5217 continue;
5218 }
5219
5220 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5221 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005222 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005223 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5224 }
5225
John McCall37ad5512010-08-23 06:44:23 +00005226 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005227 CallArgs.push_back(To.takeAs<Expr>());
5228 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005229 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005230 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005231 if (NeedsCollectableMemCpy)
5232 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005233 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005234 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005235 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005236 else
5237 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005238 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005239 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005240 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005241
Douglas Gregorb139cd52010-05-01 20:49:11 +00005242 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5243 Statements.push_back(Call.takeAs<Expr>());
5244 continue;
5245 }
5246
5247 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005248 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005249 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005250 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005251 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005252 Diag(CurrentLocation, diag::note_member_synthesized_at)
5253 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5254 CopyAssignOperator->setInvalidDecl();
5255 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005256 }
5257
5258 // Success! Record the copy.
5259 Statements.push_back(Copy.takeAs<Stmt>());
5260 }
5261
5262 if (!Invalid) {
5263 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005264 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005265
John McCalldadc5752010-08-24 06:29:42 +00005266 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005267 if (Return.isInvalid())
5268 Invalid = true;
5269 else {
5270 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005271
5272 if (Trap.hasErrorOccurred()) {
5273 Diag(CurrentLocation, diag::note_member_synthesized_at)
5274 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5275 Invalid = true;
5276 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005277 }
5278 }
5279
5280 if (Invalid) {
5281 CopyAssignOperator->setInvalidDecl();
5282 return;
5283 }
5284
John McCalldadc5752010-08-24 06:29:42 +00005285 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005286 /*isStmtExpr=*/false);
5287 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5288 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005289}
5290
Douglas Gregor0be31a22010-07-02 17:43:08 +00005291CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5292 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005293 // C++ [class.copy]p4:
5294 // If the class definition does not explicitly declare a copy
5295 // constructor, one is declared implicitly.
5296
Douglas Gregor54be3392010-07-01 17:57:27 +00005297 // C++ [class.copy]p5:
5298 // The implicitly-declared copy constructor for a class X will
5299 // have the form
5300 //
5301 // X::X(const X&)
5302 //
5303 // if
5304 bool HasConstCopyConstructor = true;
5305
5306 // -- each direct or virtual base class B of X has a copy
5307 // constructor whose first parameter is of type const B& or
5308 // const volatile B&, and
5309 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5310 BaseEnd = ClassDecl->bases_end();
5311 HasConstCopyConstructor && Base != BaseEnd;
5312 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005313 // Virtual bases are handled below.
5314 if (Base->isVirtual())
5315 continue;
5316
Douglas Gregora6d69502010-07-02 23:41:54 +00005317 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005318 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005319 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5320 DeclareImplicitCopyConstructor(BaseClassDecl);
5321
Douglas Gregorcfe68222010-07-01 18:27:03 +00005322 HasConstCopyConstructor
5323 = BaseClassDecl->hasConstCopyConstructor(Context);
5324 }
5325
5326 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5327 BaseEnd = ClassDecl->vbases_end();
5328 HasConstCopyConstructor && Base != BaseEnd;
5329 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005330 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005331 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005332 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5333 DeclareImplicitCopyConstructor(BaseClassDecl);
5334
Douglas Gregor54be3392010-07-01 17:57:27 +00005335 HasConstCopyConstructor
5336 = BaseClassDecl->hasConstCopyConstructor(Context);
5337 }
5338
5339 // -- for all the nonstatic data members of X that are of a
5340 // class type M (or array thereof), each such class type
5341 // has a copy constructor whose first parameter is of type
5342 // const M& or const volatile M&.
5343 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5344 FieldEnd = ClassDecl->field_end();
5345 HasConstCopyConstructor && Field != FieldEnd;
5346 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005347 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005348 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005349 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005350 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005351 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5352 DeclareImplicitCopyConstructor(FieldClassDecl);
5353
Douglas Gregor54be3392010-07-01 17:57:27 +00005354 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005355 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005356 }
5357 }
5358
5359 // Otherwise, the implicitly declared copy constructor will have
5360 // the form
5361 //
5362 // X::X(X&)
5363 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5364 QualType ArgType = ClassType;
5365 if (HasConstCopyConstructor)
5366 ArgType = ArgType.withConst();
5367 ArgType = Context.getLValueReferenceType(ArgType);
5368
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005369 // C++ [except.spec]p14:
5370 // An implicitly declared special member function (Clause 12) shall have an
5371 // exception-specification. [...]
5372 ImplicitExceptionSpecification ExceptSpec(Context);
5373 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5374 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5375 BaseEnd = ClassDecl->bases_end();
5376 Base != BaseEnd;
5377 ++Base) {
5378 // Virtual bases are handled below.
5379 if (Base->isVirtual())
5380 continue;
5381
Douglas Gregora6d69502010-07-02 23:41:54 +00005382 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005383 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005384 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5385 DeclareImplicitCopyConstructor(BaseClassDecl);
5386
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005387 if (CXXConstructorDecl *CopyConstructor
5388 = BaseClassDecl->getCopyConstructor(Context, Quals))
5389 ExceptSpec.CalledDecl(CopyConstructor);
5390 }
5391 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5392 BaseEnd = ClassDecl->vbases_end();
5393 Base != BaseEnd;
5394 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005395 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005396 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005397 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5398 DeclareImplicitCopyConstructor(BaseClassDecl);
5399
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005400 if (CXXConstructorDecl *CopyConstructor
5401 = BaseClassDecl->getCopyConstructor(Context, Quals))
5402 ExceptSpec.CalledDecl(CopyConstructor);
5403 }
5404 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5405 FieldEnd = ClassDecl->field_end();
5406 Field != FieldEnd;
5407 ++Field) {
5408 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5409 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005410 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005411 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005412 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5413 DeclareImplicitCopyConstructor(FieldClassDecl);
5414
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005415 if (CXXConstructorDecl *CopyConstructor
5416 = FieldClassDecl->getCopyConstructor(Context, Quals))
5417 ExceptSpec.CalledDecl(CopyConstructor);
5418 }
5419 }
5420
Douglas Gregor54be3392010-07-01 17:57:27 +00005421 // An implicitly-declared copy constructor is an inline public
5422 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005423 FunctionProtoType::ExtProtoInfo EPI;
5424 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5425 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5426 EPI.NumExceptions = ExceptSpec.size();
5427 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005428 DeclarationName Name
5429 = Context.DeclarationNames.getCXXConstructorName(
5430 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005431 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005432 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005433 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005434 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005435 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005436 /*TInfo=*/0,
5437 /*isExplicit=*/false,
5438 /*isInline=*/true,
5439 /*isImplicitlyDeclared=*/true);
5440 CopyConstructor->setAccess(AS_public);
5441 CopyConstructor->setImplicit();
5442 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5443
Douglas Gregora6d69502010-07-02 23:41:54 +00005444 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005445 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5446
Douglas Gregor54be3392010-07-01 17:57:27 +00005447 // Add the parameter to the constructor.
5448 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5449 ClassDecl->getLocation(),
5450 /*IdentifierInfo=*/0,
5451 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005452 SC_None,
5453 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005454 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005455 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005456 PushOnScopeChains(CopyConstructor, S, false);
5457 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005458
5459 return CopyConstructor;
5460}
5461
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005462void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5463 CXXConstructorDecl *CopyConstructor,
5464 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005465 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005466 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005467 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005468 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005469
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005470 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005471 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005472
Douglas Gregora57478e2010-05-01 15:04:51 +00005473 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005474 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005475
Alexis Hunt1d792652011-01-08 20:30:50 +00005476 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005477 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005478 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005479 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005480 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005481 } else {
5482 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5483 CopyConstructor->getLocation(),
5484 MultiStmtArg(*this, 0, 0),
5485 /*isStmtExpr=*/false)
5486 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005487 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005488
5489 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005490}
5491
John McCalldadc5752010-08-24 06:29:42 +00005492ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005493Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005494 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005495 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005496 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005497 unsigned ConstructKind,
5498 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005499 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005500
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005501 // C++0x [class.copy]p34:
5502 // When certain criteria are met, an implementation is allowed to
5503 // omit the copy/move construction of a class object, even if the
5504 // copy/move constructor and/or destructor for the object have
5505 // side effects. [...]
5506 // - when a temporary class object that has not been bound to a
5507 // reference (12.2) would be copied/moved to a class object
5508 // with the same cv-unqualified type, the copy/move operation
5509 // can be omitted by constructing the temporary object
5510 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005511 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5512 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005513 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005514 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005515 }
Mike Stump11289f42009-09-09 15:08:12 +00005516
5517 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005518 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005519 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005520}
5521
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005522/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5523/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005524ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005525Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5526 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005527 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005528 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005529 unsigned ConstructKind,
5530 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005531 unsigned NumExprs = ExprArgs.size();
5532 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005533
Douglas Gregor27381f32009-11-23 12:27:39 +00005534 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005535 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005536 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005537 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005538 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5539 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005540}
5541
Mike Stump11289f42009-09-09 15:08:12 +00005542bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005543 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005544 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005545 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005546 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005547 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005548 move(Exprs), false, CXXConstructExpr::CK_Complete,
5549 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005550 if (TempResult.isInvalid())
5551 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005552
Anders Carlsson6eb55572009-08-25 05:12:04 +00005553 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005554 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005555 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005556 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005557 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005558
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005559 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005560}
5561
John McCall03c48482010-02-02 09:10:11 +00005562void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5563 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005564 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005565 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005566 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005567 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005568 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005569 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005570 << VD->getDeclName()
5571 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005572
John McCall386dfc72010-09-18 05:25:11 +00005573 // TODO: this should be re-enabled for static locals by !CXAAtExit
5574 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005575 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005576 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005577}
5578
Mike Stump11289f42009-09-09 15:08:12 +00005579/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005580/// ActOnDeclarator, when a C++ direct initializer is present.
5581/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005582void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005583 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005584 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005585 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005586 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005587
5588 // If there is no declaration, there was an error parsing it. Just ignore
5589 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005590 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005591 return;
Mike Stump11289f42009-09-09 15:08:12 +00005592
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005593 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5594 if (!VDecl) {
5595 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5596 RealDecl->setInvalidDecl();
5597 return;
5598 }
5599
Douglas Gregor402250f2009-08-26 21:14:46 +00005600 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005601 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005602 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5603 //
5604 // Clients that want to distinguish between the two forms, can check for
5605 // direct initializer using VarDecl::hasCXXDirectInitializer().
5606 // A major benefit is that clients that don't particularly care about which
5607 // exactly form was it (like the CodeGen) can handle both cases without
5608 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005609
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005610 // C++ 8.5p11:
5611 // The form of initialization (using parentheses or '=') is generally
5612 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005613 // class type.
5614
Douglas Gregor50dc2192010-02-11 22:55:30 +00005615 if (!VDecl->getType()->isDependentType() &&
5616 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005617 diag::err_typecheck_decl_incomplete_type)) {
5618 VDecl->setInvalidDecl();
5619 return;
5620 }
5621
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005622 // The variable can not have an abstract class type.
5623 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5624 diag::err_abstract_type_in_decl,
5625 AbstractVariableType))
5626 VDecl->setInvalidDecl();
5627
Sebastian Redl5ca79842010-02-01 20:16:42 +00005628 const VarDecl *Def;
5629 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005630 Diag(VDecl->getLocation(), diag::err_redefinition)
5631 << VDecl->getDeclName();
5632 Diag(Def->getLocation(), diag::note_previous_definition);
5633 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005634 return;
5635 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005636
Douglas Gregorf0f83692010-08-24 05:27:49 +00005637 // C++ [class.static.data]p4
5638 // If a static data member is of const integral or const
5639 // enumeration type, its declaration in the class definition can
5640 // specify a constant-initializer which shall be an integral
5641 // constant expression (5.19). In that case, the member can appear
5642 // in integral constant expressions. The member shall still be
5643 // defined in a namespace scope if it is used in the program and the
5644 // namespace scope definition shall not contain an initializer.
5645 //
5646 // We already performed a redefinition check above, but for static
5647 // data members we also need to check whether there was an in-class
5648 // declaration with an initializer.
5649 const VarDecl* PrevInit = 0;
5650 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5651 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5652 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5653 return;
5654 }
5655
Douglas Gregor71f39c92010-12-16 01:31:22 +00005656 bool IsDependent = false;
5657 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5658 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5659 VDecl->setInvalidDecl();
5660 return;
5661 }
5662
5663 if (Exprs.get()[I]->isTypeDependent())
5664 IsDependent = true;
5665 }
5666
Douglas Gregor50dc2192010-02-11 22:55:30 +00005667 // If either the declaration has a dependent type or if any of the
5668 // expressions is type-dependent, we represent the initialization
5669 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005670 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005671 // Let clients know that initialization was done with a direct initializer.
5672 VDecl->setCXXDirectInitializer(true);
5673
5674 // Store the initialization expressions as a ParenListExpr.
5675 unsigned NumExprs = Exprs.size();
5676 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5677 (Expr **)Exprs.release(),
5678 NumExprs, RParenLoc));
5679 return;
5680 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005681
5682 // Capture the variable that is being initialized and the style of
5683 // initialization.
5684 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5685
5686 // FIXME: Poor source location information.
5687 InitializationKind Kind
5688 = InitializationKind::CreateDirect(VDecl->getLocation(),
5689 LParenLoc, RParenLoc);
5690
5691 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005692 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005693 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005694 if (Result.isInvalid()) {
5695 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005696 return;
5697 }
John McCallacf0ee52010-10-08 02:01:28 +00005698
5699 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005700
Douglas Gregora40433a2010-12-07 00:41:46 +00005701 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005702 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005703 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005704
John McCall8b7fd8f12011-01-19 11:48:09 +00005705 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005706}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005707
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005708/// \brief Given a constructor and the set of arguments provided for the
5709/// constructor, convert the arguments and add any required default arguments
5710/// to form a proper call to this constructor.
5711///
5712/// \returns true if an error occurred, false otherwise.
5713bool
5714Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5715 MultiExprArg ArgsPtr,
5716 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005717 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005718 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5719 unsigned NumArgs = ArgsPtr.size();
5720 Expr **Args = (Expr **)ArgsPtr.get();
5721
5722 const FunctionProtoType *Proto
5723 = Constructor->getType()->getAs<FunctionProtoType>();
5724 assert(Proto && "Constructor without a prototype?");
5725 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005726
5727 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005728 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005729 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005730 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005731 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005732
5733 VariadicCallType CallType =
5734 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5735 llvm::SmallVector<Expr *, 8> AllArgs;
5736 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5737 Proto, 0, Args, NumArgs, AllArgs,
5738 CallType);
5739 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5740 ConvertedArgs.push_back(AllArgs[i]);
5741 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005742}
5743
Anders Carlssone363c8e2009-12-12 00:32:00 +00005744static inline bool
5745CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5746 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005747 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005748 if (isa<NamespaceDecl>(DC)) {
5749 return SemaRef.Diag(FnDecl->getLocation(),
5750 diag::err_operator_new_delete_declared_in_namespace)
5751 << FnDecl->getDeclName();
5752 }
5753
5754 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005755 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005756 return SemaRef.Diag(FnDecl->getLocation(),
5757 diag::err_operator_new_delete_declared_static)
5758 << FnDecl->getDeclName();
5759 }
5760
Anders Carlsson60659a82009-12-12 02:43:16 +00005761 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005762}
5763
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005764static inline bool
5765CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5766 CanQualType ExpectedResultType,
5767 CanQualType ExpectedFirstParamType,
5768 unsigned DependentParamTypeDiag,
5769 unsigned InvalidParamTypeDiag) {
5770 QualType ResultType =
5771 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5772
5773 // Check that the result type is not dependent.
5774 if (ResultType->isDependentType())
5775 return SemaRef.Diag(FnDecl->getLocation(),
5776 diag::err_operator_new_delete_dependent_result_type)
5777 << FnDecl->getDeclName() << ExpectedResultType;
5778
5779 // Check that the result type is what we expect.
5780 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5781 return SemaRef.Diag(FnDecl->getLocation(),
5782 diag::err_operator_new_delete_invalid_result_type)
5783 << FnDecl->getDeclName() << ExpectedResultType;
5784
5785 // A function template must have at least 2 parameters.
5786 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5787 return SemaRef.Diag(FnDecl->getLocation(),
5788 diag::err_operator_new_delete_template_too_few_parameters)
5789 << FnDecl->getDeclName();
5790
5791 // The function decl must have at least 1 parameter.
5792 if (FnDecl->getNumParams() == 0)
5793 return SemaRef.Diag(FnDecl->getLocation(),
5794 diag::err_operator_new_delete_too_few_parameters)
5795 << FnDecl->getDeclName();
5796
5797 // Check the the first parameter type is not dependent.
5798 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5799 if (FirstParamType->isDependentType())
5800 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5801 << FnDecl->getDeclName() << ExpectedFirstParamType;
5802
5803 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005804 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005805 ExpectedFirstParamType)
5806 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5807 << FnDecl->getDeclName() << ExpectedFirstParamType;
5808
5809 return false;
5810}
5811
Anders Carlsson12308f42009-12-11 23:23:22 +00005812static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005813CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005814 // C++ [basic.stc.dynamic.allocation]p1:
5815 // A program is ill-formed if an allocation function is declared in a
5816 // namespace scope other than global scope or declared static in global
5817 // scope.
5818 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5819 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005820
5821 CanQualType SizeTy =
5822 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5823
5824 // C++ [basic.stc.dynamic.allocation]p1:
5825 // The return type shall be void*. The first parameter shall have type
5826 // std::size_t.
5827 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5828 SizeTy,
5829 diag::err_operator_new_dependent_param_type,
5830 diag::err_operator_new_param_type))
5831 return true;
5832
5833 // C++ [basic.stc.dynamic.allocation]p1:
5834 // The first parameter shall not have an associated default argument.
5835 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005836 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005837 diag::err_operator_new_default_arg)
5838 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5839
5840 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005841}
5842
5843static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005844CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5845 // C++ [basic.stc.dynamic.deallocation]p1:
5846 // A program is ill-formed if deallocation functions are declared in a
5847 // namespace scope other than global scope or declared static in global
5848 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005849 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5850 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005851
5852 // C++ [basic.stc.dynamic.deallocation]p2:
5853 // Each deallocation function shall return void and its first parameter
5854 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005855 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5856 SemaRef.Context.VoidPtrTy,
5857 diag::err_operator_delete_dependent_param_type,
5858 diag::err_operator_delete_param_type))
5859 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005860
Anders Carlsson12308f42009-12-11 23:23:22 +00005861 return false;
5862}
5863
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005864/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5865/// of this overloaded operator is well-formed. If so, returns false;
5866/// otherwise, emits appropriate diagnostics and returns true.
5867bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005868 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005869 "Expected an overloaded operator declaration");
5870
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005871 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5872
Mike Stump11289f42009-09-09 15:08:12 +00005873 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005874 // The allocation and deallocation functions, operator new,
5875 // operator new[], operator delete and operator delete[], are
5876 // described completely in 3.7.3. The attributes and restrictions
5877 // found in the rest of this subclause do not apply to them unless
5878 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005879 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005880 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005881
Anders Carlsson22f443f2009-12-12 00:26:23 +00005882 if (Op == OO_New || Op == OO_Array_New)
5883 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005884
5885 // C++ [over.oper]p6:
5886 // An operator function shall either be a non-static member
5887 // function or be a non-member function and have at least one
5888 // parameter whose type is a class, a reference to a class, an
5889 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005890 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5891 if (MethodDecl->isStatic())
5892 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005893 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005894 } else {
5895 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005896 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5897 ParamEnd = FnDecl->param_end();
5898 Param != ParamEnd; ++Param) {
5899 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005900 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5901 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005902 ClassOrEnumParam = true;
5903 break;
5904 }
5905 }
5906
Douglas Gregord69246b2008-11-17 16:14:12 +00005907 if (!ClassOrEnumParam)
5908 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005909 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005910 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005911 }
5912
5913 // C++ [over.oper]p8:
5914 // An operator function cannot have default arguments (8.3.6),
5915 // except where explicitly stated below.
5916 //
Mike Stump11289f42009-09-09 15:08:12 +00005917 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005918 // (C++ [over.call]p1).
5919 if (Op != OO_Call) {
5920 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5921 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005922 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005923 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005924 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005925 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005926 }
5927 }
5928
Douglas Gregor6cf08062008-11-10 13:38:07 +00005929 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5930 { false, false, false }
5931#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5932 , { Unary, Binary, MemberOnly }
5933#include "clang/Basic/OperatorKinds.def"
5934 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005935
Douglas Gregor6cf08062008-11-10 13:38:07 +00005936 bool CanBeUnaryOperator = OperatorUses[Op][0];
5937 bool CanBeBinaryOperator = OperatorUses[Op][1];
5938 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005939
5940 // C++ [over.oper]p8:
5941 // [...] Operator functions cannot have more or fewer parameters
5942 // than the number required for the corresponding operator, as
5943 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005944 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005945 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005946 if (Op != OO_Call &&
5947 ((NumParams == 1 && !CanBeUnaryOperator) ||
5948 (NumParams == 2 && !CanBeBinaryOperator) ||
5949 (NumParams < 1) || (NumParams > 2))) {
5950 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005951 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005952 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005953 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005954 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005955 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005956 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005957 assert(CanBeBinaryOperator &&
5958 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005959 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005960 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005961
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005962 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005963 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005964 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005965
Douglas Gregord69246b2008-11-17 16:14:12 +00005966 // Overloaded operators other than operator() cannot be variadic.
5967 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005968 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005969 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005970 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005971 }
5972
5973 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005974 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5975 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005976 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005977 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005978 }
5979
5980 // C++ [over.inc]p1:
5981 // The user-defined function called operator++ implements the
5982 // prefix and postfix ++ operator. If this function is a member
5983 // function with no parameters, or a non-member function with one
5984 // parameter of class or enumeration type, it defines the prefix
5985 // increment operator ++ for objects of that type. If the function
5986 // is a member function with one parameter (which shall be of type
5987 // int) or a non-member function with two parameters (the second
5988 // of which shall be of type int), it defines the postfix
5989 // increment operator ++ for objects of that type.
5990 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5991 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5992 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005993 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005994 ParamIsInt = BT->getKind() == BuiltinType::Int;
5995
Chris Lattner2b786902008-11-21 07:50:02 +00005996 if (!ParamIsInt)
5997 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005998 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005999 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006000 }
6001
Douglas Gregord69246b2008-11-17 16:14:12 +00006002 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006003}
Chris Lattner3b024a32008-12-17 07:09:26 +00006004
Alexis Huntc88db062010-01-13 09:01:02 +00006005/// CheckLiteralOperatorDeclaration - Check whether the declaration
6006/// of this literal operator function is well-formed. If so, returns
6007/// false; otherwise, emits appropriate diagnostics and returns true.
6008bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6009 DeclContext *DC = FnDecl->getDeclContext();
6010 Decl::Kind Kind = DC->getDeclKind();
6011 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6012 Kind != Decl::LinkageSpec) {
6013 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6014 << FnDecl->getDeclName();
6015 return true;
6016 }
6017
6018 bool Valid = false;
6019
Alexis Hunt7dd26172010-04-07 23:11:06 +00006020 // template <char...> type operator "" name() is the only valid template
6021 // signature, and the only valid signature with no parameters.
6022 if (FnDecl->param_size() == 0) {
6023 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6024 // Must have only one template parameter
6025 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6026 if (Params->size() == 1) {
6027 NonTypeTemplateParmDecl *PmDecl =
6028 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006029
Alexis Hunt7dd26172010-04-07 23:11:06 +00006030 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006031 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6032 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6033 Valid = true;
6034 }
6035 }
6036 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006037 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006038 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6039
Alexis Huntc88db062010-01-13 09:01:02 +00006040 QualType T = (*Param)->getType();
6041
Alexis Hunt079a6f72010-04-07 22:57:35 +00006042 // unsigned long long int, long double, and any character type are allowed
6043 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006044 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6045 Context.hasSameType(T, Context.LongDoubleTy) ||
6046 Context.hasSameType(T, Context.CharTy) ||
6047 Context.hasSameType(T, Context.WCharTy) ||
6048 Context.hasSameType(T, Context.Char16Ty) ||
6049 Context.hasSameType(T, Context.Char32Ty)) {
6050 if (++Param == FnDecl->param_end())
6051 Valid = true;
6052 goto FinishedParams;
6053 }
6054
Alexis Hunt079a6f72010-04-07 22:57:35 +00006055 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006056 const PointerType *PT = T->getAs<PointerType>();
6057 if (!PT)
6058 goto FinishedParams;
6059 T = PT->getPointeeType();
6060 if (!T.isConstQualified())
6061 goto FinishedParams;
6062 T = T.getUnqualifiedType();
6063
6064 // Move on to the second parameter;
6065 ++Param;
6066
6067 // If there is no second parameter, the first must be a const char *
6068 if (Param == FnDecl->param_end()) {
6069 if (Context.hasSameType(T, Context.CharTy))
6070 Valid = true;
6071 goto FinishedParams;
6072 }
6073
6074 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6075 // are allowed as the first parameter to a two-parameter function
6076 if (!(Context.hasSameType(T, Context.CharTy) ||
6077 Context.hasSameType(T, Context.WCharTy) ||
6078 Context.hasSameType(T, Context.Char16Ty) ||
6079 Context.hasSameType(T, Context.Char32Ty)))
6080 goto FinishedParams;
6081
6082 // The second and final parameter must be an std::size_t
6083 T = (*Param)->getType().getUnqualifiedType();
6084 if (Context.hasSameType(T, Context.getSizeType()) &&
6085 ++Param == FnDecl->param_end())
6086 Valid = true;
6087 }
6088
6089 // FIXME: This diagnostic is absolutely terrible.
6090FinishedParams:
6091 if (!Valid) {
6092 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6093 << FnDecl->getDeclName();
6094 return true;
6095 }
6096
6097 return false;
6098}
6099
Douglas Gregor07665a62009-01-05 19:45:36 +00006100/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6101/// linkage specification, including the language and (if present)
6102/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6103/// the location of the language string literal, which is provided
6104/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6105/// the '{' brace. Otherwise, this linkage specification does not
6106/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006107Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6108 SourceLocation LangLoc,
6109 llvm::StringRef Lang,
6110 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006111 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006112 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006113 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006114 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006115 Language = LinkageSpecDecl::lang_cxx;
6116 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006117 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006118 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006119 }
Mike Stump11289f42009-09-09 15:08:12 +00006120
Chris Lattner438e5012008-12-17 07:13:27 +00006121 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006122
Douglas Gregor07665a62009-01-05 19:45:36 +00006123 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006124 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006125 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006126 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006127 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006128 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006129}
6130
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006131/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006132/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6133/// valid, it's the position of the closing '}' brace in a linkage
6134/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006135Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6136 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006137 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006138 if (LinkageSpec)
6139 PopDeclContext();
6140 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006141}
6142
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006143/// \brief Perform semantic analysis for the variable declaration that
6144/// occurs within a C++ catch clause, returning the newly-created
6145/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006146VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006147 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006148 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006149 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006150 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006151 QualType ExDeclType = TInfo->getType();
6152
Sebastian Redl54c04d42008-12-22 19:15:10 +00006153 // Arrays and functions decay.
6154 if (ExDeclType->isArrayType())
6155 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6156 else if (ExDeclType->isFunctionType())
6157 ExDeclType = Context.getPointerType(ExDeclType);
6158
6159 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6160 // The exception-declaration shall not denote a pointer or reference to an
6161 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006162 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006163 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006164 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006165 Invalid = true;
6166 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006167
Douglas Gregor104ee002010-03-08 01:47:36 +00006168 // GCC allows catching pointers and references to incomplete types
6169 // as an extension; so do we, but we warn by default.
6170
Sebastian Redl54c04d42008-12-22 19:15:10 +00006171 QualType BaseType = ExDeclType;
6172 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006173 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006174 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006175 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006176 BaseType = Ptr->getPointeeType();
6177 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006178 DK = diag::ext_catch_incomplete_ptr;
6179 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006180 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006181 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006182 BaseType = Ref->getPointeeType();
6183 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006184 DK = diag::ext_catch_incomplete_ref;
6185 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006186 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006187 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006188 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6189 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006190 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006191
Mike Stump11289f42009-09-09 15:08:12 +00006192 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006193 RequireNonAbstractType(Loc, ExDeclType,
6194 diag::err_abstract_type_in_decl,
6195 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006196 Invalid = true;
6197
John McCall2ca705e2010-07-24 00:37:23 +00006198 // Only the non-fragile NeXT runtime currently supports C++ catches
6199 // of ObjC types, and no runtime supports catching ObjC types by value.
6200 if (!Invalid && getLangOptions().ObjC1) {
6201 QualType T = ExDeclType;
6202 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6203 T = RT->getPointeeType();
6204
6205 if (T->isObjCObjectType()) {
6206 Diag(Loc, diag::err_objc_object_catch);
6207 Invalid = true;
6208 } else if (T->isObjCObjectPointerType()) {
6209 if (!getLangOptions().NeXTRuntime) {
6210 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6211 Invalid = true;
6212 } else if (!getLangOptions().ObjCNonFragileABI) {
6213 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6214 Invalid = true;
6215 }
6216 }
6217 }
6218
Mike Stump11289f42009-09-09 15:08:12 +00006219 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006220 Name, ExDeclType, TInfo, SC_None,
6221 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006222 ExDecl->setExceptionVariable(true);
6223
Douglas Gregor6de584c2010-03-05 23:38:39 +00006224 if (!Invalid) {
6225 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6226 // C++ [except.handle]p16:
6227 // The object declared in an exception-declaration or, if the
6228 // exception-declaration does not specify a name, a temporary (12.2) is
6229 // copy-initialized (8.5) from the exception object. [...]
6230 // The object is destroyed when the handler exits, after the destruction
6231 // of any automatic objects initialized within the handler.
6232 //
6233 // We just pretend to initialize the object with itself, then make sure
6234 // it can be destroyed later.
6235 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6236 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006237 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006238 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6239 SourceLocation());
6240 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006241 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006242 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006243 if (Result.isInvalid())
6244 Invalid = true;
6245 else
6246 FinalizeVarWithDestructor(ExDecl, RecordTy);
6247 }
6248 }
6249
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006250 if (Invalid)
6251 ExDecl->setInvalidDecl();
6252
6253 return ExDecl;
6254}
6255
6256/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6257/// handler.
John McCall48871652010-08-21 09:40:31 +00006258Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006259 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006260 bool Invalid = D.isInvalidType();
6261
6262 // Check for unexpanded parameter packs.
6263 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6264 UPPC_ExceptionType)) {
6265 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6266 D.getIdentifierLoc());
6267 Invalid = true;
6268 }
6269
Sebastian Redl54c04d42008-12-22 19:15:10 +00006270 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006271 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006272 LookupOrdinaryName,
6273 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006274 // The scope should be freshly made just for us. There is just no way
6275 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006276 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006277 if (PrevDecl->isTemplateParameter()) {
6278 // Maybe we will complain about the shadowed template parameter.
6279 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006280 }
6281 }
6282
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006283 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006284 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6285 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006286 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006287 }
6288
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006289 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006290 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006291 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006292
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006293 if (Invalid)
6294 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006295
Sebastian Redl54c04d42008-12-22 19:15:10 +00006296 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006297 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006298 PushOnScopeChains(ExDecl, S);
6299 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006300 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006301
Douglas Gregor758a8692009-06-17 21:51:59 +00006302 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006303 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006304}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006305
John McCall48871652010-08-21 09:40:31 +00006306Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006307 Expr *AssertExpr,
6308 Expr *AssertMessageExpr_) {
6309 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006310
Anders Carlsson54b26982009-03-14 00:33:21 +00006311 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6312 llvm::APSInt Value(32);
6313 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6314 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6315 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006316 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006317 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006318
Anders Carlsson54b26982009-03-14 00:33:21 +00006319 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006320 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006321 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006322 }
6323 }
Mike Stump11289f42009-09-09 15:08:12 +00006324
Douglas Gregoref68fee2010-12-15 23:55:21 +00006325 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6326 return 0;
6327
Mike Stump11289f42009-09-09 15:08:12 +00006328 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006329 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006330
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006331 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006332 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006333}
Sebastian Redlf769df52009-03-24 22:27:57 +00006334
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006335/// \brief Perform semantic analysis of the given friend type declaration.
6336///
6337/// \returns A friend declaration that.
6338FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6339 TypeSourceInfo *TSInfo) {
6340 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6341
6342 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006343 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006344
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006345 if (!getLangOptions().CPlusPlus0x) {
6346 // C++03 [class.friend]p2:
6347 // An elaborated-type-specifier shall be used in a friend declaration
6348 // for a class.*
6349 //
6350 // * The class-key of the elaborated-type-specifier is required.
6351 if (!ActiveTemplateInstantiations.empty()) {
6352 // Do not complain about the form of friend template types during
6353 // template instantiation; we will already have complained when the
6354 // template was declared.
6355 } else if (!T->isElaboratedTypeSpecifier()) {
6356 // If we evaluated the type to a record type, suggest putting
6357 // a tag in front.
6358 if (const RecordType *RT = T->getAs<RecordType>()) {
6359 RecordDecl *RD = RT->getDecl();
6360
6361 std::string InsertionText = std::string(" ") + RD->getKindName();
6362
6363 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6364 << (unsigned) RD->getTagKind()
6365 << T
6366 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6367 InsertionText);
6368 } else {
6369 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6370 << T
6371 << SourceRange(FriendLoc, TypeRange.getEnd());
6372 }
6373 } else if (T->getAs<EnumType>()) {
6374 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006375 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006376 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006377 }
6378 }
6379
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006380 // C++0x [class.friend]p3:
6381 // If the type specifier in a friend declaration designates a (possibly
6382 // cv-qualified) class type, that class is declared as a friend; otherwise,
6383 // the friend declaration is ignored.
6384
6385 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6386 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006387
6388 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6389}
6390
John McCallace48cd2010-10-19 01:40:49 +00006391/// Handle a friend tag declaration where the scope specifier was
6392/// templated.
6393Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6394 unsigned TagSpec, SourceLocation TagLoc,
6395 CXXScopeSpec &SS,
6396 IdentifierInfo *Name, SourceLocation NameLoc,
6397 AttributeList *Attr,
6398 MultiTemplateParamsArg TempParamLists) {
6399 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6400
6401 bool isExplicitSpecialization = false;
6402 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6403 bool Invalid = false;
6404
6405 if (TemplateParameterList *TemplateParams
6406 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6407 TempParamLists.get(),
6408 TempParamLists.size(),
6409 /*friend*/ true,
6410 isExplicitSpecialization,
6411 Invalid)) {
6412 --NumMatchedTemplateParamLists;
6413
6414 if (TemplateParams->size() > 0) {
6415 // This is a declaration of a class template.
6416 if (Invalid)
6417 return 0;
6418
6419 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6420 SS, Name, NameLoc, Attr,
6421 TemplateParams, AS_public).take();
6422 } else {
6423 // The "template<>" header is extraneous.
6424 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6425 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6426 isExplicitSpecialization = true;
6427 }
6428 }
6429
6430 if (Invalid) return 0;
6431
6432 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6433
6434 bool isAllExplicitSpecializations = true;
6435 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6436 if (TempParamLists.get()[I]->size()) {
6437 isAllExplicitSpecializations = false;
6438 break;
6439 }
6440 }
6441
6442 // FIXME: don't ignore attributes.
6443
6444 // If it's explicit specializations all the way down, just forget
6445 // about the template header and build an appropriate non-templated
6446 // friend. TODO: for source fidelity, remember the headers.
6447 if (isAllExplicitSpecializations) {
6448 ElaboratedTypeKeyword Keyword
6449 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6450 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6451 TagLoc, SS.getRange(), NameLoc);
6452 if (T.isNull())
6453 return 0;
6454
6455 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6456 if (isa<DependentNameType>(T)) {
6457 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6458 TL.setKeywordLoc(TagLoc);
6459 TL.setQualifierRange(SS.getRange());
6460 TL.setNameLoc(NameLoc);
6461 } else {
6462 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6463 TL.setKeywordLoc(TagLoc);
6464 TL.setQualifierRange(SS.getRange());
6465 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6466 }
6467
6468 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6469 TSI, FriendLoc);
6470 Friend->setAccess(AS_public);
6471 CurContext->addDecl(Friend);
6472 return Friend;
6473 }
6474
6475 // Handle the case of a templated-scope friend class. e.g.
6476 // template <class T> class A<T>::B;
6477 // FIXME: we don't support these right now.
6478 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6479 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6480 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6481 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6482 TL.setKeywordLoc(TagLoc);
6483 TL.setQualifierRange(SS.getRange());
6484 TL.setNameLoc(NameLoc);
6485
6486 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6487 TSI, FriendLoc);
6488 Friend->setAccess(AS_public);
6489 Friend->setUnsupportedFriend(true);
6490 CurContext->addDecl(Friend);
6491 return Friend;
6492}
6493
6494
John McCall11083da2009-09-16 22:47:08 +00006495/// Handle a friend type declaration. This works in tandem with
6496/// ActOnTag.
6497///
6498/// Notes on friend class templates:
6499///
6500/// We generally treat friend class declarations as if they were
6501/// declaring a class. So, for example, the elaborated type specifier
6502/// in a friend declaration is required to obey the restrictions of a
6503/// class-head (i.e. no typedefs in the scope chain), template
6504/// parameters are required to match up with simple template-ids, &c.
6505/// However, unlike when declaring a template specialization, it's
6506/// okay to refer to a template specialization without an empty
6507/// template parameter declaration, e.g.
6508/// friend class A<T>::B<unsigned>;
6509/// We permit this as a special case; if there are any template
6510/// parameters present at all, require proper matching, i.e.
6511/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006512Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006513 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006514 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006515
6516 assert(DS.isFriendSpecified());
6517 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6518
John McCall11083da2009-09-16 22:47:08 +00006519 // Try to convert the decl specifier to a type. This works for
6520 // friend templates because ActOnTag never produces a ClassTemplateDecl
6521 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006522 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006523 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6524 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006525 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006526 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006527
Douglas Gregor6c110f32010-12-16 01:14:37 +00006528 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6529 return 0;
6530
John McCall11083da2009-09-16 22:47:08 +00006531 // This is definitely an error in C++98. It's probably meant to
6532 // be forbidden in C++0x, too, but the specification is just
6533 // poorly written.
6534 //
6535 // The problem is with declarations like the following:
6536 // template <T> friend A<T>::foo;
6537 // where deciding whether a class C is a friend or not now hinges
6538 // on whether there exists an instantiation of A that causes
6539 // 'foo' to equal C. There are restrictions on class-heads
6540 // (which we declare (by fiat) elaborated friend declarations to
6541 // be) that makes this tractable.
6542 //
6543 // FIXME: handle "template <> friend class A<T>;", which
6544 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006545 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006546 Diag(Loc, diag::err_tagless_friend_type_template)
6547 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006548 return 0;
John McCall11083da2009-09-16 22:47:08 +00006549 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006550
John McCallaa74a0c2009-08-28 07:59:38 +00006551 // C++98 [class.friend]p1: A friend of a class is a function
6552 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006553 // This is fixed in DR77, which just barely didn't make the C++03
6554 // deadline. It's also a very silly restriction that seriously
6555 // affects inner classes and which nobody else seems to implement;
6556 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006557 //
6558 // But note that we could warn about it: it's always useless to
6559 // friend one of your own members (it's not, however, worthless to
6560 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006561
John McCall11083da2009-09-16 22:47:08 +00006562 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006563 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006564 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006565 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006566 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006567 TSI,
John McCall11083da2009-09-16 22:47:08 +00006568 DS.getFriendSpecLoc());
6569 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006570 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6571
6572 if (!D)
John McCall48871652010-08-21 09:40:31 +00006573 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006574
John McCall11083da2009-09-16 22:47:08 +00006575 D->setAccess(AS_public);
6576 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006577
John McCall48871652010-08-21 09:40:31 +00006578 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006579}
6580
John McCallde3fd222010-10-12 23:13:28 +00006581Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6582 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006583 const DeclSpec &DS = D.getDeclSpec();
6584
6585 assert(DS.isFriendSpecified());
6586 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6587
6588 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6590 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006591
6592 // C++ [class.friend]p1
6593 // A friend of a class is a function or class....
6594 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006595 // It *doesn't* see through dependent types, which is correct
6596 // according to [temp.arg.type]p3:
6597 // If a declaration acquires a function type through a
6598 // type dependent on a template-parameter and this causes
6599 // a declaration that does not use the syntactic form of a
6600 // function declarator to have a function type, the program
6601 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006602 if (!T->isFunctionType()) {
6603 Diag(Loc, diag::err_unexpected_friend);
6604
6605 // It might be worthwhile to try to recover by creating an
6606 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006607 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006608 }
6609
6610 // C++ [namespace.memdef]p3
6611 // - If a friend declaration in a non-local class first declares a
6612 // class or function, the friend class or function is a member
6613 // of the innermost enclosing namespace.
6614 // - The name of the friend is not found by simple name lookup
6615 // until a matching declaration is provided in that namespace
6616 // scope (either before or after the class declaration granting
6617 // friendship).
6618 // - If a friend function is called, its name may be found by the
6619 // name lookup that considers functions from namespaces and
6620 // classes associated with the types of the function arguments.
6621 // - When looking for a prior declaration of a class or a function
6622 // declared as a friend, scopes outside the innermost enclosing
6623 // namespace scope are not considered.
6624
John McCallde3fd222010-10-12 23:13:28 +00006625 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006626 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6627 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006628 assert(Name);
6629
Douglas Gregor6c110f32010-12-16 01:14:37 +00006630 // Check for unexpanded parameter packs.
6631 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6632 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6633 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6634 return 0;
6635
John McCall07e91c02009-08-06 02:15:43 +00006636 // The context we found the declaration in, or in which we should
6637 // create the declaration.
6638 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006639 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006640 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006641 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006642
John McCallde3fd222010-10-12 23:13:28 +00006643 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006644
John McCallde3fd222010-10-12 23:13:28 +00006645 // There are four cases here.
6646 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006647 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006648 // there as appropriate.
6649 // Recover from invalid scope qualifiers as if they just weren't there.
6650 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006651 // C++0x [namespace.memdef]p3:
6652 // If the name in a friend declaration is neither qualified nor
6653 // a template-id and the declaration is a function or an
6654 // elaborated-type-specifier, the lookup to determine whether
6655 // the entity has been previously declared shall not consider
6656 // any scopes outside the innermost enclosing namespace.
6657 // C++0x [class.friend]p11:
6658 // If a friend declaration appears in a local class and the name
6659 // specified is an unqualified name, a prior declaration is
6660 // looked up without considering scopes that are outside the
6661 // innermost enclosing non-class scope. For a friend function
6662 // declaration, if there is no prior declaration, the program is
6663 // ill-formed.
6664 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006665 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006666
John McCallf7cfb222010-10-13 05:45:15 +00006667 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006668 DC = CurContext;
6669 while (true) {
6670 // Skip class contexts. If someone can cite chapter and verse
6671 // for this behavior, that would be nice --- it's what GCC and
6672 // EDG do, and it seems like a reasonable intent, but the spec
6673 // really only says that checks for unqualified existing
6674 // declarations should stop at the nearest enclosing namespace,
6675 // not that they should only consider the nearest enclosing
6676 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006677 while (DC->isRecord())
6678 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006679
John McCall1f82f242009-11-18 22:49:29 +00006680 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006681
6682 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006683 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006684 break;
John McCallf7cfb222010-10-13 05:45:15 +00006685
John McCallf4776592010-10-14 22:22:28 +00006686 if (isTemplateId) {
6687 if (isa<TranslationUnitDecl>(DC)) break;
6688 } else {
6689 if (DC->isFileContext()) break;
6690 }
John McCall07e91c02009-08-06 02:15:43 +00006691 DC = DC->getParent();
6692 }
6693
6694 // C++ [class.friend]p1: A friend of a class is a function or
6695 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006696 // C++0x changes this for both friend types and functions.
6697 // Most C++ 98 compilers do seem to give an error here, so
6698 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006699 if (!Previous.empty() && DC->Equals(CurContext)
6700 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006701 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006702
John McCallccbc0322010-10-13 06:22:15 +00006703 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006704
John McCallde3fd222010-10-12 23:13:28 +00006705 // - There's a non-dependent scope specifier, in which case we
6706 // compute it and do a previous lookup there for a function
6707 // or function template.
6708 } else if (!SS.getScopeRep()->isDependent()) {
6709 DC = computeDeclContext(SS);
6710 if (!DC) return 0;
6711
6712 if (RequireCompleteDeclContext(SS, DC)) return 0;
6713
6714 LookupQualifiedName(Previous, DC);
6715
6716 // Ignore things found implicitly in the wrong scope.
6717 // TODO: better diagnostics for this case. Suggesting the right
6718 // qualified scope would be nice...
6719 LookupResult::Filter F = Previous.makeFilter();
6720 while (F.hasNext()) {
6721 NamedDecl *D = F.next();
6722 if (!DC->InEnclosingNamespaceSetOf(
6723 D->getDeclContext()->getRedeclContext()))
6724 F.erase();
6725 }
6726 F.done();
6727
6728 if (Previous.empty()) {
6729 D.setInvalidType();
6730 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6731 return 0;
6732 }
6733
6734 // C++ [class.friend]p1: A friend of a class is a function or
6735 // class that is not a member of the class . . .
6736 if (DC->Equals(CurContext))
6737 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6738
6739 // - There's a scope specifier that does not match any template
6740 // parameter lists, in which case we use some arbitrary context,
6741 // create a method or method template, and wait for instantiation.
6742 // - There's a scope specifier that does match some template
6743 // parameter lists, which we don't handle right now.
6744 } else {
6745 DC = CurContext;
6746 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006747 }
6748
John McCallf7cfb222010-10-13 05:45:15 +00006749 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006750 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006751 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6752 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6753 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006754 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006755 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6756 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006757 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006758 }
John McCall07e91c02009-08-06 02:15:43 +00006759 }
6760
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006761 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006762 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006763 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006764 IsDefinition,
6765 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006766 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006767
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006768 assert(ND->getDeclContext() == DC);
6769 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006770
John McCall759e32b2009-08-31 22:39:49 +00006771 // Add the function declaration to the appropriate lookup tables,
6772 // adjusting the redeclarations list as necessary. We don't
6773 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006774 //
John McCall759e32b2009-08-31 22:39:49 +00006775 // Also update the scope-based lookup if the target context's
6776 // lookup context is in lexical scope.
6777 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006778 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006779 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006780 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006781 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006782 }
John McCallaa74a0c2009-08-28 07:59:38 +00006783
6784 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006785 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006786 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006787 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006788 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006789
John McCallde3fd222010-10-12 23:13:28 +00006790 if (ND->isInvalidDecl())
6791 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006792 else {
6793 FunctionDecl *FD;
6794 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6795 FD = FTD->getTemplatedDecl();
6796 else
6797 FD = cast<FunctionDecl>(ND);
6798
6799 // Mark templated-scope function declarations as unsupported.
6800 if (FD->getNumTemplateParameterLists())
6801 FrD->setUnsupportedFriend(true);
6802 }
John McCallde3fd222010-10-12 23:13:28 +00006803
John McCall48871652010-08-21 09:40:31 +00006804 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006805}
6806
John McCall48871652010-08-21 09:40:31 +00006807void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6808 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006809
Sebastian Redlf769df52009-03-24 22:27:57 +00006810 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6811 if (!Fn) {
6812 Diag(DelLoc, diag::err_deleted_non_function);
6813 return;
6814 }
6815 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6816 Diag(DelLoc, diag::err_deleted_decl_not_first);
6817 Diag(Prev->getLocation(), diag::note_previous_declaration);
6818 // If the declaration wasn't the first, we delete the function anyway for
6819 // recovery.
6820 }
6821 Fn->setDeleted();
6822}
Sebastian Redl4c018662009-04-27 21:33:24 +00006823
6824static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6825 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6826 ++CI) {
6827 Stmt *SubStmt = *CI;
6828 if (!SubStmt)
6829 continue;
6830 if (isa<ReturnStmt>(SubStmt))
6831 Self.Diag(SubStmt->getSourceRange().getBegin(),
6832 diag::err_return_in_constructor_handler);
6833 if (!isa<Expr>(SubStmt))
6834 SearchForReturnInStmt(Self, SubStmt);
6835 }
6836}
6837
6838void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6839 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6840 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6841 SearchForReturnInStmt(*this, Handler);
6842 }
6843}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006844
Mike Stump11289f42009-09-09 15:08:12 +00006845bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006846 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006847 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6848 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006849
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006850 if (Context.hasSameType(NewTy, OldTy) ||
6851 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006852 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006853
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006854 // Check if the return types are covariant
6855 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006856
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006857 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006858 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6859 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006860 NewClassTy = NewPT->getPointeeType();
6861 OldClassTy = OldPT->getPointeeType();
6862 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006863 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6864 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6865 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6866 NewClassTy = NewRT->getPointeeType();
6867 OldClassTy = OldRT->getPointeeType();
6868 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006869 }
6870 }
Mike Stump11289f42009-09-09 15:08:12 +00006871
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006872 // The return types aren't either both pointers or references to a class type.
6873 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006874 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006875 diag::err_different_return_type_for_overriding_virtual_function)
6876 << New->getDeclName() << NewTy << OldTy;
6877 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006878
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006879 return true;
6880 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006881
Anders Carlssone60365b2009-12-31 18:34:24 +00006882 // C++ [class.virtual]p6:
6883 // If the return type of D::f differs from the return type of B::f, the
6884 // class type in the return type of D::f shall be complete at the point of
6885 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006886 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6887 if (!RT->isBeingDefined() &&
6888 RequireCompleteType(New->getLocation(), NewClassTy,
6889 PDiag(diag::err_covariant_return_incomplete)
6890 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006891 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006892 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006893
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006894 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006895 // Check if the new class derives from the old class.
6896 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6897 Diag(New->getLocation(),
6898 diag::err_covariant_return_not_derived)
6899 << New->getDeclName() << NewTy << OldTy;
6900 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6901 return true;
6902 }
Mike Stump11289f42009-09-09 15:08:12 +00006903
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006904 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006905 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006906 diag::err_covariant_return_inaccessible_base,
6907 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6908 // FIXME: Should this point to the return type?
6909 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006910 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6911 return true;
6912 }
6913 }
Mike Stump11289f42009-09-09 15:08:12 +00006914
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006915 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006916 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006917 Diag(New->getLocation(),
6918 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006919 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006920 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6921 return true;
6922 };
Mike Stump11289f42009-09-09 15:08:12 +00006923
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006924
6925 // The new class type must have the same or less qualifiers as the old type.
6926 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6927 Diag(New->getLocation(),
6928 diag::err_covariant_return_type_class_type_more_qualified)
6929 << New->getDeclName() << NewTy << OldTy;
6930 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6931 return true;
6932 };
Mike Stump11289f42009-09-09 15:08:12 +00006933
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006934 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006935}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006936
Douglas Gregor21920e372009-12-01 17:24:26 +00006937/// \brief Mark the given method pure.
6938///
6939/// \param Method the method to be marked pure.
6940///
6941/// \param InitRange the source range that covers the "0" initializer.
6942bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6943 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6944 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006945 return false;
6946 }
6947
6948 if (!Method->isInvalidDecl())
6949 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6950 << Method->getDeclName() << InitRange;
6951 return true;
6952}
6953
John McCall1f4ee7b2009-12-19 09:28:58 +00006954/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6955/// an initializer for the out-of-line declaration 'Dcl'. The scope
6956/// is a fresh scope pushed for just this purpose.
6957///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006958/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6959/// static data member of class X, names should be looked up in the scope of
6960/// class X.
John McCall48871652010-08-21 09:40:31 +00006961void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006962 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006963 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006964
John McCall1f4ee7b2009-12-19 09:28:58 +00006965 // We should only get called for declarations with scope specifiers, like:
6966 // int foo::bar;
6967 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006968 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006969}
6970
6971/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006972/// initializer for the out-of-line declaration 'D'.
6973void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006974 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006975 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006976
John McCall1f4ee7b2009-12-19 09:28:58 +00006977 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006978 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006979}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006980
6981/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6982/// C++ if/switch/while/for statement.
6983/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006984DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006985 // C++ 6.4p2:
6986 // The declarator shall not specify a function or an array.
6987 // The type-specifier-seq shall not contain typedef and shall not declare a
6988 // new class or enumeration.
6989 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6990 "Parser allowed 'typedef' as storage class of condition decl.");
6991
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006992 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006993 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6994 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006995
6996 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6997 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6998 // would be created and CXXConditionDeclExpr wants a VarDecl.
6999 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7000 << D.getSourceRange();
7001 return DeclResult();
7002 } else if (OwnedTag && OwnedTag->isDefinition()) {
7003 // The type-specifier-seq shall not declare a new class or enumeration.
7004 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7005 }
7006
John McCall48871652010-08-21 09:40:31 +00007007 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007008 if (!Dcl)
7009 return DeclResult();
7010
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007011 return Dcl;
7012}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007013
Douglas Gregor88d292c2010-05-13 16:44:06 +00007014void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7015 bool DefinitionRequired) {
7016 // Ignore any vtable uses in unevaluated operands or for classes that do
7017 // not have a vtable.
7018 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7019 CurContext->isDependentContext() ||
7020 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007021 return;
7022
Douglas Gregor88d292c2010-05-13 16:44:06 +00007023 // Try to insert this class into the map.
7024 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7025 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7026 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7027 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007028 // If we already had an entry, check to see if we are promoting this vtable
7029 // to required a definition. If so, we need to reappend to the VTableUses
7030 // list, since we may have already processed the first entry.
7031 if (DefinitionRequired && !Pos.first->second) {
7032 Pos.first->second = true;
7033 } else {
7034 // Otherwise, we can early exit.
7035 return;
7036 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007037 }
7038
7039 // Local classes need to have their virtual members marked
7040 // immediately. For all other classes, we mark their virtual members
7041 // at the end of the translation unit.
7042 if (Class->isLocalClass())
7043 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007044 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007045 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007046}
7047
Douglas Gregor88d292c2010-05-13 16:44:06 +00007048bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007049 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007050 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007051
Douglas Gregor88d292c2010-05-13 16:44:06 +00007052 // Note: The VTableUses vector could grow as a result of marking
7053 // the members of a class as "used", so we check the size each
7054 // time through the loop and prefer indices (with are stable) to
7055 // iterators (which are not).
7056 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007057 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007058 if (!Class)
7059 continue;
7060
7061 SourceLocation Loc = VTableUses[I].second;
7062
7063 // If this class has a key function, but that key function is
7064 // defined in another translation unit, we don't need to emit the
7065 // vtable even though we're using it.
7066 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007067 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007068 switch (KeyFunction->getTemplateSpecializationKind()) {
7069 case TSK_Undeclared:
7070 case TSK_ExplicitSpecialization:
7071 case TSK_ExplicitInstantiationDeclaration:
7072 // The key function is in another translation unit.
7073 continue;
7074
7075 case TSK_ExplicitInstantiationDefinition:
7076 case TSK_ImplicitInstantiation:
7077 // We will be instantiating the key function.
7078 break;
7079 }
7080 } else if (!KeyFunction) {
7081 // If we have a class with no key function that is the subject
7082 // of an explicit instantiation declaration, suppress the
7083 // vtable; it will live with the explicit instantiation
7084 // definition.
7085 bool IsExplicitInstantiationDeclaration
7086 = Class->getTemplateSpecializationKind()
7087 == TSK_ExplicitInstantiationDeclaration;
7088 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7089 REnd = Class->redecls_end();
7090 R != REnd; ++R) {
7091 TemplateSpecializationKind TSK
7092 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7093 if (TSK == TSK_ExplicitInstantiationDeclaration)
7094 IsExplicitInstantiationDeclaration = true;
7095 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7096 IsExplicitInstantiationDeclaration = false;
7097 break;
7098 }
7099 }
7100
7101 if (IsExplicitInstantiationDeclaration)
7102 continue;
7103 }
7104
7105 // Mark all of the virtual members of this class as referenced, so
7106 // that we can build a vtable. Then, tell the AST consumer that a
7107 // vtable for this class is required.
7108 MarkVirtualMembersReferenced(Loc, Class);
7109 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7110 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7111
7112 // Optionally warn if we're emitting a weak vtable.
7113 if (Class->getLinkage() == ExternalLinkage &&
7114 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007115 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007116 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7117 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007118 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007119 VTableUses.clear();
7120
Anders Carlsson82fccd02009-12-07 08:24:59 +00007121 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007122}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007123
Rafael Espindola5b334082010-03-26 00:36:59 +00007124void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7125 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007126 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7127 e = RD->method_end(); i != e; ++i) {
7128 CXXMethodDecl *MD = *i;
7129
7130 // C++ [basic.def.odr]p2:
7131 // [...] A virtual member function is used if it is not pure. [...]
7132 if (MD->isVirtual() && !MD->isPure())
7133 MarkDeclarationReferenced(Loc, MD);
7134 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007135
7136 // Only classes that have virtual bases need a VTT.
7137 if (RD->getNumVBases() == 0)
7138 return;
7139
7140 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7141 e = RD->bases_end(); i != e; ++i) {
7142 const CXXRecordDecl *Base =
7143 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007144 if (Base->getNumVBases() == 0)
7145 continue;
7146 MarkVirtualMembersReferenced(Loc, Base);
7147 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007148}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007149
7150/// SetIvarInitializers - This routine builds initialization ASTs for the
7151/// Objective-C implementation whose ivars need be initialized.
7152void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7153 if (!getLangOptions().CPlusPlus)
7154 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007155 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007156 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7157 CollectIvarsToConstructOrDestruct(OID, ivars);
7158 if (ivars.empty())
7159 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007160 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007161 for (unsigned i = 0; i < ivars.size(); i++) {
7162 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007163 if (Field->isInvalidDecl())
7164 continue;
7165
Alexis Hunt1d792652011-01-08 20:30:50 +00007166 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007167 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7168 InitializationKind InitKind =
7169 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7170
7171 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007172 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007173 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007174 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007175 // Note, MemberInit could actually come back empty if no initialization
7176 // is required (e.g., because it would call a trivial default constructor)
7177 if (!MemberInit.get() || MemberInit.isInvalid())
7178 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007179
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007180 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007181 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7182 SourceLocation(),
7183 MemberInit.takeAs<Expr>(),
7184 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007185 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007186
7187 // Be sure that the destructor is accessible and is marked as referenced.
7188 if (const RecordType *RecordTy
7189 = Context.getBaseElementType(Field->getType())
7190 ->getAs<RecordType>()) {
7191 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007192 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007193 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7194 CheckDestructorAccess(Field->getLocation(), Destructor,
7195 PDiag(diag::err_access_dtor_ivar)
7196 << Context.getBaseElementType(Field->getType()));
7197 }
7198 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007199 }
7200 ObjCImplementation->setIvarInitializers(Context,
7201 AllToInit.data(), AllToInit.size());
7202 }
7203}