blob: 186f23d73fe859995dceae65c4cf140e09a46373 [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"
Alexis Huntc5575cc2011-02-26 19:13:13 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000031#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000033#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000035#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000036#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000037
38using namespace clang;
39
Chris Lattner58258242008-04-10 02:22:51 +000040//===----------------------------------------------------------------------===//
41// CheckDefaultArgumentVisitor
42//===----------------------------------------------------------------------===//
43
Chris Lattnerb0d38442008-04-12 23:52:44 +000044namespace {
45 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
46 /// the default argument of a parameter to determine whether it
47 /// contains any ill-formed subexpressions. For example, this will
48 /// diagnose the use of local variables or parameters within the
49 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000050 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000051 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 Expr *DefaultArg;
53 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 public:
Mike Stump11289f42009-09-09 15:08:12 +000056 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 bool VisitExpr(Expr *Node);
60 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000061 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 };
Chris Lattner58258242008-04-10 02:22:51 +000063
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 /// VisitExpr - Visit all of the children of this expression.
65 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
66 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000067 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000068 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregor752a5952011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000524 // C++ [class.derived]p2:
525 // If a class is marked with the class-virt-specifier final and it appears
526 // as a base-type-specifier in a base-clause (10 class.derived), the program
527 // is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000528 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000529 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
530 << CXXBaseDecl->getDeclName();
531 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
532 << CXXBaseDecl->getDeclName();
533 return 0;
534 }
535
John McCall3696dcb2010-08-17 07:23:57 +0000536 if (BaseDecl->isInvalidDecl())
537 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000538
539 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000540 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000541 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000542 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000543}
544
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
546/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000547/// example:
548/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000549/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000550BaseResult
John McCall48871652010-08-21 09:40:31 +0000551Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000552 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000553 ParsedType basetype, SourceLocation BaseLoc,
554 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000555 if (!classdecl)
556 return true;
557
Douglas Gregorc40290e2009-03-09 23:48:35 +0000558 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000559 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000560 if (!Class)
561 return true;
562
Nick Lewycky19b9f952010-07-26 16:56:01 +0000563 TypeSourceInfo *TInfo = 0;
564 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000565
Douglas Gregor752a5952011-01-03 22:36:02 +0000566 if (EllipsisLoc.isInvalid() &&
567 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000568 UPPC_BaseType))
569 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000570
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000572 Virtual, Access, TInfo,
573 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000574 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000577}
Douglas Gregor556877c2008-04-13 21:30:24 +0000578
Douglas Gregor463421d2009-03-03 04:44:36 +0000579/// \brief Performs the actual work of attaching the given base class
580/// specifiers to a C++ class.
581bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
582 unsigned NumBases) {
583 if (NumBases == 0)
584 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000585
586 // Used to keep track of which base types we have already seen, so
587 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000588 // that the key is always the unqualified canonical type of the base
589 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000590 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
591
592 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000593 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000594 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000595 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000598 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000599 if (!Class->hasObjectMember()) {
600 if (const RecordType *FDTTy =
601 NewBaseType.getTypePtr()->getAs<RecordType>())
602 if (FDTTy->getDecl()->hasObjectMember())
603 Class->setHasObjectMember(true);
604 }
605
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 if (KnownBaseTypes[NewBaseType]) {
607 // C++ [class.mi]p3:
608 // A class shall not be specified as a direct base class of a
609 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000611 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000613 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000617 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000618
619 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 } else {
621 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 KnownBaseTypes[NewBaseType] = Bases[idx];
623 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000624 }
625 }
626
627 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000628 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000629
630 // Delete the remaining (good) base class specifiers, since their
631 // data has been copied into the CXXRecordDecl.
632 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000634
635 return Invalid;
636}
637
638/// ActOnBaseSpecifiers - Attach the given base specifiers to the
639/// class, after checking whether there are any duplicate base
640/// classes.
John McCall48871652010-08-21 09:40:31 +0000641void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000642 unsigned NumBases) {
643 if (!ClassDecl || !Bases || !NumBases)
644 return;
645
646 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000647 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000649}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000650
John McCalle78aac42010-03-10 03:28:59 +0000651static CXXRecordDecl *GetClassForType(QualType T) {
652 if (const RecordType *RT = T->getAs<RecordType>())
653 return cast<CXXRecordDecl>(RT->getDecl());
654 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
655 return ICT->getDecl();
656 else
657 return 0;
658}
659
Douglas Gregor36d1b142009-10-06 17:59:45 +0000660/// \brief Determine whether the type \p Derived is a C++ class that is
661/// derived from the type \p Base.
662bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
663 if (!getLangOptions().CPlusPlus)
664 return false;
John McCalle78aac42010-03-10 03:28:59 +0000665
666 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
667 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCalle78aac42010-03-10 03:28:59 +0000670 CXXRecordDecl *BaseRD = GetClassForType(Base);
671 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672 return false;
673
John McCall67da35c2010-02-04 22:26:26 +0000674 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
675 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000676}
677
678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
John McCalle78aac42010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000690 return false;
691
Douglas Gregor36d1b142009-10-06 17:59:45 +0000692 return DerivedRD->isDerivedFrom(BaseRD, Paths);
693}
694
Anders Carlssona70cff62010-04-24 19:06:50 +0000695void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000696 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000697 assert(BasePathArray.empty() && "Base path array must be empty!");
698 assert(Paths.isRecordingPaths() && "Must record paths!");
699
700 const CXXBasePath &Path = Paths.front();
701
702 // We first go backward and check if we have a virtual base.
703 // FIXME: It would be better if CXXBasePath had the base specifier for
704 // the nearest virtual base.
705 unsigned Start = 0;
706 for (unsigned I = Path.size(); I != 0; --I) {
707 if (Path[I - 1].Base->isVirtual()) {
708 Start = I - 1;
709 break;
710 }
711 }
712
713 // Now add all bases.
714 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000715 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000716}
717
Douglas Gregor88d292c2010-05-13 16:44:06 +0000718/// \brief Determine whether the given base path includes a virtual
719/// base class.
John McCallcf142162010-08-07 06:22:56 +0000720bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
721 for (CXXCastPath::const_iterator B = BasePath.begin(),
722 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000723 B != BEnd; ++B)
724 if ((*B)->isVirtual())
725 return true;
726
727 return false;
728}
729
Douglas Gregor36d1b142009-10-06 17:59:45 +0000730/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
731/// conversion (where Derived and Base are class types) is
732/// well-formed, meaning that the conversion is unambiguous (and
733/// that all of the base classes are accessible). Returns true
734/// and emits a diagnostic if the code is ill-formed, returns false
735/// otherwise. Loc is the location where this routine should point to
736/// if there is an error, and Range is the source range to highlight
737/// if there is an error.
738bool
739Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000740 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 unsigned AmbigiousBaseConvID,
742 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000743 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000744 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000745 // First, determine whether the path from Derived to Base is
746 // ambiguous. This is slightly more expensive than checking whether
747 // the Derived to Base conversion exists, because here we need to
748 // explore multiple paths to determine if there is an ambiguity.
749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
750 /*DetectVirtual=*/false);
751 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
752 assert(DerivationOkay &&
753 "Can only be used with a derived-to-base conversion");
754 (void)DerivationOkay;
755
756 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000757 if (InaccessibleBaseID) {
758 // Check that the base class can be accessed.
759 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
760 InaccessibleBaseID)) {
761 case AR_inaccessible:
762 return true;
763 case AR_accessible:
764 case AR_dependent:
765 case AR_delayed:
766 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000767 }
John McCall5b0829a2010-02-10 09:31:12 +0000768 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000769
770 // Build a base path if necessary.
771 if (BasePath)
772 BuildBasePathArray(Paths, *BasePath);
773 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000774 }
775
776 // We know that the derived-to-base conversion is ambiguous, and
777 // we're going to produce a diagnostic. Perform the derived-to-base
778 // search just one more time to compute all of the possible paths so
779 // that we can print them out. This is more expensive than any of
780 // the previous derived-to-base checks we've done, but at this point
781 // performance isn't as much of an issue.
782 Paths.clear();
783 Paths.setRecordingPaths(true);
784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
785 assert(StillOkay && "Can only be used with a derived-to-base conversion");
786 (void)StillOkay;
787
788 // Build up a textual representation of the ambiguous paths, e.g.,
789 // D -> B -> A, that will be used to illustrate the ambiguous
790 // conversions in the diagnostic. We only print one of the paths
791 // to each base class subobject.
792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
793
794 Diag(Loc, AmbigiousBaseConvID)
795 << Derived << Base << PathDisplayStr << Range << Name;
796 return true;
797}
798
799bool
800Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000801 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000802 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000803 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000804 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000805 IgnoreAccess ? 0
806 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000807 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000808 Loc, Range, DeclarationName(),
809 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000810}
811
812
813/// @brief Builds a string representing ambiguous paths from a
814/// specific derived class to different subobjects of the same base
815/// class.
816///
817/// This function builds a string that can be used in error messages
818/// to show the different paths that one can take through the
819/// inheritance hierarchy to go from the derived class to different
820/// subobjects of a base class. The result looks something like this:
821/// @code
822/// struct D -> struct B -> struct A
823/// struct D -> struct C -> struct A
824/// @endcode
825std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
826 std::string PathDisplayStr;
827 std::set<unsigned> DisplayedPaths;
828 for (CXXBasePaths::paths_iterator Path = Paths.begin();
829 Path != Paths.end(); ++Path) {
830 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
831 // We haven't displayed a path to this particular base
832 // class subobject yet.
833 PathDisplayStr += "\n ";
834 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
835 for (CXXBasePath::const_iterator Element = Path->begin();
836 Element != Path->end(); ++Element)
837 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
838 }
839 }
840
841 return PathDisplayStr;
842}
843
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000844//===----------------------------------------------------------------------===//
845// C++ class member Handling
846//===----------------------------------------------------------------------===//
847
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000849Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
850 SourceLocation ASLoc,
851 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000852 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000853 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000854 ASLoc, ColonLoc);
855 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000856 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000857}
858
Anders Carlssonfd835532011-01-20 05:57:14 +0000859/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000860void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000861 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
862 if (!MD || !MD->isVirtual())
863 return;
864
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000865 if (MD->isDependentContext())
866 return;
867
Anders Carlssonfd835532011-01-20 05:57:14 +0000868 // C++0x [class.virtual]p3:
869 // If a virtual function is marked with the virt-specifier override and does
870 // not override a member function of a base class,
871 // the program is ill-formed.
872 bool HasOverriddenMethods =
873 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +0000874 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000875 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000876 diag::err_function_marked_override_not_overriding)
877 << MD->getDeclName();
878 return;
879 }
Anders Carlsson7d59a682011-01-22 22:23:37 +0000880
881 // C++0x [class.derived]p8:
882 // In a class definition marked with the class-virt-specifier explicit,
883 // if a virtual member function that is neither implicitly-declared nor a
884 // destructor overrides a member function of a base class and it is not
885 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000886 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
887 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlsson7d59a682011-01-22 22:23:37 +0000888 llvm::SmallVector<const CXXMethodDecl*, 4>
889 OverriddenMethods(MD->begin_overridden_methods(),
890 MD->end_overridden_methods());
891
892 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
893 << MD->getDeclName()
894 << (unsigned)OverriddenMethods.size();
895
896 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
897 Diag(OverriddenMethods[I]->getLocation(),
898 diag::note_overridden_virtual_function);
899 }
Anders Carlssonfd835532011-01-20 05:57:14 +0000900}
901
Anders Carlsson3f610c72011-01-20 16:25:36 +0000902/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
903/// function overrides a virtual member function marked 'final', according to
904/// C++0x [class.virtual]p3.
905bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
906 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +0000907 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +0000908 return false;
909
910 Diag(New->getLocation(), diag::err_final_function_overridden)
911 << New->getDeclName();
912 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
913 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +0000914}
915
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000916/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
917/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
918/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000919/// any.
John McCall48871652010-08-21 09:40:31 +0000920Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000921Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000922 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000923 ExprTy *BW, const VirtSpecifiers &VS,
924 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000925 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000926 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000927 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
928 DeclarationName Name = NameInfo.getName();
929 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000930
931 // For anonymous bitfields, the location should point to the type.
932 if (Loc.isInvalid())
933 Loc = D.getSourceRange().getBegin();
934
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935 Expr *BitWidth = static_cast<Expr*>(BW);
936 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937
John McCallb1cd7da2010-06-04 08:34:12 +0000938 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000939 assert(!DS.isFriendSpecified());
940
John McCallb1cd7da2010-06-04 08:34:12 +0000941 bool isFunc = false;
942 if (D.isFunctionDeclarator())
943 isFunc = true;
944 else if (D.getNumTypeObjects() == 0 &&
945 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000946 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000947 isFunc = TDType->isFunctionType();
948 }
949
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000950 // C++ 9.2p6: A member shall not be declared to have automatic storage
951 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000952 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
953 // data members and cannot be applied to names declared const or static,
954 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000955 switch (DS.getStorageClassSpec()) {
956 case DeclSpec::SCS_unspecified:
957 case DeclSpec::SCS_typedef:
958 case DeclSpec::SCS_static:
959 // FALL THROUGH.
960 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000961 case DeclSpec::SCS_mutable:
962 if (isFunc) {
963 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000964 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000965 else
Chris Lattner3b054132008-11-19 05:08:23 +0000966 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Sebastian Redl8071edb2008-11-17 23:24:37 +0000968 // FIXME: It would be nicer if the keyword was ignored only for this
969 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000970 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000971 }
972 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000973 default:
974 if (DS.getStorageClassSpecLoc().isValid())
975 Diag(DS.getStorageClassSpecLoc(),
976 diag::err_storageclass_invalid_for_member);
977 else
978 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
979 D.getMutableDeclSpec().ClearStorageClassSpecs();
980 }
981
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000982 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
983 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000984 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000985
986 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000987 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000988 CXXScopeSpec &SS = D.getCXXScopeSpec();
989
990
991 if (SS.isSet() && !SS.isInvalid()) {
992 // The user provided a superfluous scope specifier inside a class
993 // definition:
994 //
995 // class X {
996 // int X::member;
997 // };
998 DeclContext *DC = 0;
999 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1000 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1001 << Name << FixItHint::CreateRemoval(SS.getRange());
1002 else
1003 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1004 << Name << SS.getRange();
1005
1006 SS.clear();
1007 }
1008
Douglas Gregor3447e762009-08-20 22:52:58 +00001009 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001010 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001011 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1012 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001013 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001014 } else {
John McCall48871652010-08-21 09:40:31 +00001015 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001016 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001017 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001018 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001019
1020 // Non-instance-fields can't have a bitfield.
1021 if (BitWidth) {
1022 if (Member->isInvalidDecl()) {
1023 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001024 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001025 // C++ 9.6p3: A bit-field shall not be a static member.
1026 // "static member 'A' cannot be a bit-field"
1027 Diag(Loc, diag::err_static_not_bitfield)
1028 << Name << BitWidth->getSourceRange();
1029 } else if (isa<TypedefDecl>(Member)) {
1030 // "typedef member 'x' cannot be a bit-field"
1031 Diag(Loc, diag::err_typedef_not_bitfield)
1032 << Name << BitWidth->getSourceRange();
1033 } else {
1034 // A function typedef ("typedef int f(); f a;").
1035 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1036 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001037 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001038 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Chris Lattnerd26760a2009-03-05 23:01:03 +00001041 BitWidth = 0;
1042 Member->setInvalidDecl();
1043 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001044
1045 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregor3447e762009-08-20 22:52:58 +00001047 // If we have declared a member function template, set the access of the
1048 // templated declaration as well.
1049 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1050 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001051 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001052
Anders Carlsson13a69102011-01-20 04:34:22 +00001053 if (VS.isOverrideSpecified()) {
1054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1055 if (!MD || !MD->isVirtual()) {
1056 Diag(Member->getLocStart(),
1057 diag::override_keyword_only_allowed_on_virtual_member_functions)
1058 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001059 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001060 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001061 }
1062 if (VS.isFinalSpecified()) {
1063 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1064 if (!MD || !MD->isVirtual()) {
1065 Diag(Member->getLocStart(),
1066 diag::override_keyword_only_allowed_on_virtual_member_functions)
1067 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001068 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001069 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001070 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001071
Douglas Gregorf2f08062011-03-08 17:10:18 +00001072 if (VS.getLastLocation().isValid()) {
1073 // Update the end location of a method that has a virt-specifiers.
1074 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1075 MD->setRangeEnd(VS.getLastLocation());
1076 }
1077
Anders Carlssonc87f8612011-01-20 06:29:02 +00001078 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001079
Douglas Gregor92751d42008-11-17 22:58:34 +00001080 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001081
Douglas Gregor0c880302009-03-11 23:00:04 +00001082 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001083 AddInitializerToDecl(Member, Init, false,
1084 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001085 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001086 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001087
Richard Smithb2bc2e62011-02-21 20:05:19 +00001088 FinalizeDeclaration(Member);
1089
John McCall25849ca2011-02-15 07:12:36 +00001090 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001091 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001092 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001093}
1094
Douglas Gregor15e77a22009-12-31 09:10:24 +00001095/// \brief Find the direct and/or virtual base specifiers that
1096/// correspond to the given base type, for use in base initialization
1097/// within a constructor.
1098static bool FindBaseInitializer(Sema &SemaRef,
1099 CXXRecordDecl *ClassDecl,
1100 QualType BaseType,
1101 const CXXBaseSpecifier *&DirectBaseSpec,
1102 const CXXBaseSpecifier *&VirtualBaseSpec) {
1103 // First, check for a direct base class.
1104 DirectBaseSpec = 0;
1105 for (CXXRecordDecl::base_class_const_iterator Base
1106 = ClassDecl->bases_begin();
1107 Base != ClassDecl->bases_end(); ++Base) {
1108 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1109 // We found a direct base of this type. That's what we're
1110 // initializing.
1111 DirectBaseSpec = &*Base;
1112 break;
1113 }
1114 }
1115
1116 // Check for a virtual base class.
1117 // FIXME: We might be able to short-circuit this if we know in advance that
1118 // there are no virtual bases.
1119 VirtualBaseSpec = 0;
1120 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1121 // We haven't found a base yet; search the class hierarchy for a
1122 // virtual base class.
1123 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1124 /*DetectVirtual=*/false);
1125 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1126 BaseType, Paths)) {
1127 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1128 Path != Paths.end(); ++Path) {
1129 if (Path->back().Base->isVirtual()) {
1130 VirtualBaseSpec = Path->back().Base;
1131 break;
1132 }
1133 }
1134 }
1135 }
1136
1137 return DirectBaseSpec || VirtualBaseSpec;
1138}
1139
Douglas Gregore8381c02008-11-05 04:29:56 +00001140/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001141MemInitResult
John McCall48871652010-08-21 09:40:31 +00001142Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001143 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001144 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001145 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001146 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001147 SourceLocation IdLoc,
1148 SourceLocation LParenLoc,
1149 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001150 SourceLocation RParenLoc,
1151 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001152 if (!ConstructorD)
1153 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001154
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001155 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001156
1157 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001158 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001159 if (!Constructor) {
1160 // The user wrote a constructor initializer on a function that is
1161 // not a C++ constructor. Ignore the error for now, because we may
1162 // have more member initializers coming; we'll diagnose it just
1163 // once in ActOnMemInitializers.
1164 return true;
1165 }
1166
1167 CXXRecordDecl *ClassDecl = Constructor->getParent();
1168
1169 // C++ [class.base.init]p2:
1170 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001171 // constructor's class and, if not found in that scope, are looked
1172 // up in the scope containing the constructor's definition.
1173 // [Note: if the constructor's class contains a member with the
1174 // same name as a direct or virtual base class of the class, a
1175 // mem-initializer-id naming the member or base class and composed
1176 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001177 // mem-initializer-id for the hidden base class may be specified
1178 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001179 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001180 // Look for a member, first.
1181 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001182 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001183 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001184 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001185 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001186
Douglas Gregor44e7df62011-01-04 00:32:56 +00001187 if (Member) {
1188 if (EllipsisLoc.isValid())
1189 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1190 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1191
Francois Pichetd583da02010-12-04 09:14:42 +00001192 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001193 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001194 }
1195
Francois Pichetd583da02010-12-04 09:14:42 +00001196 // Handle anonymous union case.
1197 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001198 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1199 if (EllipsisLoc.isValid())
1200 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1201 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1202
Francois Pichetd583da02010-12-04 09:14:42 +00001203 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1204 NumArgs, IdLoc,
1205 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001206 }
Francois Pichetd583da02010-12-04 09:14:42 +00001207 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001208 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001209 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001210 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001211 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001212
1213 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001214 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001215 } else {
1216 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1217 LookupParsedName(R, S, &SS);
1218
1219 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1220 if (!TyD) {
1221 if (R.isAmbiguous()) return true;
1222
John McCallda6841b2010-04-09 19:01:14 +00001223 // We don't want access-control diagnostics here.
1224 R.suppressDiagnostics();
1225
Douglas Gregora3b624a2010-01-19 06:46:48 +00001226 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1227 bool NotUnknownSpecialization = false;
1228 DeclContext *DC = computeDeclContext(SS, false);
1229 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1230 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1231
1232 if (!NotUnknownSpecialization) {
1233 // When the scope specifier can refer to a member of an unknown
1234 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001235 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1236 SS.getWithLocInContext(Context),
1237 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001238 if (BaseType.isNull())
1239 return true;
1240
Douglas Gregora3b624a2010-01-19 06:46:48 +00001241 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001242 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001243 }
1244 }
1245
Douglas Gregor15e77a22009-12-31 09:10:24 +00001246 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001247 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001248 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1249 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001250 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001251 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001252 // We have found a non-static data member with a similar
1253 // name to what was typed; complain and initialize that
1254 // member.
1255 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1256 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001257 << FixItHint::CreateReplacement(R.getNameLoc(),
1258 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001259 Diag(Member->getLocation(), diag::note_previous_decl)
1260 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001261
1262 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1263 LParenLoc, RParenLoc);
1264 }
1265 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1266 const CXXBaseSpecifier *DirectBaseSpec;
1267 const CXXBaseSpecifier *VirtualBaseSpec;
1268 if (FindBaseInitializer(*this, ClassDecl,
1269 Context.getTypeDeclType(Type),
1270 DirectBaseSpec, VirtualBaseSpec)) {
1271 // We have found a direct or virtual base class with a
1272 // similar name to what was typed; complain and initialize
1273 // that base class.
1274 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1275 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001276 << FixItHint::CreateReplacement(R.getNameLoc(),
1277 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001278
1279 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1280 : VirtualBaseSpec;
1281 Diag(BaseSpec->getSourceRange().getBegin(),
1282 diag::note_base_class_specified_here)
1283 << BaseSpec->getType()
1284 << BaseSpec->getSourceRange();
1285
Douglas Gregor15e77a22009-12-31 09:10:24 +00001286 TyD = Type;
1287 }
1288 }
1289 }
1290
Douglas Gregora3b624a2010-01-19 06:46:48 +00001291 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001292 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1293 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1294 return true;
1295 }
John McCallb5a0d312009-12-21 10:41:20 +00001296 }
1297
Douglas Gregora3b624a2010-01-19 06:46:48 +00001298 if (BaseType.isNull()) {
1299 BaseType = Context.getTypeDeclType(TyD);
1300 if (SS.isSet()) {
1301 NestedNameSpecifier *Qualifier =
1302 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001303
Douglas Gregora3b624a2010-01-19 06:46:48 +00001304 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001305 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001306 }
John McCallb5a0d312009-12-21 10:41:20 +00001307 }
1308 }
Mike Stump11289f42009-09-09 15:08:12 +00001309
John McCallbcd03502009-12-07 02:54:59 +00001310 if (!TInfo)
1311 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001312
John McCallbcd03502009-12-07 02:54:59 +00001313 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001314 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001315}
1316
John McCalle22a04a2009-11-04 23:02:40 +00001317/// Checks an initializer expression for use of uninitialized fields, such as
1318/// containing the field that is being initialized. Returns true if there is an
1319/// uninitialized field was used an updates the SourceLocation parameter; false
1320/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001321static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001322 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001323 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001324 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1325
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001326 if (isa<CallExpr>(S)) {
1327 // Do not descend into function calls or constructors, as the use
1328 // of an uninitialized field may be valid. One would have to inspect
1329 // the contents of the function/ctor to determine if it is safe or not.
1330 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1331 // may be safe, depending on what the function/ctor does.
1332 return false;
1333 }
1334 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1335 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001336
1337 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1338 // The member expression points to a static data member.
1339 assert(VD->isStaticDataMember() &&
1340 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001341 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001342 return false;
1343 }
1344
1345 if (isa<EnumConstantDecl>(RhsField)) {
1346 // The member expression points to an enum.
1347 return false;
1348 }
1349
John McCalle22a04a2009-11-04 23:02:40 +00001350 if (RhsField == LhsField) {
1351 // Initializing a field with itself. Throw a warning.
1352 // But wait; there are exceptions!
1353 // Exception #1: The field may not belong to this record.
1354 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001355 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001356 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1357 // Even though the field matches, it does not belong to this record.
1358 return false;
1359 }
1360 // None of the exceptions triggered; return true to indicate an
1361 // uninitialized field was used.
1362 *L = ME->getMemberLoc();
1363 return true;
1364 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001365 } else if (isa<SizeOfAlignOfExpr>(S)) {
1366 // sizeof/alignof doesn't reference contents, do not warn.
1367 return false;
1368 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1369 // address-of doesn't reference contents (the pointer may be dereferenced
1370 // in the same expression but it would be rare; and weird).
1371 if (UOE->getOpcode() == UO_AddrOf)
1372 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001373 }
John McCall8322c3a2011-02-13 04:07:26 +00001374 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001375 if (!*it) {
1376 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001377 continue;
1378 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001379 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1380 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001381 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001382 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001383}
1384
John McCallfaf5fb42010-08-26 23:41:50 +00001385MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001386Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001387 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001388 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001389 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001390 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1391 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1392 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001393 "Member must be a FieldDecl or IndirectFieldDecl");
1394
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001395 if (Member->isInvalidDecl())
1396 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001397
John McCalle22a04a2009-11-04 23:02:40 +00001398 // Diagnose value-uses of fields to initialize themselves, e.g.
1399 // foo(foo)
1400 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001401 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001402 for (unsigned i = 0; i < NumArgs; ++i) {
1403 SourceLocation L;
1404 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1405 // FIXME: Return true in the case when other fields are used before being
1406 // uninitialized. For example, let this field be the i'th field. When
1407 // initializing the i'th field, throw a warning if any of the >= i'th
1408 // fields are used, as they are not yet initialized.
1409 // Right now we are only handling the case where the i'th field uses
1410 // itself in its initializer.
1411 Diag(L, diag::warn_field_is_uninit);
1412 }
1413 }
1414
Eli Friedman8e1433b2009-07-29 19:44:27 +00001415 bool HasDependentArg = false;
1416 for (unsigned i = 0; i < NumArgs; i++)
1417 HasDependentArg |= Args[i]->isTypeDependent();
1418
Chandler Carruthd44c3102010-12-06 09:23:57 +00001419 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001420 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001421 // Can't check initialization for a member of dependent type or when
1422 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001423 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1424 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001425
1426 // Erase any temporaries within this evaluation context; we're not
1427 // going to track them in the AST, since we'll be rebuilding the
1428 // ASTs during template instantiation.
1429 ExprTemporaries.erase(
1430 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1431 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001432 } else {
1433 // Initialize the member.
1434 InitializedEntity MemberEntity =
1435 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1436 : InitializedEntity::InitializeMember(IndirectMember, 0);
1437 InitializationKind Kind =
1438 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001439
Chandler Carruthd44c3102010-12-06 09:23:57 +00001440 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1441
1442 ExprResult MemberInit =
1443 InitSeq.Perform(*this, MemberEntity, Kind,
1444 MultiExprArg(*this, Args, NumArgs), 0);
1445 if (MemberInit.isInvalid())
1446 return true;
1447
1448 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1449
1450 // C++0x [class.base.init]p7:
1451 // The initialization of each base and member constitutes a
1452 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001453 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001454 if (MemberInit.isInvalid())
1455 return true;
1456
1457 // If we are in a dependent context, template instantiation will
1458 // perform this type-checking again. Just save the arguments that we
1459 // received in a ParenListExpr.
1460 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1461 // of the information that we have about the member
1462 // initializer. However, deconstructing the ASTs is a dicey process,
1463 // and this approach is far more likely to get the corner cases right.
1464 if (CurContext->isDependentContext())
1465 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1466 RParenLoc);
1467 else
1468 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001469 }
1470
Chandler Carruthd44c3102010-12-06 09:23:57 +00001471 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001472 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001473 IdLoc, LParenLoc, Init,
1474 RParenLoc);
1475 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001476 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001477 IdLoc, LParenLoc, Init,
1478 RParenLoc);
1479 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001480}
1481
John McCallfaf5fb42010-08-26 23:41:50 +00001482MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001483Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1484 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001485 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001486 SourceLocation LParenLoc,
1487 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001488 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001489 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1490 if (!LangOpts.CPlusPlus0x)
1491 return Diag(Loc, diag::err_delegation_0x_only)
1492 << TInfo->getTypeLoc().getLocalSourceRange();
1493
Alexis Huntc5575cc2011-02-26 19:13:13 +00001494 // Initialize the object.
1495 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1496 QualType(ClassDecl->getTypeForDecl(), 0));
1497 InitializationKind Kind =
1498 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1499
1500 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1501
1502 ExprResult DelegationInit =
1503 InitSeq.Perform(*this, DelegationEntity, Kind,
1504 MultiExprArg(*this, Args, NumArgs), 0);
1505 if (DelegationInit.isInvalid())
1506 return true;
1507
1508 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1509 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1510 assert(Constructor && "Delegating constructor with no target?");
1511
1512 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1513
1514 // C++0x [class.base.init]p7:
1515 // The initialization of each base and member constitutes a
1516 // full-expression.
1517 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1518 if (DelegationInit.isInvalid())
1519 return true;
1520
1521 // If we are in a dependent context, template instantiation will
1522 // perform this type-checking again. Just save the arguments that we
1523 // received in a ParenListExpr.
1524 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1525 // of the information that we have about the base
1526 // initializer. However, deconstructing the ASTs is a dicey process,
1527 // and this approach is far more likely to get the corner cases right.
1528 if (CurContext->isDependentContext()) {
1529 ExprResult Init
1530 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1531 NumArgs, RParenLoc));
1532 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1533 Constructor, Init.takeAs<Expr>(),
1534 RParenLoc);
1535 }
1536
1537 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1538 DelegationInit.takeAs<Expr>(),
1539 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001540}
1541
1542MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001543Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001544 Expr **Args, unsigned NumArgs,
1545 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001546 CXXRecordDecl *ClassDecl,
1547 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001548 bool HasDependentArg = false;
1549 for (unsigned i = 0; i < NumArgs; i++)
1550 HasDependentArg |= Args[i]->isTypeDependent();
1551
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001552 SourceLocation BaseLoc
1553 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1554
1555 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1556 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1557 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1558
1559 // C++ [class.base.init]p2:
1560 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001561 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001562 // of that class, the mem-initializer is ill-formed. A
1563 // mem-initializer-list can initialize a base class using any
1564 // name that denotes that base class type.
1565 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1566
Douglas Gregor44e7df62011-01-04 00:32:56 +00001567 if (EllipsisLoc.isValid()) {
1568 // This is a pack expansion.
1569 if (!BaseType->containsUnexpandedParameterPack()) {
1570 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1571 << SourceRange(BaseLoc, RParenLoc);
1572
1573 EllipsisLoc = SourceLocation();
1574 }
1575 } else {
1576 // Check for any unexpanded parameter packs.
1577 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1578 return true;
1579
1580 for (unsigned I = 0; I != NumArgs; ++I)
1581 if (DiagnoseUnexpandedParameterPack(Args[I]))
1582 return true;
1583 }
1584
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001585 // Check for direct and virtual base classes.
1586 const CXXBaseSpecifier *DirectBaseSpec = 0;
1587 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1588 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001589 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1590 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001591 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1592 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001593
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001594 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1595 VirtualBaseSpec);
1596
1597 // C++ [base.class.init]p2:
1598 // Unless the mem-initializer-id names a nonstatic data member of the
1599 // constructor's class or a direct or virtual base of that class, the
1600 // mem-initializer is ill-formed.
1601 if (!DirectBaseSpec && !VirtualBaseSpec) {
1602 // If the class has any dependent bases, then it's possible that
1603 // one of those types will resolve to the same type as
1604 // BaseType. Therefore, just treat this as a dependent base
1605 // class initialization. FIXME: Should we try to check the
1606 // initialization anyway? It seems odd.
1607 if (ClassDecl->hasAnyDependentBases())
1608 Dependent = true;
1609 else
1610 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1611 << BaseType << Context.getTypeDeclType(ClassDecl)
1612 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1613 }
1614 }
1615
1616 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001617 // Can't check initialization for a base of dependent type or when
1618 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001619 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001620 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1621 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001622
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001623 // Erase any temporaries within this evaluation context; we're not
1624 // going to track them in the AST, since we'll be rebuilding the
1625 // ASTs during template instantiation.
1626 ExprTemporaries.erase(
1627 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1628 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001629
Alexis Hunt1d792652011-01-08 20:30:50 +00001630 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001631 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001632 LParenLoc,
1633 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001634 RParenLoc,
1635 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001636 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001637
1638 // C++ [base.class.init]p2:
1639 // If a mem-initializer-id is ambiguous because it designates both
1640 // a direct non-virtual base class and an inherited virtual base
1641 // class, the mem-initializer is ill-formed.
1642 if (DirectBaseSpec && VirtualBaseSpec)
1643 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001644 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001645
1646 CXXBaseSpecifier *BaseSpec
1647 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1648 if (!BaseSpec)
1649 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1650
1651 // Initialize the base.
1652 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001653 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001654 InitializationKind Kind =
1655 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1656
1657 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1658
John McCalldadc5752010-08-24 06:29:42 +00001659 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001660 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001661 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001662 if (BaseInit.isInvalid())
1663 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001664
1665 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001666
1667 // C++0x [class.base.init]p7:
1668 // The initialization of each base and member constitutes a
1669 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001670 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001671 if (BaseInit.isInvalid())
1672 return true;
1673
1674 // If we are in a dependent context, template instantiation will
1675 // perform this type-checking again. Just save the arguments that we
1676 // received in a ParenListExpr.
1677 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1678 // of the information that we have about the base
1679 // initializer. However, deconstructing the ASTs is a dicey process,
1680 // and this approach is far more likely to get the corner cases right.
1681 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001682 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001683 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1684 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001685 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001686 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001687 LParenLoc,
1688 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001689 RParenLoc,
1690 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001691 }
1692
Alexis Hunt1d792652011-01-08 20:30:50 +00001693 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001694 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001695 LParenLoc,
1696 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001697 RParenLoc,
1698 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001699}
1700
Anders Carlsson1b00e242010-04-23 03:10:23 +00001701/// ImplicitInitializerKind - How an implicit base or member initializer should
1702/// initialize its base or member.
1703enum ImplicitInitializerKind {
1704 IIK_Default,
1705 IIK_Copy,
1706 IIK_Move
1707};
1708
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001709static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001710BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001711 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001712 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001713 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001714 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001715 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001716 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1717 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001718
John McCalldadc5752010-08-24 06:29:42 +00001719 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001720
1721 switch (ImplicitInitKind) {
1722 case IIK_Default: {
1723 InitializationKind InitKind
1724 = InitializationKind::CreateDefault(Constructor->getLocation());
1725 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1726 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001727 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001728 break;
1729 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001730
Anders Carlsson1b00e242010-04-23 03:10:23 +00001731 case IIK_Copy: {
1732 ParmVarDecl *Param = Constructor->getParamDecl(0);
1733 QualType ParamType = Param->getType().getNonReferenceType();
1734
1735 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001736 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001737 Constructor->getLocation(), ParamType,
1738 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001739
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001740 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001741 QualType ArgTy =
1742 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1743 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001744
1745 CXXCastPath BasePath;
1746 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001747 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001748 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001749 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001750
Anders Carlsson1b00e242010-04-23 03:10:23 +00001751 InitializationKind InitKind
1752 = InitializationKind::CreateDirect(Constructor->getLocation(),
1753 SourceLocation(), SourceLocation());
1754 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1755 &CopyCtorArg, 1);
1756 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001757 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001758 break;
1759 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001760
Anders Carlsson1b00e242010-04-23 03:10:23 +00001761 case IIK_Move:
1762 assert(false && "Unhandled initializer kind!");
1763 }
John McCallb268a282010-08-23 23:25:46 +00001764
Douglas Gregora40433a2010-12-07 00:41:46 +00001765 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001766 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001767 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001768
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001769 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001770 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001771 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1772 SourceLocation()),
1773 BaseSpec->isVirtual(),
1774 SourceLocation(),
1775 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001776 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001777 SourceLocation());
1778
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001779 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001780}
1781
Anders Carlsson3c1db572010-04-23 02:15:47 +00001782static bool
1783BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001784 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001785 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001786 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001787 if (Field->isInvalidDecl())
1788 return true;
1789
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001790 SourceLocation Loc = Constructor->getLocation();
1791
Anders Carlsson423f5d82010-04-23 16:04:08 +00001792 if (ImplicitInitKind == IIK_Copy) {
1793 ParmVarDecl *Param = Constructor->getParamDecl(0);
1794 QualType ParamType = Param->getType().getNonReferenceType();
1795
1796 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001797 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001798 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001799
1800 // Build a reference to this field within the parameter.
1801 CXXScopeSpec SS;
1802 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1803 Sema::LookupMemberName);
1804 MemberLookup.addDecl(Field, AS_public);
1805 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001806 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001807 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001808 ParamType, Loc,
1809 /*IsArrow=*/false,
1810 SS,
1811 /*FirstQualifierInScope=*/0,
1812 MemberLookup,
1813 /*TemplateArgs=*/0);
1814 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001815 return true;
1816
Douglas Gregor94f9a482010-05-05 05:51:00 +00001817 // When the field we are copying is an array, create index variables for
1818 // each dimension of the array. We use these index variables to subscript
1819 // the source array, and other clients (e.g., CodeGen) will perform the
1820 // necessary iteration with these index variables.
1821 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1822 QualType BaseType = Field->getType();
1823 QualType SizeType = SemaRef.Context.getSizeType();
1824 while (const ConstantArrayType *Array
1825 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1826 // Create the iteration variable for this array index.
1827 IdentifierInfo *IterationVarName = 0;
1828 {
1829 llvm::SmallString<8> Str;
1830 llvm::raw_svector_ostream OS(Str);
1831 OS << "__i" << IndexVariables.size();
1832 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1833 }
1834 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00001835 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001836 IterationVarName, SizeType,
1837 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001838 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001839 IndexVariables.push_back(IterationVar);
1840
1841 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001842 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001843 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001844 assert(!IterationVarRef.isInvalid() &&
1845 "Reference to invented variable cannot fail!");
1846
1847 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001848 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001849 Loc,
John McCallb268a282010-08-23 23:25:46 +00001850 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001851 Loc);
1852 if (CopyCtorArg.isInvalid())
1853 return true;
1854
1855 BaseType = Array->getElementType();
1856 }
1857
1858 // Construct the entity that we will be initializing. For an array, this
1859 // will be first element in the array, which may require several levels
1860 // of array-subscript entities.
1861 llvm::SmallVector<InitializedEntity, 4> Entities;
1862 Entities.reserve(1 + IndexVariables.size());
1863 Entities.push_back(InitializedEntity::InitializeMember(Field));
1864 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1865 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1866 0,
1867 Entities.back()));
1868
1869 // Direct-initialize to use the copy constructor.
1870 InitializationKind InitKind =
1871 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1872
1873 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1874 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1875 &CopyCtorArgE, 1);
1876
John McCalldadc5752010-08-24 06:29:42 +00001877 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001878 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001879 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001880 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001881 if (MemberInit.isInvalid())
1882 return true;
1883
1884 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001885 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001886 MemberInit.takeAs<Expr>(), Loc,
1887 IndexVariables.data(),
1888 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001889 return false;
1890 }
1891
Anders Carlsson423f5d82010-04-23 16:04:08 +00001892 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1893
Anders Carlsson3c1db572010-04-23 02:15:47 +00001894 QualType FieldBaseElementType =
1895 SemaRef.Context.getBaseElementType(Field->getType());
1896
Anders Carlsson3c1db572010-04-23 02:15:47 +00001897 if (FieldBaseElementType->isRecordType()) {
1898 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001899 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001900 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001901
1902 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001903 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001904 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001905
Douglas Gregora40433a2010-12-07 00:41:46 +00001906 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001907 if (MemberInit.isInvalid())
1908 return true;
1909
1910 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001911 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001912 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001913 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001914 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001915 return false;
1916 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001917
1918 if (FieldBaseElementType->isReferenceType()) {
1919 SemaRef.Diag(Constructor->getLocation(),
1920 diag::err_uninitialized_member_in_ctor)
1921 << (int)Constructor->isImplicit()
1922 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1923 << 0 << Field->getDeclName();
1924 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1925 return true;
1926 }
1927
1928 if (FieldBaseElementType.isConstQualified()) {
1929 SemaRef.Diag(Constructor->getLocation(),
1930 diag::err_uninitialized_member_in_ctor)
1931 << (int)Constructor->isImplicit()
1932 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1933 << 1 << Field->getDeclName();
1934 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1935 return true;
1936 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001937
1938 // Nothing to initialize.
1939 CXXMemberInit = 0;
1940 return false;
1941}
John McCallbc83b3f2010-05-20 23:23:51 +00001942
1943namespace {
1944struct BaseAndFieldInfo {
1945 Sema &S;
1946 CXXConstructorDecl *Ctor;
1947 bool AnyErrorsInInits;
1948 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001949 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1950 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001951
1952 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1953 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1954 // FIXME: Handle implicit move constructors.
1955 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1956 IIK = IIK_Copy;
1957 else
1958 IIK = IIK_Default;
1959 }
1960};
1961}
1962
1963static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1964 FieldDecl *Top, FieldDecl *Field) {
1965
Chandler Carruth139e9622010-06-30 02:59:29 +00001966 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001967 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001968 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001969 return false;
1970 }
1971
1972 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1973 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1974 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001975 CXXRecordDecl *FieldClassDecl
1976 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001977
1978 // Even though union members never have non-trivial default
1979 // constructions in C++03, we still build member initializers for aggregate
1980 // record types which can be union members, and C++0x allows non-trivial
1981 // default constructors for union members, so we ensure that only one
1982 // member is initialized for these.
1983 if (FieldClassDecl->isUnion()) {
1984 // First check for an explicit initializer for one field.
1985 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1986 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001987 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001988 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001989
1990 // Once we've initialized a field of an anonymous union, the union
1991 // field in the class is also initialized, so exit immediately.
1992 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001993 } else if ((*FA)->isAnonymousStructOrUnion()) {
1994 if (CollectFieldInitializer(Info, Top, *FA))
1995 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001996 }
1997 }
1998
1999 // Fallthrough and construct a default initializer for the union as
2000 // a whole, which can call its default constructor if such a thing exists
2001 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2002 // behavior going forward with C++0x, when anonymous unions there are
2003 // finalized, we should revisit this.
2004 } else {
2005 // For structs, we simply descend through to initialize all members where
2006 // necessary.
2007 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2008 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2009 if (CollectFieldInitializer(Info, Top, *FA))
2010 return true;
2011 }
2012 }
John McCallbc83b3f2010-05-20 23:23:51 +00002013 }
2014
2015 // Don't try to build an implicit initializer if there were semantic
2016 // errors in any of the initializers (and therefore we might be
2017 // missing some that the user actually wrote).
2018 if (Info.AnyErrorsInInits)
2019 return false;
2020
Alexis Hunt1d792652011-01-08 20:30:50 +00002021 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002022 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2023 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002024
Francois Pichetd583da02010-12-04 09:14:42 +00002025 if (Init)
2026 Info.AllToInit.push_back(Init);
2027
John McCallbc83b3f2010-05-20 23:23:51 +00002028 return false;
2029}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002030
Eli Friedman9cf6b592009-11-09 19:20:36 +00002031bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002032Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2033 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002034 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002035 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002036 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002037 // Just store the initializers as written, they will be checked during
2038 // instantiation.
2039 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002040 Constructor->setNumCtorInitializers(NumInitializers);
2041 CXXCtorInitializer **baseOrMemberInitializers =
2042 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002043 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002044 NumInitializers * sizeof(CXXCtorInitializer*));
2045 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002046 }
2047
2048 return false;
2049 }
2050
John McCallbc83b3f2010-05-20 23:23:51 +00002051 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002052
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002053 // We need to build the initializer AST according to order of construction
2054 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002055 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002056 if (!ClassDecl)
2057 return true;
2058
Eli Friedman9cf6b592009-11-09 19:20:36 +00002059 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002060
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002061 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002062 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002063
2064 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002065 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002066 else
Francois Pichetd583da02010-12-04 09:14:42 +00002067 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002068 }
2069
Anders Carlsson43c64af2010-04-21 19:52:01 +00002070 // Keep track of the direct virtual bases.
2071 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2072 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2073 E = ClassDecl->bases_end(); I != E; ++I) {
2074 if (I->isVirtual())
2075 DirectVBases.insert(I);
2076 }
2077
Anders Carlssondb0a9652010-04-02 06:26:44 +00002078 // Push virtual bases before others.
2079 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2080 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2081
Alexis Hunt1d792652011-01-08 20:30:50 +00002082 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002083 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2084 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002085 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002086 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002087 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002088 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002089 VBase, IsInheritedVirtualBase,
2090 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002091 HadError = true;
2092 continue;
2093 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002094
John McCallbc83b3f2010-05-20 23:23:51 +00002095 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002096 }
2097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
John McCallbc83b3f2010-05-20 23:23:51 +00002099 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2101 E = ClassDecl->bases_end(); Base != E; ++Base) {
2102 // Virtuals are in the virtual base list and already constructed.
2103 if (Base->isVirtual())
2104 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002105
Alexis Hunt1d792652011-01-08 20:30:50 +00002106 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002107 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2108 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002109 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002110 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002111 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002112 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002113 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002114 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002115 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002116 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002117
John McCallbc83b3f2010-05-20 23:23:51 +00002118 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002119 }
2120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
John McCallbc83b3f2010-05-20 23:23:51 +00002122 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002123 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002124 E = ClassDecl->field_end(); Field != E; ++Field) {
2125 if ((*Field)->getType()->isIncompleteArrayType()) {
2126 assert(ClassDecl->hasFlexibleArrayMember() &&
2127 "Incomplete array type is not valid");
2128 continue;
2129 }
John McCallbc83b3f2010-05-20 23:23:51 +00002130 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002131 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002132 }
Mike Stump11289f42009-09-09 15:08:12 +00002133
John McCallbc83b3f2010-05-20 23:23:51 +00002134 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002135 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002136 Constructor->setNumCtorInitializers(NumInitializers);
2137 CXXCtorInitializer **baseOrMemberInitializers =
2138 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002139 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002140 NumInitializers * sizeof(CXXCtorInitializer*));
2141 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002142
John McCalla6309952010-03-16 21:39:52 +00002143 // Constructors implicitly reference the base and member
2144 // destructors.
2145 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2146 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002147 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002148
2149 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002150}
2151
Eli Friedman952c15d2009-07-21 19:28:10 +00002152static void *GetKeyForTopLevelField(FieldDecl *Field) {
2153 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002154 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002155 if (RT->getDecl()->isAnonymousStructOrUnion())
2156 return static_cast<void *>(RT->getDecl());
2157 }
2158 return static_cast<void *>(Field);
2159}
2160
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002161static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002162 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002163}
2164
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002165static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002166 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002167 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002168 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002169
Eli Friedman952c15d2009-07-21 19:28:10 +00002170 // For fields injected into the class via declaration of an anonymous union,
2171 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002172 FieldDecl *Field = Member->getAnyMember();
2173
John McCall23eebd92010-04-10 09:28:51 +00002174 // If the field is a member of an anonymous struct or union, our key
2175 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002176 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002177 if (RD->isAnonymousStructOrUnion()) {
2178 while (true) {
2179 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2180 if (Parent->isAnonymousStructOrUnion())
2181 RD = Parent;
2182 else
2183 break;
2184 }
2185
Anders Carlsson83ac3122010-03-30 16:19:37 +00002186 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Anders Carlssona942dcd2010-03-30 15:39:27 +00002189 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002190}
2191
Anders Carlssone857b292010-04-02 03:37:03 +00002192static void
2193DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002194 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002195 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002196 unsigned NumInits) {
2197 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002198 return;
Mike Stump11289f42009-09-09 15:08:12 +00002199
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002200 // Don't check initializers order unless the warning is enabled at the
2201 // location of at least one initializer.
2202 bool ShouldCheckOrder = false;
2203 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002204 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002205 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2206 Init->getSourceLocation())
2207 != Diagnostic::Ignored) {
2208 ShouldCheckOrder = true;
2209 break;
2210 }
2211 }
2212 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002213 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002214
John McCallbb7b6582010-04-10 07:37:23 +00002215 // Build the list of bases and members in the order that they'll
2216 // actually be initialized. The explicit initializers should be in
2217 // this same order but may be missing things.
2218 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002219
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002220 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2221
John McCallbb7b6582010-04-10 07:37:23 +00002222 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002223 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002224 ClassDecl->vbases_begin(),
2225 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002226 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002227
John McCallbb7b6582010-04-10 07:37:23 +00002228 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002229 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002230 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002231 if (Base->isVirtual())
2232 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002233 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235
John McCallbb7b6582010-04-10 07:37:23 +00002236 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002237 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2238 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002239 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002240
John McCallbb7b6582010-04-10 07:37:23 +00002241 unsigned NumIdealInits = IdealInitKeys.size();
2242 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002243
Alexis Hunt1d792652011-01-08 20:30:50 +00002244 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002245 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002246 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002247 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002248
2249 // Scan forward to try to find this initializer in the idealized
2250 // initializers list.
2251 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2252 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002253 break;
John McCallbb7b6582010-04-10 07:37:23 +00002254
2255 // If we didn't find this initializer, it must be because we
2256 // scanned past it on a previous iteration. That can only
2257 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002258 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002259 Sema::SemaDiagnosticBuilder D =
2260 SemaRef.Diag(PrevInit->getSourceLocation(),
2261 diag::warn_initializer_out_of_order);
2262
Francois Pichetd583da02010-12-04 09:14:42 +00002263 if (PrevInit->isAnyMemberInitializer())
2264 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002265 else
2266 D << 1 << PrevInit->getBaseClassInfo()->getType();
2267
Francois Pichetd583da02010-12-04 09:14:42 +00002268 if (Init->isAnyMemberInitializer())
2269 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002270 else
2271 D << 1 << Init->getBaseClassInfo()->getType();
2272
2273 // Move back to the initializer's location in the ideal list.
2274 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2275 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002276 break;
John McCallbb7b6582010-04-10 07:37:23 +00002277
2278 assert(IdealIndex != NumIdealInits &&
2279 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002280 }
John McCallbb7b6582010-04-10 07:37:23 +00002281
2282 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002283 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002284}
2285
John McCall23eebd92010-04-10 09:28:51 +00002286namespace {
2287bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002288 CXXCtorInitializer *Init,
2289 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002290 if (!PrevInit) {
2291 PrevInit = Init;
2292 return false;
2293 }
2294
2295 if (FieldDecl *Field = Init->getMember())
2296 S.Diag(Init->getSourceLocation(),
2297 diag::err_multiple_mem_initialization)
2298 << Field->getDeclName()
2299 << Init->getSourceRange();
2300 else {
John McCall424cec92011-01-19 06:33:43 +00002301 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002302 assert(BaseClass && "neither field nor base");
2303 S.Diag(Init->getSourceLocation(),
2304 diag::err_multiple_base_initialization)
2305 << QualType(BaseClass, 0)
2306 << Init->getSourceRange();
2307 }
2308 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2309 << 0 << PrevInit->getSourceRange();
2310
2311 return true;
2312}
2313
Alexis Hunt1d792652011-01-08 20:30:50 +00002314typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002315typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2316
2317bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002318 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002319 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002320 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002321 RecordDecl *Parent = Field->getParent();
2322 if (!Parent->isAnonymousStructOrUnion())
2323 return false;
2324
2325 NamedDecl *Child = Field;
2326 do {
2327 if (Parent->isUnion()) {
2328 UnionEntry &En = Unions[Parent];
2329 if (En.first && En.first != Child) {
2330 S.Diag(Init->getSourceLocation(),
2331 diag::err_multiple_mem_union_initialization)
2332 << Field->getDeclName()
2333 << Init->getSourceRange();
2334 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2335 << 0 << En.second->getSourceRange();
2336 return true;
2337 } else if (!En.first) {
2338 En.first = Child;
2339 En.second = Init;
2340 }
2341 }
2342
2343 Child = Parent;
2344 Parent = cast<RecordDecl>(Parent->getDeclContext());
2345 } while (Parent->isAnonymousStructOrUnion());
2346
2347 return false;
2348}
2349}
2350
Anders Carlssone857b292010-04-02 03:37:03 +00002351/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002352void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002353 SourceLocation ColonLoc,
2354 MemInitTy **meminits, unsigned NumMemInits,
2355 bool AnyErrors) {
2356 if (!ConstructorDecl)
2357 return;
2358
2359 AdjustDeclIfTemplate(ConstructorDecl);
2360
2361 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002362 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002363
2364 if (!Constructor) {
2365 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2366 return;
2367 }
2368
Alexis Hunt1d792652011-01-08 20:30:50 +00002369 CXXCtorInitializer **MemInits =
2370 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002371
2372 // Mapping for the duplicate initializers check.
2373 // For member initializers, this is keyed with a FieldDecl*.
2374 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002375 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002376
2377 // Mapping for the inconsistent anonymous-union initializers check.
2378 RedundantUnionMap MemberUnions;
2379
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002380 bool HadError = false;
2381 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002382 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002383
Abramo Bagnara341d7832010-05-26 18:09:23 +00002384 // Set the source order index.
2385 Init->setSourceOrder(i);
2386
Francois Pichetd583da02010-12-04 09:14:42 +00002387 if (Init->isAnyMemberInitializer()) {
2388 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002389 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2390 CheckRedundantUnionInit(*this, Init, MemberUnions))
2391 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002392 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002393 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2394 if (CheckRedundantInit(*this, Init, Members[Key]))
2395 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002396 } else {
2397 assert(Init->isDelegatingInitializer());
2398 // This must be the only initializer
2399 if (i != 0 || NumMemInits > 1) {
2400 Diag(MemInits[0]->getSourceLocation(),
2401 diag::err_delegating_initializer_alone)
2402 << MemInits[0]->getSourceRange();
2403 HadError = true;
2404 }
Anders Carlssone857b292010-04-02 03:37:03 +00002405 }
Anders Carlssone857b292010-04-02 03:37:03 +00002406 }
2407
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002408 if (HadError)
2409 return;
2410
Anders Carlssone857b292010-04-02 03:37:03 +00002411 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002412
Alexis Hunt1d792652011-01-08 20:30:50 +00002413 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002414}
2415
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002416void
John McCalla6309952010-03-16 21:39:52 +00002417Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2418 CXXRecordDecl *ClassDecl) {
2419 // Ignore dependent contexts.
2420 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002421 return;
John McCall1064d7e2010-03-16 05:22:47 +00002422
2423 // FIXME: all the access-control diagnostics are positioned on the
2424 // field/base declaration. That's probably good; that said, the
2425 // user might reasonably want to know why the destructor is being
2426 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002427
Anders Carlssondee9a302009-11-17 04:44:12 +00002428 // Non-static data members.
2429 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2430 E = ClassDecl->field_end(); I != E; ++I) {
2431 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002432 if (Field->isInvalidDecl())
2433 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002434 QualType FieldType = Context.getBaseElementType(Field->getType());
2435
2436 const RecordType* RT = FieldType->getAs<RecordType>();
2437 if (!RT)
2438 continue;
2439
2440 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2441 if (FieldClassDecl->hasTrivialDestructor())
2442 continue;
2443
Douglas Gregore71edda2010-07-01 22:47:18 +00002444 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002445 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002446 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002447 << Field->getDeclName()
2448 << FieldType);
2449
John McCalla6309952010-03-16 21:39:52 +00002450 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002451 }
2452
John McCall1064d7e2010-03-16 05:22:47 +00002453 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2454
Anders Carlssondee9a302009-11-17 04:44:12 +00002455 // Bases.
2456 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2457 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002458 // Bases are always records in a well-formed non-dependent class.
2459 const RecordType *RT = Base->getType()->getAs<RecordType>();
2460
2461 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002462 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002463 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002464
2465 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002466 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002467 if (BaseClassDecl->hasTrivialDestructor())
2468 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002469
Douglas Gregore71edda2010-07-01 22:47:18 +00002470 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002471
2472 // FIXME: caret should be on the start of the class name
2473 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002474 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002475 << Base->getType()
2476 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002477
John McCalla6309952010-03-16 21:39:52 +00002478 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002479 }
2480
2481 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002482 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2483 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002484
2485 // Bases are always records in a well-formed non-dependent class.
2486 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2487
2488 // Ignore direct virtual bases.
2489 if (DirectVirtualBases.count(RT))
2490 continue;
2491
Anders Carlssondee9a302009-11-17 04:44:12 +00002492 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002493 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002494 if (BaseClassDecl->hasTrivialDestructor())
2495 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002496
Douglas Gregore71edda2010-07-01 22:47:18 +00002497 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002498 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002499 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002500 << VBase->getType());
2501
John McCalla6309952010-03-16 21:39:52 +00002502 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002503 }
2504}
2505
John McCall48871652010-08-21 09:40:31 +00002506void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002507 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002508 return;
Mike Stump11289f42009-09-09 15:08:12 +00002509
Mike Stump11289f42009-09-09 15:08:12 +00002510 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002511 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002512 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002513}
2514
Mike Stump11289f42009-09-09 15:08:12 +00002515bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002516 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002517 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002518 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002519 else
John McCall02db245d2010-08-18 09:41:07 +00002520 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002521}
2522
Anders Carlssoneabf7702009-08-27 00:13:57 +00002523bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002524 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002525 if (!getLangOptions().CPlusPlus)
2526 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002527
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002528 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002529 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002530
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002531 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002532 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002533 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002534 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002535
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002536 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002537 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002538 }
Mike Stump11289f42009-09-09 15:08:12 +00002539
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002540 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002541 if (!RT)
2542 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002543
John McCall67da35c2010-02-04 22:26:26 +00002544 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002545
John McCall02db245d2010-08-18 09:41:07 +00002546 // We can't answer whether something is abstract until it has a
2547 // definition. If it's currently being defined, we'll walk back
2548 // over all the declarations when we have a full definition.
2549 const CXXRecordDecl *Def = RD->getDefinition();
2550 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002551 return false;
2552
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002553 if (!RD->isAbstract())
2554 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002555
Anders Carlssoneabf7702009-08-27 00:13:57 +00002556 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002557 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002558
John McCall02db245d2010-08-18 09:41:07 +00002559 return true;
2560}
2561
2562void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2563 // Check if we've already emitted the list of pure virtual functions
2564 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002565 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002566 return;
Mike Stump11289f42009-09-09 15:08:12 +00002567
Douglas Gregor4165bd62010-03-23 23:47:56 +00002568 CXXFinalOverriderMap FinalOverriders;
2569 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002570
Anders Carlssona2f74f32010-06-03 01:00:02 +00002571 // Keep a set of seen pure methods so we won't diagnose the same method
2572 // more than once.
2573 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2574
Douglas Gregor4165bd62010-03-23 23:47:56 +00002575 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2576 MEnd = FinalOverriders.end();
2577 M != MEnd;
2578 ++M) {
2579 for (OverridingMethods::iterator SO = M->second.begin(),
2580 SOEnd = M->second.end();
2581 SO != SOEnd; ++SO) {
2582 // C++ [class.abstract]p4:
2583 // A class is abstract if it contains or inherits at least one
2584 // pure virtual function for which the final overrider is pure
2585 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002586
Douglas Gregor4165bd62010-03-23 23:47:56 +00002587 //
2588 if (SO->second.size() != 1)
2589 continue;
2590
2591 if (!SO->second.front().Method->isPure())
2592 continue;
2593
Anders Carlssona2f74f32010-06-03 01:00:02 +00002594 if (!SeenPureMethods.insert(SO->second.front().Method))
2595 continue;
2596
Douglas Gregor4165bd62010-03-23 23:47:56 +00002597 Diag(SO->second.front().Method->getLocation(),
2598 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002599 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002600 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002601 }
2602
2603 if (!PureVirtualClassDiagSet)
2604 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2605 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002606}
2607
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002608namespace {
John McCall02db245d2010-08-18 09:41:07 +00002609struct AbstractUsageInfo {
2610 Sema &S;
2611 CXXRecordDecl *Record;
2612 CanQualType AbstractType;
2613 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002614
John McCall02db245d2010-08-18 09:41:07 +00002615 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2616 : S(S), Record(Record),
2617 AbstractType(S.Context.getCanonicalType(
2618 S.Context.getTypeDeclType(Record))),
2619 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002620
John McCall02db245d2010-08-18 09:41:07 +00002621 void DiagnoseAbstractType() {
2622 if (Invalid) return;
2623 S.DiagnoseAbstractType(Record);
2624 Invalid = true;
2625 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002626
John McCall02db245d2010-08-18 09:41:07 +00002627 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2628};
2629
2630struct CheckAbstractUsage {
2631 AbstractUsageInfo &Info;
2632 const NamedDecl *Ctx;
2633
2634 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2635 : Info(Info), Ctx(Ctx) {}
2636
2637 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2638 switch (TL.getTypeLocClass()) {
2639#define ABSTRACT_TYPELOC(CLASS, PARENT)
2640#define TYPELOC(CLASS, PARENT) \
2641 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2642#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002643 }
John McCall02db245d2010-08-18 09:41:07 +00002644 }
Mike Stump11289f42009-09-09 15:08:12 +00002645
John McCall02db245d2010-08-18 09:41:07 +00002646 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2647 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2648 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002649 if (!TL.getArg(I))
2650 continue;
2651
John McCall02db245d2010-08-18 09:41:07 +00002652 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2653 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002654 }
John McCall02db245d2010-08-18 09:41:07 +00002655 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002656
John McCall02db245d2010-08-18 09:41:07 +00002657 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2658 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2659 }
Mike Stump11289f42009-09-09 15:08:12 +00002660
John McCall02db245d2010-08-18 09:41:07 +00002661 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2662 // Visit the type parameters from a permissive context.
2663 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2664 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2665 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2666 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2667 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2668 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002669 }
John McCall02db245d2010-08-18 09:41:07 +00002670 }
Mike Stump11289f42009-09-09 15:08:12 +00002671
John McCall02db245d2010-08-18 09:41:07 +00002672 // Visit pointee types from a permissive context.
2673#define CheckPolymorphic(Type) \
2674 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2675 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2676 }
2677 CheckPolymorphic(PointerTypeLoc)
2678 CheckPolymorphic(ReferenceTypeLoc)
2679 CheckPolymorphic(MemberPointerTypeLoc)
2680 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002681
John McCall02db245d2010-08-18 09:41:07 +00002682 /// Handle all the types we haven't given a more specific
2683 /// implementation for above.
2684 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2685 // Every other kind of type that we haven't called out already
2686 // that has an inner type is either (1) sugar or (2) contains that
2687 // inner type in some way as a subobject.
2688 if (TypeLoc Next = TL.getNextTypeLoc())
2689 return Visit(Next, Sel);
2690
2691 // If there's no inner type and we're in a permissive context,
2692 // don't diagnose.
2693 if (Sel == Sema::AbstractNone) return;
2694
2695 // Check whether the type matches the abstract type.
2696 QualType T = TL.getType();
2697 if (T->isArrayType()) {
2698 Sel = Sema::AbstractArrayType;
2699 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002700 }
John McCall02db245d2010-08-18 09:41:07 +00002701 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2702 if (CT != Info.AbstractType) return;
2703
2704 // It matched; do some magic.
2705 if (Sel == Sema::AbstractArrayType) {
2706 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2707 << T << TL.getSourceRange();
2708 } else {
2709 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2710 << Sel << T << TL.getSourceRange();
2711 }
2712 Info.DiagnoseAbstractType();
2713 }
2714};
2715
2716void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2717 Sema::AbstractDiagSelID Sel) {
2718 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2719}
2720
2721}
2722
2723/// Check for invalid uses of an abstract type in a method declaration.
2724static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2725 CXXMethodDecl *MD) {
2726 // No need to do the check on definitions, which require that
2727 // the return/param types be complete.
2728 if (MD->isThisDeclarationADefinition())
2729 return;
2730
2731 // For safety's sake, just ignore it if we don't have type source
2732 // information. This should never happen for non-implicit methods,
2733 // but...
2734 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2735 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2736}
2737
2738/// Check for invalid uses of an abstract type within a class definition.
2739static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2740 CXXRecordDecl *RD) {
2741 for (CXXRecordDecl::decl_iterator
2742 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2743 Decl *D = *I;
2744 if (D->isImplicit()) continue;
2745
2746 // Methods and method templates.
2747 if (isa<CXXMethodDecl>(D)) {
2748 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2749 } else if (isa<FunctionTemplateDecl>(D)) {
2750 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2751 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2752
2753 // Fields and static variables.
2754 } else if (isa<FieldDecl>(D)) {
2755 FieldDecl *FD = cast<FieldDecl>(D);
2756 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2757 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2758 } else if (isa<VarDecl>(D)) {
2759 VarDecl *VD = cast<VarDecl>(D);
2760 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2761 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2762
2763 // Nested classes and class templates.
2764 } else if (isa<CXXRecordDecl>(D)) {
2765 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2766 } else if (isa<ClassTemplateDecl>(D)) {
2767 CheckAbstractClassUsage(Info,
2768 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2769 }
2770 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002771}
2772
Douglas Gregorc99f1552009-12-03 18:33:45 +00002773/// \brief Perform semantic checks on a class definition that has been
2774/// completing, introducing implicitly-declared members, checking for
2775/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002776void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002777 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002778 return;
2779
John McCall02db245d2010-08-18 09:41:07 +00002780 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2781 AbstractUsageInfo Info(*this, Record);
2782 CheckAbstractClassUsage(Info, Record);
2783 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002784
2785 // If this is not an aggregate type and has no user-declared constructor,
2786 // complain about any non-static data members of reference or const scalar
2787 // type, since they will never get initializers.
2788 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2789 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2790 bool Complained = false;
2791 for (RecordDecl::field_iterator F = Record->field_begin(),
2792 FEnd = Record->field_end();
2793 F != FEnd; ++F) {
2794 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002795 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002796 if (!Complained) {
2797 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2798 << Record->getTagKind() << Record;
2799 Complained = true;
2800 }
2801
2802 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2803 << F->getType()->isReferenceType()
2804 << F->getDeclName();
2805 }
2806 }
2807 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002808
Anders Carlssone771e762011-01-25 18:08:22 +00002809 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002810 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002811
2812 if (Record->getIdentifier()) {
2813 // C++ [class.mem]p13:
2814 // If T is the name of a class, then each of the following shall have a
2815 // name different from T:
2816 // - every member of every anonymous union that is a member of class T.
2817 //
2818 // C++ [class.mem]p14:
2819 // In addition, if class T has a user-declared constructor (12.1), every
2820 // non-static data member of class T shall have a name different from T.
2821 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002822 R.first != R.second; ++R.first) {
2823 NamedDecl *D = *R.first;
2824 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2825 isa<IndirectFieldDecl>(D)) {
2826 Diag(D->getLocation(), diag::err_member_name_of_class)
2827 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002828 break;
2829 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002830 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002831 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002832
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002833 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002834 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002835 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002836 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002837 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2838 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2839 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002840
2841 // See if a method overloads virtual methods in a base
2842 /// class without overriding any.
2843 if (!Record->isDependentType()) {
2844 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2845 MEnd = Record->method_end();
2846 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00002847 if (!(*M)->isStatic())
2848 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002849 }
2850 }
Sebastian Redl08905022011-02-05 19:23:19 +00002851
2852 // Declare inherited constructors. We do this eagerly here because:
2853 // - The standard requires an eager diagnostic for conflicting inherited
2854 // constructors from different classes.
2855 // - The lazy declaration of the other implicit constructors is so as to not
2856 // waste space and performance on classes that are not meant to be
2857 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2858 // have inherited constructors.
2859 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002860}
2861
2862/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00002863namespace {
2864 struct FindHiddenVirtualMethodData {
2865 Sema *S;
2866 CXXMethodDecl *Method;
2867 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2868 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2869 };
2870}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002871
2872/// \brief Member lookup function that determines whether a given C++
2873/// method overloads virtual methods in a base class without overriding any,
2874/// to be used with CXXRecordDecl::lookupInBases().
2875static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2876 CXXBasePath &Path,
2877 void *UserData) {
2878 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2879
2880 FindHiddenVirtualMethodData &Data
2881 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2882
2883 DeclarationName Name = Data.Method->getDeclName();
2884 assert(Name.getNameKind() == DeclarationName::Identifier);
2885
2886 bool foundSameNameMethod = false;
2887 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2888 for (Path.Decls = BaseRecord->lookup(Name);
2889 Path.Decls.first != Path.Decls.second;
2890 ++Path.Decls.first) {
2891 NamedDecl *D = *Path.Decls.first;
2892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002893 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002894 foundSameNameMethod = true;
2895 // Interested only in hidden virtual methods.
2896 if (!MD->isVirtual())
2897 continue;
2898 // If the method we are checking overrides a method from its base
2899 // don't warn about the other overloaded methods.
2900 if (!Data.S->IsOverload(Data.Method, MD, false))
2901 return true;
2902 // Collect the overload only if its hidden.
2903 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2904 overloadedMethods.push_back(MD);
2905 }
2906 }
2907
2908 if (foundSameNameMethod)
2909 Data.OverloadedMethods.append(overloadedMethods.begin(),
2910 overloadedMethods.end());
2911 return foundSameNameMethod;
2912}
2913
2914/// \brief See if a method overloads virtual methods in a base class without
2915/// overriding any.
2916void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2917 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2918 MD->getLocation()) == Diagnostic::Ignored)
2919 return;
2920 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2921 return;
2922
2923 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2924 /*bool RecordPaths=*/false,
2925 /*bool DetectVirtual=*/false);
2926 FindHiddenVirtualMethodData Data;
2927 Data.Method = MD;
2928 Data.S = this;
2929
2930 // Keep the base methods that were overriden or introduced in the subclass
2931 // by 'using' in a set. A base method not in this set is hidden.
2932 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2933 res.first != res.second; ++res.first) {
2934 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2935 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2936 E = MD->end_overridden_methods();
2937 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002938 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002939 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2940 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002941 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002942 }
2943
2944 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2945 !Data.OverloadedMethods.empty()) {
2946 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2947 << MD << (Data.OverloadedMethods.size() > 1);
2948
2949 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2950 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2951 Diag(overloadedMD->getLocation(),
2952 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2953 }
2954 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002955}
2956
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002957void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002958 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002959 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002960 SourceLocation RBrac,
2961 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002962 if (!TagDecl)
2963 return;
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002965 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002966
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002967 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002968 // strict aliasing violation!
2969 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002970 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002971
Douglas Gregor0be31a22010-07-02 17:43:08 +00002972 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002973 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002974}
2975
Douglas Gregor95755162010-07-01 05:10:53 +00002976namespace {
2977 /// \brief Helper class that collects exception specifications for
2978 /// implicitly-declared special member functions.
2979 class ImplicitExceptionSpecification {
2980 ASTContext &Context;
2981 bool AllowsAllExceptions;
2982 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2983 llvm::SmallVector<QualType, 4> Exceptions;
2984
2985 public:
2986 explicit ImplicitExceptionSpecification(ASTContext &Context)
2987 : Context(Context), AllowsAllExceptions(false) { }
2988
2989 /// \brief Whether the special member function should have any
2990 /// exception specification at all.
2991 bool hasExceptionSpecification() const {
2992 return !AllowsAllExceptions;
2993 }
2994
2995 /// \brief Whether the special member function should have a
2996 /// throw(...) exception specification (a Microsoft extension).
2997 bool hasAnyExceptionSpecification() const {
2998 return false;
2999 }
3000
3001 /// \brief The number of exceptions in the exception specification.
3002 unsigned size() const { return Exceptions.size(); }
3003
3004 /// \brief The set of exceptions in the exception specification.
3005 const QualType *data() const { return Exceptions.data(); }
3006
3007 /// \brief Note that
3008 void CalledDecl(CXXMethodDecl *Method) {
3009 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00003010 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00003011 return;
3012
3013 const FunctionProtoType *Proto
3014 = Method->getType()->getAs<FunctionProtoType>();
3015
3016 // If this function can throw any exceptions, make a note of that.
3017 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
3018 AllowsAllExceptions = true;
3019 ExceptionsSeen.clear();
3020 Exceptions.clear();
3021 return;
3022 }
3023
3024 // Record the exceptions in this function's exception specification.
3025 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3026 EEnd = Proto->exception_end();
3027 E != EEnd; ++E)
3028 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3029 Exceptions.push_back(*E);
3030 }
3031 };
3032}
3033
3034
Douglas Gregor05379422008-11-03 17:51:48 +00003035/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3036/// special functions, such as the default constructor, copy
3037/// constructor, or destructor, to the given C++ class (C++
3038/// [special]p1). This routine can only be executed just before the
3039/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003040void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00003041 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003042 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003043
Douglas Gregor54be3392010-07-01 17:57:27 +00003044 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00003045 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003046
Douglas Gregor330b9cf2010-07-02 21:50:04 +00003047 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3048 ++ASTContext::NumImplicitCopyAssignmentOperators;
3049
3050 // If we have a dynamic class, then the copy assignment operator may be
3051 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3052 // it shows up in the right place in the vtable and that we diagnose
3053 // problems with the implicit exception specification.
3054 if (ClassDecl->isDynamicClass())
3055 DeclareImplicitCopyAssignment(ClassDecl);
3056 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003057
Douglas Gregor7454c562010-07-02 20:37:36 +00003058 if (!ClassDecl->hasUserDeclaredDestructor()) {
3059 ++ASTContext::NumImplicitDestructors;
3060
3061 // If we have a dynamic class, then the destructor may be virtual, so we
3062 // have to declare the destructor immediately. This ensures that, e.g., it
3063 // shows up in the right place in the vtable and that we diagnose problems
3064 // with the implicit exception specification.
3065 if (ClassDecl->isDynamicClass())
3066 DeclareImplicitDestructor(ClassDecl);
3067 }
Douglas Gregor05379422008-11-03 17:51:48 +00003068}
3069
John McCall48871652010-08-21 09:40:31 +00003070void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003071 if (!D)
3072 return;
3073
3074 TemplateParameterList *Params = 0;
3075 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3076 Params = Template->getTemplateParameters();
3077 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3078 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3079 Params = PartialSpec->getTemplateParameters();
3080 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003081 return;
3082
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003083 for (TemplateParameterList::iterator Param = Params->begin(),
3084 ParamEnd = Params->end();
3085 Param != ParamEnd; ++Param) {
3086 NamedDecl *Named = cast<NamedDecl>(*Param);
3087 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003088 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003089 IdResolver.AddDecl(Named);
3090 }
3091 }
3092}
3093
John McCall48871652010-08-21 09:40:31 +00003094void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003095 if (!RecordD) return;
3096 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003097 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003098 PushDeclContext(S, Record);
3099}
3100
John McCall48871652010-08-21 09:40:31 +00003101void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003102 if (!RecordD) return;
3103 PopDeclContext();
3104}
3105
Douglas Gregor4d87df52008-12-16 21:30:33 +00003106/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3107/// parsing a top-level (non-nested) C++ class, and we are now
3108/// parsing those parts of the given Method declaration that could
3109/// not be parsed earlier (C++ [class.mem]p2), such as default
3110/// arguments. This action should enter the scope of the given
3111/// Method declaration as if we had just parsed the qualified method
3112/// name. However, it should not bring the parameters into scope;
3113/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003114void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003115}
3116
3117/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3118/// C++ method declaration. We're (re-)introducing the given
3119/// function parameter into scope for use in parsing later parts of
3120/// the method declaration. For example, we could see an
3121/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003122void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003123 if (!ParamD)
3124 return;
Mike Stump11289f42009-09-09 15:08:12 +00003125
John McCall48871652010-08-21 09:40:31 +00003126 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003127
3128 // If this parameter has an unparsed default argument, clear it out
3129 // to make way for the parsed default argument.
3130 if (Param->hasUnparsedDefaultArg())
3131 Param->setDefaultArg(0);
3132
John McCall48871652010-08-21 09:40:31 +00003133 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003134 if (Param->getDeclName())
3135 IdResolver.AddDecl(Param);
3136}
3137
3138/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3139/// processing the delayed method declaration for Method. The method
3140/// declaration is now considered finished. There may be a separate
3141/// ActOnStartOfFunctionDef action later (not necessarily
3142/// immediately!) for this method, if it was also defined inside the
3143/// class body.
John McCall48871652010-08-21 09:40:31 +00003144void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003145 if (!MethodD)
3146 return;
Mike Stump11289f42009-09-09 15:08:12 +00003147
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003148 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003149
John McCall48871652010-08-21 09:40:31 +00003150 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003151
3152 // Now that we have our default arguments, check the constructor
3153 // again. It could produce additional diagnostics or affect whether
3154 // the class has implicitly-declared destructors, among other
3155 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003156 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3157 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003158
3159 // Check the default arguments, which we may have added.
3160 if (!Method->isInvalidDecl())
3161 CheckCXXDefaultArguments(Method);
3162}
3163
Douglas Gregor831c93f2008-11-05 20:51:48 +00003164/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003165/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003166/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003167/// emit diagnostics and set the invalid bit to true. In any case, the type
3168/// will be updated to reflect a well-formed type for the constructor and
3169/// returned.
3170QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003171 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003172 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003173
3174 // C++ [class.ctor]p3:
3175 // A constructor shall not be virtual (10.3) or static (9.4). A
3176 // constructor can be invoked for a const, volatile or const
3177 // volatile object. A constructor shall not be declared const,
3178 // volatile, or const volatile (9.3.2).
3179 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003180 if (!D.isInvalidType())
3181 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3182 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3183 << SourceRange(D.getIdentifierLoc());
3184 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003185 }
John McCall8e7d6562010-08-26 03:08:43 +00003186 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003187 if (!D.isInvalidType())
3188 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3189 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3190 << SourceRange(D.getIdentifierLoc());
3191 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003192 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003195 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003196 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003197 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003198 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3199 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003200 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003201 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3202 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003203 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003204 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3205 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003206 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003207 }
Mike Stump11289f42009-09-09 15:08:12 +00003208
Douglas Gregordb9d6642011-01-26 05:01:58 +00003209 // C++0x [class.ctor]p4:
3210 // A constructor shall not be declared with a ref-qualifier.
3211 if (FTI.hasRefQualifier()) {
3212 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3213 << FTI.RefQualifierIsLValueRef
3214 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3215 D.setInvalidType();
3216 }
3217
Douglas Gregor831c93f2008-11-05 20:51:48 +00003218 // Rebuild the function type "R" without any type qualifiers (in
3219 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003220 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003221 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003222 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3223 return R;
3224
3225 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3226 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003227 EPI.RefQualifier = RQ_None;
3228
Chris Lattner38378bf2009-04-25 08:28:21 +00003229 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003230 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003231}
3232
Douglas Gregor4d87df52008-12-16 21:30:33 +00003233/// CheckConstructor - Checks a fully-formed constructor for
3234/// well-formedness, issuing any diagnostics required. Returns true if
3235/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003236void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003237 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003238 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3239 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003240 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003241
3242 // C++ [class.copy]p3:
3243 // A declaration of a constructor for a class X is ill-formed if
3244 // its first parameter is of type (optionally cv-qualified) X and
3245 // either there are no other parameters or else all other
3246 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003247 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003248 ((Constructor->getNumParams() == 1) ||
3249 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003250 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3251 Constructor->getTemplateSpecializationKind()
3252 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003253 QualType ParamType = Constructor->getParamDecl(0)->getType();
3254 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3255 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003256 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003257 const char *ConstRef
3258 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3259 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003260 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003261 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003262
3263 // FIXME: Rather that making the constructor invalid, we should endeavor
3264 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003265 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003266 }
3267 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003268}
3269
John McCalldeb646e2010-08-04 01:04:25 +00003270/// CheckDestructor - Checks a fully-formed destructor definition for
3271/// well-formedness, issuing any diagnostics required. Returns true
3272/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003273bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003274 CXXRecordDecl *RD = Destructor->getParent();
3275
3276 if (Destructor->isVirtual()) {
3277 SourceLocation Loc;
3278
3279 if (!Destructor->isImplicit())
3280 Loc = Destructor->getLocation();
3281 else
3282 Loc = RD->getLocation();
3283
3284 // If we have a virtual destructor, look up the deallocation function
3285 FunctionDecl *OperatorDelete = 0;
3286 DeclarationName Name =
3287 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003288 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003289 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003290
3291 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003292
3293 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003294 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003295
3296 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003297}
3298
Mike Stump11289f42009-09-09 15:08:12 +00003299static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003300FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3301 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3302 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003303 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003304}
3305
Douglas Gregor831c93f2008-11-05 20:51:48 +00003306/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3307/// the well-formednes of the destructor declarator @p D with type @p
3308/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003309/// emit diagnostics and set the declarator to invalid. Even if this happens,
3310/// will be updated to reflect a well-formed type for the destructor and
3311/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003312QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003313 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003314 // C++ [class.dtor]p1:
3315 // [...] A typedef-name that names a class is a class-name
3316 // (7.1.3); however, a typedef-name that names a class shall not
3317 // be used as the identifier in the declarator for a destructor
3318 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003319 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003320 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003321 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003322 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003323
3324 // C++ [class.dtor]p2:
3325 // A destructor is used to destroy objects of its class type. A
3326 // destructor takes no parameters, and no return type can be
3327 // specified for it (not even void). The address of a destructor
3328 // shall not be taken. A destructor shall not be static. A
3329 // destructor can be invoked for a const, volatile or const
3330 // volatile object. A destructor shall not be declared const,
3331 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003332 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003333 if (!D.isInvalidType())
3334 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3335 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003336 << SourceRange(D.getIdentifierLoc())
3337 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3338
John McCall8e7d6562010-08-26 03:08:43 +00003339 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003340 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003341 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003342 // Destructors don't have return types, but the parser will
3343 // happily parse something like:
3344 //
3345 // class X {
3346 // float ~X();
3347 // };
3348 //
3349 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003350 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3351 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3352 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003353 }
Mike Stump11289f42009-09-09 15:08:12 +00003354
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003355 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003356 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003357 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003358 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3359 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003360 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003361 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3362 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003363 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003364 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3365 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003366 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003367 }
3368
Douglas Gregordb9d6642011-01-26 05:01:58 +00003369 // C++0x [class.dtor]p2:
3370 // A destructor shall not be declared with a ref-qualifier.
3371 if (FTI.hasRefQualifier()) {
3372 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3373 << FTI.RefQualifierIsLValueRef
3374 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3375 D.setInvalidType();
3376 }
3377
Douglas Gregor831c93f2008-11-05 20:51:48 +00003378 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003379 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003380 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3381
3382 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003383 FTI.freeArgs();
3384 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003385 }
3386
Mike Stump11289f42009-09-09 15:08:12 +00003387 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003388 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003389 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003390 D.setInvalidType();
3391 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003392
3393 // Rebuild the function type "R" without any type qualifiers or
3394 // parameters (in case any of the errors above fired) and with
3395 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003396 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003397 if (!D.isInvalidType())
3398 return R;
3399
Douglas Gregor95755162010-07-01 05:10:53 +00003400 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003401 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3402 EPI.Variadic = false;
3403 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003404 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003405 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003406}
3407
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003408/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3409/// well-formednes of the conversion function declarator @p D with
3410/// type @p R. If there are any errors in the declarator, this routine
3411/// will emit diagnostics and return true. Otherwise, it will return
3412/// false. Either way, the type @p R will be updated to reflect a
3413/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003414void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003415 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003416 // C++ [class.conv.fct]p1:
3417 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003418 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003419 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003420 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003421 if (!D.isInvalidType())
3422 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3423 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3424 << SourceRange(D.getIdentifierLoc());
3425 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003426 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003427 }
John McCall212fa2e2010-04-13 00:04:31 +00003428
3429 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3430
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003431 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003432 // Conversion functions don't have return types, but the parser will
3433 // happily parse something like:
3434 //
3435 // class X {
3436 // float operator bool();
3437 // };
3438 //
3439 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003440 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3441 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3442 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003443 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003444 }
3445
John McCall212fa2e2010-04-13 00:04:31 +00003446 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3447
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003448 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003449 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003450 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3451
3452 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003453 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003454 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003455 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003456 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003457 D.setInvalidType();
3458 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003459
John McCall212fa2e2010-04-13 00:04:31 +00003460 // Diagnose "&operator bool()" and other such nonsense. This
3461 // is actually a gcc extension which we don't support.
3462 if (Proto->getResultType() != ConvType) {
3463 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3464 << Proto->getResultType();
3465 D.setInvalidType();
3466 ConvType = Proto->getResultType();
3467 }
3468
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003469 // C++ [class.conv.fct]p4:
3470 // The conversion-type-id shall not represent a function type nor
3471 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003472 if (ConvType->isArrayType()) {
3473 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3474 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003475 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003476 } else if (ConvType->isFunctionType()) {
3477 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3478 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003479 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003480 }
3481
3482 // Rebuild the function type "R" without any parameters (in case any
3483 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003484 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003485 if (D.isInvalidType())
3486 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003487
Douglas Gregor5fb53972009-01-14 15:45:31 +00003488 // C++0x explicit conversion operators.
3489 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003490 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003491 diag::warn_explicit_conversion_functions)
3492 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003493}
3494
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003495/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3496/// the declaration of the given C++ conversion function. This routine
3497/// is responsible for recording the conversion function in the C++
3498/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003499Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003500 assert(Conversion && "Expected to receive a conversion function declaration");
3501
Douglas Gregor4287b372008-12-12 08:25:50 +00003502 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003503
3504 // Make sure we aren't redeclaring the conversion function.
3505 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003506
3507 // C++ [class.conv.fct]p1:
3508 // [...] A conversion function is never used to convert a
3509 // (possibly cv-qualified) object to the (possibly cv-qualified)
3510 // same object type (or a reference to it), to a (possibly
3511 // cv-qualified) base class of that type (or a reference to it),
3512 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003513 // FIXME: Suppress this warning if the conversion function ends up being a
3514 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003515 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003516 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003517 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003518 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003519 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3520 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003521 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003522 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003523 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3524 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003525 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003526 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003527 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003528 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003529 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003530 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003531 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003532 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003533 }
3534
Douglas Gregor457104e2010-09-29 04:25:11 +00003535 if (FunctionTemplateDecl *ConversionTemplate
3536 = Conversion->getDescribedFunctionTemplate())
3537 return ConversionTemplate;
3538
John McCall48871652010-08-21 09:40:31 +00003539 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003540}
3541
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003542//===----------------------------------------------------------------------===//
3543// Namespace Handling
3544//===----------------------------------------------------------------------===//
3545
John McCallb1be5232010-08-26 09:15:37 +00003546
3547
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003548/// ActOnStartNamespaceDef - This is called at the start of a namespace
3549/// definition.
John McCall48871652010-08-21 09:40:31 +00003550Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003551 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003552 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00003553 SourceLocation IdentLoc,
3554 IdentifierInfo *II,
3555 SourceLocation LBrace,
3556 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003557 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3558 // For anonymous namespace, take the location of the left brace.
3559 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00003560 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003561 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003562 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003563
3564 Scope *DeclRegionScope = NamespcScope->getParent();
3565
Anders Carlssona7bcade2010-02-07 01:09:23 +00003566 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3567
John McCall2faf32c2010-12-10 02:59:44 +00003568 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3569 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003570
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003571 if (II) {
3572 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003573 // The identifier in an original-namespace-definition shall not
3574 // have been previously defined in the declarative region in
3575 // which the original-namespace-definition appears. The
3576 // identifier in an original-namespace-definition is the name of
3577 // the namespace. Subsequently in that declarative region, it is
3578 // treated as an original-namespace-name.
3579 //
3580 // Since namespace names are unique in their scope, and we don't
3581 // look through using directives, just
3582 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3583 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003584
Douglas Gregor91f84212008-12-11 16:49:14 +00003585 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3586 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003587 if (Namespc->isInline() != OrigNS->isInline()) {
3588 // inline-ness must match
3589 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3590 << Namespc->isInline();
3591 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3592 Namespc->setInvalidDecl();
3593 // Recover by ignoring the new namespace's inline status.
3594 Namespc->setInline(OrigNS->isInline());
3595 }
3596
Douglas Gregor91f84212008-12-11 16:49:14 +00003597 // Attach this namespace decl to the chain of extended namespace
3598 // definitions.
3599 OrigNS->setNextNamespace(Namespc);
3600 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003601
Mike Stump11289f42009-09-09 15:08:12 +00003602 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003603 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003604 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003605 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003606 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003607 } else if (PrevDecl) {
3608 // This is an invalid name redefinition.
3609 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3610 << Namespc->getDeclName();
3611 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3612 Namespc->setInvalidDecl();
3613 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003614 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003615 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003616 // This is the first "real" definition of the namespace "std", so update
3617 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003618 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003619 // We had already defined a dummy namespace "std". Link this new
3620 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003621 StdNS->setNextNamespace(Namespc);
3622 StdNS->setLocation(IdentLoc);
3623 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003624 }
3625
3626 // Make our StdNamespace cache point at the first real definition of the
3627 // "std" namespace.
3628 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003629 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003630
3631 PushOnScopeChains(Namespc, DeclRegionScope);
3632 } else {
John McCall4fa53422009-10-01 00:25:31 +00003633 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003634 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003635
3636 // Link the anonymous namespace into its parent.
3637 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003638 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003639 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3640 PrevDecl = TU->getAnonymousNamespace();
3641 TU->setAnonymousNamespace(Namespc);
3642 } else {
3643 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3644 PrevDecl = ND->getAnonymousNamespace();
3645 ND->setAnonymousNamespace(Namespc);
3646 }
3647
3648 // Link the anonymous namespace with its previous declaration.
3649 if (PrevDecl) {
3650 assert(PrevDecl->isAnonymousNamespace());
3651 assert(!PrevDecl->getNextNamespace());
3652 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3653 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003654
3655 if (Namespc->isInline() != PrevDecl->isInline()) {
3656 // inline-ness must match
3657 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3658 << Namespc->isInline();
3659 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3660 Namespc->setInvalidDecl();
3661 // Recover by ignoring the new namespace's inline status.
3662 Namespc->setInline(PrevDecl->isInline());
3663 }
John McCall0db42252009-12-16 02:06:49 +00003664 }
John McCall4fa53422009-10-01 00:25:31 +00003665
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003666 CurContext->addDecl(Namespc);
3667
John McCall4fa53422009-10-01 00:25:31 +00003668 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3669 // behaves as if it were replaced by
3670 // namespace unique { /* empty body */ }
3671 // using namespace unique;
3672 // namespace unique { namespace-body }
3673 // where all occurrences of 'unique' in a translation unit are
3674 // replaced by the same identifier and this identifier differs
3675 // from all other identifiers in the entire program.
3676
3677 // We just create the namespace with an empty name and then add an
3678 // implicit using declaration, just like the standard suggests.
3679 //
3680 // CodeGen enforces the "universally unique" aspect by giving all
3681 // declarations semantically contained within an anonymous
3682 // namespace internal linkage.
3683
John McCall0db42252009-12-16 02:06:49 +00003684 if (!PrevDecl) {
3685 UsingDirectiveDecl* UD
3686 = UsingDirectiveDecl::Create(Context, CurContext,
3687 /* 'using' */ LBrace,
3688 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00003689 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00003690 /* identifier */ SourceLocation(),
3691 Namespc,
3692 /* Ancestor */ CurContext);
3693 UD->setImplicit();
3694 CurContext->addDecl(UD);
3695 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003696 }
3697
3698 // Although we could have an invalid decl (i.e. the namespace name is a
3699 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003700 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3701 // for the namespace has the declarations that showed up in that particular
3702 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003703 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003704 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003705}
3706
Sebastian Redla6602e92009-11-23 15:34:23 +00003707/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3708/// is a namespace alias, returns the namespace it points to.
3709static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3710 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3711 return AD->getNamespace();
3712 return dyn_cast_or_null<NamespaceDecl>(D);
3713}
3714
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003715/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3716/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003717void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003718 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3719 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003720 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003721 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003722 if (Namespc->hasAttr<VisibilityAttr>())
3723 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003724}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003725
John McCall28a0cf72010-08-25 07:42:41 +00003726CXXRecordDecl *Sema::getStdBadAlloc() const {
3727 return cast_or_null<CXXRecordDecl>(
3728 StdBadAlloc.get(Context.getExternalSource()));
3729}
3730
3731NamespaceDecl *Sema::getStdNamespace() const {
3732 return cast_or_null<NamespaceDecl>(
3733 StdNamespace.get(Context.getExternalSource()));
3734}
3735
Douglas Gregorcdf87022010-06-29 17:53:46 +00003736/// \brief Retrieve the special "std" namespace, which may require us to
3737/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003738NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003739 if (!StdNamespace) {
3740 // The "std" namespace has not yet been defined, so build one implicitly.
3741 StdNamespace = NamespaceDecl::Create(Context,
3742 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003743 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00003744 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003745 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003746 }
3747
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003748 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003749}
3750
John McCall48871652010-08-21 09:40:31 +00003751Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003752 SourceLocation UsingLoc,
3753 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003754 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003755 SourceLocation IdentLoc,
3756 IdentifierInfo *NamespcName,
3757 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003758 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3759 assert(NamespcName && "Invalid NamespcName.");
3760 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003761
3762 // This can only happen along a recovery path.
3763 while (S->getFlags() & Scope::TemplateParamScope)
3764 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003765 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003766
Douglas Gregor889ceb72009-02-03 19:21:40 +00003767 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003768 NestedNameSpecifier *Qualifier = 0;
3769 if (SS.isSet())
3770 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3771
Douglas Gregor34074322009-01-14 22:20:51 +00003772 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003773 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3774 LookupParsedName(R, S, &SS);
3775 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003776 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003777
Douglas Gregorcdf87022010-06-29 17:53:46 +00003778 if (R.empty()) {
3779 // Allow "using namespace std;" or "using namespace ::std;" even if
3780 // "std" hasn't been defined yet, for GCC compatibility.
3781 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3782 NamespcName->isStr("std")) {
3783 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003784 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003785 R.resolveKind();
3786 }
3787 // Otherwise, attempt typo correction.
3788 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3789 CTC_NoKeywords, 0)) {
3790 if (R.getAsSingle<NamespaceDecl>() ||
3791 R.getAsSingle<NamespaceAliasDecl>()) {
3792 if (DeclContext *DC = computeDeclContext(SS, false))
3793 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3794 << NamespcName << DC << Corrected << SS.getRange()
3795 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3796 else
3797 Diag(IdentLoc, diag::err_using_directive_suggest)
3798 << NamespcName << Corrected
3799 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3800 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3801 << Corrected;
3802
3803 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003804 } else {
3805 R.clear();
3806 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003807 }
3808 }
3809 }
3810
John McCall9f3059a2009-10-09 21:13:30 +00003811 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003812 NamedDecl *Named = R.getFoundDecl();
3813 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3814 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003815 // C++ [namespace.udir]p1:
3816 // A using-directive specifies that the names in the nominated
3817 // namespace can be used in the scope in which the
3818 // using-directive appears after the using-directive. During
3819 // unqualified name lookup (3.4.1), the names appear as if they
3820 // were declared in the nearest enclosing namespace which
3821 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003822 // namespace. [Note: in this context, "contains" means "contains
3823 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003824
3825 // Find enclosing context containing both using-directive and
3826 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003827 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003828 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3829 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3830 CommonAncestor = CommonAncestor->getParent();
3831
Sebastian Redla6602e92009-11-23 15:34:23 +00003832 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00003833 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00003834 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003835 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003836 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003837 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003838 }
3839
Douglas Gregor889ceb72009-02-03 19:21:40 +00003840 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003841 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003842}
3843
3844void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3845 // If scope has associated entity, then using directive is at namespace
3846 // or translation unit scope. We add UsingDirectiveDecls, into
3847 // it's lookup structure.
3848 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003849 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003850 else
3851 // Otherwise it is block-sope. using-directives will affect lookup
3852 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003853 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003854}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003855
Douglas Gregorfec52632009-06-20 00:51:54 +00003856
John McCall48871652010-08-21 09:40:31 +00003857Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003858 AccessSpecifier AS,
3859 bool HasUsingKeyword,
3860 SourceLocation UsingLoc,
3861 CXXScopeSpec &SS,
3862 UnqualifiedId &Name,
3863 AttributeList *AttrList,
3864 bool IsTypeName,
3865 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003866 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003867
Douglas Gregor220f4272009-11-04 16:30:06 +00003868 switch (Name.getKind()) {
3869 case UnqualifiedId::IK_Identifier:
3870 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003871 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003872 case UnqualifiedId::IK_ConversionFunctionId:
3873 break;
3874
3875 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003876 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003877 // C++0x inherited constructors.
3878 if (getLangOptions().CPlusPlus0x) break;
3879
Douglas Gregor220f4272009-11-04 16:30:06 +00003880 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3881 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003882 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003883
3884 case UnqualifiedId::IK_DestructorName:
3885 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3886 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003887 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003888
3889 case UnqualifiedId::IK_TemplateId:
3890 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3891 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003892 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003893 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003894
3895 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3896 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003897 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003898 return 0;
John McCall3969e302009-12-08 07:46:18 +00003899
John McCalla0097262009-12-11 02:10:03 +00003900 // Warn about using declarations.
3901 // TODO: store that the declaration was written without 'using' and
3902 // talk about access decls instead of using decls in the
3903 // diagnostics.
3904 if (!HasUsingKeyword) {
3905 UsingLoc = Name.getSourceRange().getBegin();
3906
3907 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003908 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003909 }
3910
Douglas Gregorc4356532010-12-16 00:46:58 +00003911 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3912 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3913 return 0;
3914
John McCall3f746822009-11-17 05:59:44 +00003915 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003916 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003917 /* IsInstantiation */ false,
3918 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003919 if (UD)
3920 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003921
John McCall48871652010-08-21 09:40:31 +00003922 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003923}
3924
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003925/// \brief Determine whether a using declaration considers the given
3926/// declarations as "equivalent", e.g., if they are redeclarations of
3927/// the same entity or are both typedefs of the same type.
3928static bool
3929IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3930 bool &SuppressRedeclaration) {
3931 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3932 SuppressRedeclaration = false;
3933 return true;
3934 }
3935
3936 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3937 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3938 SuppressRedeclaration = true;
3939 return Context.hasSameType(TD1->getUnderlyingType(),
3940 TD2->getUnderlyingType());
3941 }
3942
3943 return false;
3944}
3945
3946
John McCall84d87672009-12-10 09:41:52 +00003947/// Determines whether to create a using shadow decl for a particular
3948/// decl, given the set of decls existing prior to this using lookup.
3949bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3950 const LookupResult &Previous) {
3951 // Diagnose finding a decl which is not from a base class of the
3952 // current class. We do this now because there are cases where this
3953 // function will silently decide not to build a shadow decl, which
3954 // will pre-empt further diagnostics.
3955 //
3956 // We don't need to do this in C++0x because we do the check once on
3957 // the qualifier.
3958 //
3959 // FIXME: diagnose the following if we care enough:
3960 // struct A { int foo; };
3961 // struct B : A { using A::foo; };
3962 // template <class T> struct C : A {};
3963 // template <class T> struct D : C<T> { using B::foo; } // <---
3964 // This is invalid (during instantiation) in C++03 because B::foo
3965 // resolves to the using decl in B, which is not a base class of D<T>.
3966 // We can't diagnose it immediately because C<T> is an unknown
3967 // specialization. The UsingShadowDecl in D<T> then points directly
3968 // to A::foo, which will look well-formed when we instantiate.
3969 // The right solution is to not collapse the shadow-decl chain.
3970 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3971 DeclContext *OrigDC = Orig->getDeclContext();
3972
3973 // Handle enums and anonymous structs.
3974 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3975 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3976 while (OrigRec->isAnonymousStructOrUnion())
3977 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3978
3979 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3980 if (OrigDC == CurContext) {
3981 Diag(Using->getLocation(),
3982 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003983 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00003984 Diag(Orig->getLocation(), diag::note_using_decl_target);
3985 return true;
3986 }
3987
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003988 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00003989 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003990 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00003991 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003992 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00003993 Diag(Orig->getLocation(), diag::note_using_decl_target);
3994 return true;
3995 }
3996 }
3997
3998 if (Previous.empty()) return false;
3999
4000 NamedDecl *Target = Orig;
4001 if (isa<UsingShadowDecl>(Target))
4002 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4003
John McCalla17e83e2009-12-11 02:33:26 +00004004 // If the target happens to be one of the previous declarations, we
4005 // don't have a conflict.
4006 //
4007 // FIXME: but we might be increasing its access, in which case we
4008 // should redeclare it.
4009 NamedDecl *NonTag = 0, *Tag = 0;
4010 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4011 I != E; ++I) {
4012 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004013 bool Result;
4014 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4015 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00004016
4017 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4018 }
4019
John McCall84d87672009-12-10 09:41:52 +00004020 if (Target->isFunctionOrFunctionTemplate()) {
4021 FunctionDecl *FD;
4022 if (isa<FunctionTemplateDecl>(Target))
4023 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4024 else
4025 FD = cast<FunctionDecl>(Target);
4026
4027 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00004028 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00004029 case Ovl_Overload:
4030 return false;
4031
4032 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00004033 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004034 break;
4035
4036 // We found a decl with the exact signature.
4037 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004038 // If we're in a record, we want to hide the target, so we
4039 // return true (without a diagnostic) to tell the caller not to
4040 // build a shadow decl.
4041 if (CurContext->isRecord())
4042 return true;
4043
4044 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00004045 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004046 break;
4047 }
4048
4049 Diag(Target->getLocation(), diag::note_using_decl_target);
4050 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4051 return true;
4052 }
4053
4054 // Target is not a function.
4055
John McCall84d87672009-12-10 09:41:52 +00004056 if (isa<TagDecl>(Target)) {
4057 // No conflict between a tag and a non-tag.
4058 if (!Tag) return false;
4059
John McCalle29c5cd2009-12-10 19:51:03 +00004060 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004061 Diag(Target->getLocation(), diag::note_using_decl_target);
4062 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4063 return true;
4064 }
4065
4066 // No conflict between a tag and a non-tag.
4067 if (!NonTag) return false;
4068
John McCalle29c5cd2009-12-10 19:51:03 +00004069 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004070 Diag(Target->getLocation(), diag::note_using_decl_target);
4071 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4072 return true;
4073}
4074
John McCall3f746822009-11-17 05:59:44 +00004075/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004076UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004077 UsingDecl *UD,
4078 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004079
4080 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004081 NamedDecl *Target = Orig;
4082 if (isa<UsingShadowDecl>(Target)) {
4083 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4084 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004085 }
4086
4087 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004088 = UsingShadowDecl::Create(Context, CurContext,
4089 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004090 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004091
4092 Shadow->setAccess(UD->getAccess());
4093 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4094 Shadow->setInvalidDecl();
4095
John McCall3f746822009-11-17 05:59:44 +00004096 if (S)
John McCall3969e302009-12-08 07:46:18 +00004097 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004098 else
John McCall3969e302009-12-08 07:46:18 +00004099 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004100
John McCall3969e302009-12-08 07:46:18 +00004101
John McCall84d87672009-12-10 09:41:52 +00004102 return Shadow;
4103}
John McCall3969e302009-12-08 07:46:18 +00004104
John McCall84d87672009-12-10 09:41:52 +00004105/// Hides a using shadow declaration. This is required by the current
4106/// using-decl implementation when a resolvable using declaration in a
4107/// class is followed by a declaration which would hide or override
4108/// one or more of the using decl's targets; for example:
4109///
4110/// struct Base { void foo(int); };
4111/// struct Derived : Base {
4112/// using Base::foo;
4113/// void foo(int);
4114/// };
4115///
4116/// The governing language is C++03 [namespace.udecl]p12:
4117///
4118/// When a using-declaration brings names from a base class into a
4119/// derived class scope, member functions in the derived class
4120/// override and/or hide member functions with the same name and
4121/// parameter types in a base class (rather than conflicting).
4122///
4123/// There are two ways to implement this:
4124/// (1) optimistically create shadow decls when they're not hidden
4125/// by existing declarations, or
4126/// (2) don't create any shadow decls (or at least don't make them
4127/// visible) until we've fully parsed/instantiated the class.
4128/// The problem with (1) is that we might have to retroactively remove
4129/// a shadow decl, which requires several O(n) operations because the
4130/// decl structures are (very reasonably) not designed for removal.
4131/// (2) avoids this but is very fiddly and phase-dependent.
4132void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004133 if (Shadow->getDeclName().getNameKind() ==
4134 DeclarationName::CXXConversionFunctionName)
4135 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4136
John McCall84d87672009-12-10 09:41:52 +00004137 // Remove it from the DeclContext...
4138 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004139
John McCall84d87672009-12-10 09:41:52 +00004140 // ...and the scope, if applicable...
4141 if (S) {
John McCall48871652010-08-21 09:40:31 +00004142 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004143 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004144 }
4145
John McCall84d87672009-12-10 09:41:52 +00004146 // ...and the using decl.
4147 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4148
4149 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004150 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004151}
4152
John McCalle61f2ba2009-11-18 02:36:19 +00004153/// Builds a using declaration.
4154///
4155/// \param IsInstantiation - Whether this call arises from an
4156/// instantiation of an unresolved using declaration. We treat
4157/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004158NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4159 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004160 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004161 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004162 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004163 bool IsInstantiation,
4164 bool IsTypeName,
4165 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004166 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004167 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004168 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004169
Anders Carlssonf038fc22009-08-28 05:49:21 +00004170 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004171
Anders Carlsson59140b32009-08-28 03:16:11 +00004172 if (SS.isEmpty()) {
4173 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004174 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004175 }
Mike Stump11289f42009-09-09 15:08:12 +00004176
John McCall84d87672009-12-10 09:41:52 +00004177 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004178 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004179 ForRedeclaration);
4180 Previous.setHideTags(false);
4181 if (S) {
4182 LookupName(Previous, S);
4183
4184 // It is really dumb that we have to do this.
4185 LookupResult::Filter F = Previous.makeFilter();
4186 while (F.hasNext()) {
4187 NamedDecl *D = F.next();
4188 if (!isDeclInScope(D, CurContext, S))
4189 F.erase();
4190 }
4191 F.done();
4192 } else {
4193 assert(IsInstantiation && "no scope in non-instantiation");
4194 assert(CurContext->isRecord() && "scope not record in instantiation");
4195 LookupQualifiedName(Previous, CurContext);
4196 }
4197
John McCall84d87672009-12-10 09:41:52 +00004198 // Check for invalid redeclarations.
4199 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4200 return 0;
4201
4202 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004203 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4204 return 0;
4205
John McCall84c16cf2009-11-12 03:15:40 +00004206 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004207 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004208 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004209 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004210 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004211 // FIXME: not all declaration name kinds are legal here
4212 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4213 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004214 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004215 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004216 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004217 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4218 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004219 }
John McCallb96ec562009-12-04 22:46:56 +00004220 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004221 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4222 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004223 }
John McCallb96ec562009-12-04 22:46:56 +00004224 D->setAccess(AS);
4225 CurContext->addDecl(D);
4226
4227 if (!LookupContext) return D;
4228 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004229
John McCall0b66eb32010-05-01 00:40:08 +00004230 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004231 UD->setInvalidDecl();
4232 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004233 }
4234
Sebastian Redl08905022011-02-05 19:23:19 +00004235 // Constructor inheriting using decls get special treatment.
4236 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4237 if (CheckInheritedConstructorUsingDecl(UD))
4238 UD->setInvalidDecl();
4239 return UD;
4240 }
4241
4242 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004243
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004244 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004245
John McCall3969e302009-12-08 07:46:18 +00004246 // Unlike most lookups, we don't always want to hide tag
4247 // declarations: tag names are visible through the using declaration
4248 // even if hidden by ordinary names, *except* in a dependent context
4249 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004250 if (!IsInstantiation)
4251 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004252
John McCall27b18f82009-11-17 02:14:36 +00004253 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004254
John McCall9f3059a2009-10-09 21:13:30 +00004255 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004256 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004257 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004258 UD->setInvalidDecl();
4259 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004260 }
4261
John McCallb96ec562009-12-04 22:46:56 +00004262 if (R.isAmbiguous()) {
4263 UD->setInvalidDecl();
4264 return UD;
4265 }
Mike Stump11289f42009-09-09 15:08:12 +00004266
John McCalle61f2ba2009-11-18 02:36:19 +00004267 if (IsTypeName) {
4268 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004269 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004270 Diag(IdentLoc, diag::err_using_typename_non_type);
4271 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4272 Diag((*I)->getUnderlyingDecl()->getLocation(),
4273 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004274 UD->setInvalidDecl();
4275 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004276 }
4277 } else {
4278 // If we asked for a non-typename and we got a type, error out,
4279 // but only if this is an instantiation of an unresolved using
4280 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004281 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004282 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4283 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004284 UD->setInvalidDecl();
4285 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004286 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004287 }
4288
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004289 // C++0x N2914 [namespace.udecl]p6:
4290 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004291 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004292 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4293 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004294 UD->setInvalidDecl();
4295 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004296 }
Mike Stump11289f42009-09-09 15:08:12 +00004297
John McCall84d87672009-12-10 09:41:52 +00004298 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4299 if (!CheckUsingShadowDecl(UD, *I, Previous))
4300 BuildUsingShadowDecl(S, UD, *I);
4301 }
John McCall3f746822009-11-17 05:59:44 +00004302
4303 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004304}
4305
Sebastian Redl08905022011-02-05 19:23:19 +00004306/// Additional checks for a using declaration referring to a constructor name.
4307bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4308 if (UD->isTypeName()) {
4309 // FIXME: Cannot specify typename when specifying constructor
4310 return true;
4311 }
4312
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004313 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004314 assert(SourceType &&
4315 "Using decl naming constructor doesn't have type in scope spec.");
4316 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4317
4318 // Check whether the named type is a direct base class.
4319 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4320 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4321 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4322 BaseIt != BaseE; ++BaseIt) {
4323 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4324 if (CanonicalSourceType == BaseType)
4325 break;
4326 }
4327
4328 if (BaseIt == BaseE) {
4329 // Did not find SourceType in the bases.
4330 Diag(UD->getUsingLocation(),
4331 diag::err_using_decl_constructor_not_in_direct_base)
4332 << UD->getNameInfo().getSourceRange()
4333 << QualType(SourceType, 0) << TargetClass;
4334 return true;
4335 }
4336
4337 BaseIt->setInheritConstructors();
4338
4339 return false;
4340}
4341
John McCall84d87672009-12-10 09:41:52 +00004342/// Checks that the given using declaration is not an invalid
4343/// redeclaration. Note that this is checking only for the using decl
4344/// itself, not for any ill-formedness among the UsingShadowDecls.
4345bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4346 bool isTypeName,
4347 const CXXScopeSpec &SS,
4348 SourceLocation NameLoc,
4349 const LookupResult &Prev) {
4350 // C++03 [namespace.udecl]p8:
4351 // C++0x [namespace.udecl]p10:
4352 // A using-declaration is a declaration and can therefore be used
4353 // repeatedly where (and only where) multiple declarations are
4354 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004355 //
John McCall032092f2010-11-29 18:01:58 +00004356 // That's in non-member contexts.
4357 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004358 return false;
4359
4360 NestedNameSpecifier *Qual
4361 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4362
4363 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4364 NamedDecl *D = *I;
4365
4366 bool DTypename;
4367 NestedNameSpecifier *DQual;
4368 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4369 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004370 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004371 } else if (UnresolvedUsingValueDecl *UD
4372 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4373 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004374 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004375 } else if (UnresolvedUsingTypenameDecl *UD
4376 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4377 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004378 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004379 } else continue;
4380
4381 // using decls differ if one says 'typename' and the other doesn't.
4382 // FIXME: non-dependent using decls?
4383 if (isTypeName != DTypename) continue;
4384
4385 // using decls differ if they name different scopes (but note that
4386 // template instantiation can cause this check to trigger when it
4387 // didn't before instantiation).
4388 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4389 Context.getCanonicalNestedNameSpecifier(DQual))
4390 continue;
4391
4392 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004393 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004394 return true;
4395 }
4396
4397 return false;
4398}
4399
John McCall3969e302009-12-08 07:46:18 +00004400
John McCallb96ec562009-12-04 22:46:56 +00004401/// Checks that the given nested-name qualifier used in a using decl
4402/// in the current context is appropriately related to the current
4403/// scope. If an error is found, diagnoses it and returns true.
4404bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4405 const CXXScopeSpec &SS,
4406 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004407 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004408
John McCall3969e302009-12-08 07:46:18 +00004409 if (!CurContext->isRecord()) {
4410 // C++03 [namespace.udecl]p3:
4411 // C++0x [namespace.udecl]p8:
4412 // A using-declaration for a class member shall be a member-declaration.
4413
4414 // If we weren't able to compute a valid scope, it must be a
4415 // dependent class scope.
4416 if (!NamedContext || NamedContext->isRecord()) {
4417 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4418 << SS.getRange();
4419 return true;
4420 }
4421
4422 // Otherwise, everything is known to be fine.
4423 return false;
4424 }
4425
4426 // The current scope is a record.
4427
4428 // If the named context is dependent, we can't decide much.
4429 if (!NamedContext) {
4430 // FIXME: in C++0x, we can diagnose if we can prove that the
4431 // nested-name-specifier does not refer to a base class, which is
4432 // still possible in some cases.
4433
4434 // Otherwise we have to conservatively report that things might be
4435 // okay.
4436 return false;
4437 }
4438
4439 if (!NamedContext->isRecord()) {
4440 // Ideally this would point at the last name in the specifier,
4441 // but we don't have that level of source info.
4442 Diag(SS.getRange().getBegin(),
4443 diag::err_using_decl_nested_name_specifier_is_not_class)
4444 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4445 return true;
4446 }
4447
Douglas Gregor7c842292010-12-21 07:41:49 +00004448 if (!NamedContext->isDependentContext() &&
4449 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4450 return true;
4451
John McCall3969e302009-12-08 07:46:18 +00004452 if (getLangOptions().CPlusPlus0x) {
4453 // C++0x [namespace.udecl]p3:
4454 // In a using-declaration used as a member-declaration, the
4455 // nested-name-specifier shall name a base class of the class
4456 // being defined.
4457
4458 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4459 cast<CXXRecordDecl>(NamedContext))) {
4460 if (CurContext == NamedContext) {
4461 Diag(NameLoc,
4462 diag::err_using_decl_nested_name_specifier_is_current_class)
4463 << SS.getRange();
4464 return true;
4465 }
4466
4467 Diag(SS.getRange().getBegin(),
4468 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4469 << (NestedNameSpecifier*) SS.getScopeRep()
4470 << cast<CXXRecordDecl>(CurContext)
4471 << SS.getRange();
4472 return true;
4473 }
4474
4475 return false;
4476 }
4477
4478 // C++03 [namespace.udecl]p4:
4479 // A using-declaration used as a member-declaration shall refer
4480 // to a member of a base class of the class being defined [etc.].
4481
4482 // Salient point: SS doesn't have to name a base class as long as
4483 // lookup only finds members from base classes. Therefore we can
4484 // diagnose here only if we can prove that that can't happen,
4485 // i.e. if the class hierarchies provably don't intersect.
4486
4487 // TODO: it would be nice if "definitely valid" results were cached
4488 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4489 // need to be repeated.
4490
4491 struct UserData {
4492 llvm::DenseSet<const CXXRecordDecl*> Bases;
4493
4494 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4495 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4496 Data->Bases.insert(Base);
4497 return true;
4498 }
4499
4500 bool hasDependentBases(const CXXRecordDecl *Class) {
4501 return !Class->forallBases(collect, this);
4502 }
4503
4504 /// Returns true if the base is dependent or is one of the
4505 /// accumulated base classes.
4506 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4507 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4508 return !Data->Bases.count(Base);
4509 }
4510
4511 bool mightShareBases(const CXXRecordDecl *Class) {
4512 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4513 }
4514 };
4515
4516 UserData Data;
4517
4518 // Returns false if we find a dependent base.
4519 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4520 return false;
4521
4522 // Returns false if the class has a dependent base or if it or one
4523 // of its bases is present in the base set of the current context.
4524 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4525 return false;
4526
4527 Diag(SS.getRange().getBegin(),
4528 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4529 << (NestedNameSpecifier*) SS.getScopeRep()
4530 << cast<CXXRecordDecl>(CurContext)
4531 << SS.getRange();
4532
4533 return true;
John McCallb96ec562009-12-04 22:46:56 +00004534}
4535
John McCall48871652010-08-21 09:40:31 +00004536Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004537 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004538 SourceLocation AliasLoc,
4539 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004540 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004541 SourceLocation IdentLoc,
4542 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004543
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004544 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004545 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4546 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004547
Anders Carlssondca83c42009-03-28 06:23:46 +00004548 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004549 NamedDecl *PrevDecl
4550 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4551 ForRedeclaration);
4552 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4553 PrevDecl = 0;
4554
4555 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004556 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004557 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004558 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004559 // FIXME: At some point, we'll want to create the (redundant)
4560 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004561 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004562 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004563 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Anders Carlssondca83c42009-03-28 06:23:46 +00004566 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4567 diag::err_redefinition_different_kind;
4568 Diag(AliasLoc, DiagID) << Alias;
4569 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004570 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004571 }
4572
John McCall27b18f82009-11-17 02:14:36 +00004573 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004574 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004575
John McCall9f3059a2009-10-09 21:13:30 +00004576 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004577 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4578 CTC_NoKeywords, 0)) {
4579 if (R.getAsSingle<NamespaceDecl>() ||
4580 R.getAsSingle<NamespaceAliasDecl>()) {
4581 if (DeclContext *DC = computeDeclContext(SS, false))
4582 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4583 << Ident << DC << Corrected << SS.getRange()
4584 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4585 else
4586 Diag(IdentLoc, diag::err_using_directive_suggest)
4587 << Ident << Corrected
4588 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4589
4590 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4591 << Corrected;
4592
4593 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004594 } else {
4595 R.clear();
4596 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004597 }
4598 }
4599
4600 if (R.empty()) {
4601 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004602 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004603 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004604 }
Mike Stump11289f42009-09-09 15:08:12 +00004605
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004606 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004607 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00004608 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00004609 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004610
John McCalld8d0d432010-02-16 06:53:13 +00004611 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004612 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004613}
4614
Douglas Gregora57478e2010-05-01 15:04:51 +00004615namespace {
4616 /// \brief Scoped object used to handle the state changes required in Sema
4617 /// to implicitly define the body of a C++ member function;
4618 class ImplicitlyDefinedFunctionScope {
4619 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00004620 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00004621
4622 public:
4623 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00004624 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00004625 {
Douglas Gregora57478e2010-05-01 15:04:51 +00004626 S.PushFunctionScope();
4627 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4628 }
4629
4630 ~ImplicitlyDefinedFunctionScope() {
4631 S.PopExpressionEvaluationContext();
4632 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00004633 }
4634 };
4635}
4636
Sebastian Redlc15c3262010-09-13 22:02:47 +00004637static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4638 CXXRecordDecl *D) {
4639 ASTContext &Context = Self.Context;
4640 QualType ClassType = Context.getTypeDeclType(D);
4641 DeclarationName ConstructorName
4642 = Context.DeclarationNames.getCXXConstructorName(
4643 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4644
4645 DeclContext::lookup_const_iterator Con, ConEnd;
4646 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4647 Con != ConEnd; ++Con) {
4648 // FIXME: In C++0x, a constructor template can be a default constructor.
4649 if (isa<FunctionTemplateDecl>(*Con))
4650 continue;
4651
4652 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4653 if (Constructor->isDefaultConstructor())
4654 return Constructor;
4655 }
4656 return 0;
4657}
4658
Douglas Gregor0be31a22010-07-02 17:43:08 +00004659CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4660 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004661 // C++ [class.ctor]p5:
4662 // A default constructor for a class X is a constructor of class X
4663 // that can be called without an argument. If there is no
4664 // user-declared constructor for class X, a default constructor is
4665 // implicitly declared. An implicitly-declared default constructor
4666 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004667 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4668 "Should not build implicit default constructor!");
4669
Douglas Gregor6d880b12010-07-01 22:31:05 +00004670 // C++ [except.spec]p14:
4671 // An implicitly declared special member function (Clause 12) shall have an
4672 // exception-specification. [...]
4673 ImplicitExceptionSpecification ExceptSpec(Context);
4674
4675 // Direct base-class destructors.
4676 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4677 BEnd = ClassDecl->bases_end();
4678 B != BEnd; ++B) {
4679 if (B->isVirtual()) // Handled below.
4680 continue;
4681
Douglas Gregor9672f922010-07-03 00:47:00 +00004682 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4683 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4684 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4685 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004686 else if (CXXConstructorDecl *Constructor
4687 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004688 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004689 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004690 }
4691
4692 // Virtual base-class destructors.
4693 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4694 BEnd = ClassDecl->vbases_end();
4695 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004696 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4697 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4698 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4699 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4700 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004701 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004702 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004703 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004704 }
4705
4706 // Field destructors.
4707 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4708 FEnd = ClassDecl->field_end();
4709 F != FEnd; ++F) {
4710 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004711 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4712 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4713 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4714 ExceptSpec.CalledDecl(
4715 DeclareImplicitDefaultConstructor(FieldClassDecl));
4716 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004717 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004718 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004719 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004720 }
John McCalldb40c7f2010-12-14 08:05:40 +00004721
4722 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004723 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
4724 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
4725 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004726 EPI.NumExceptions = ExceptSpec.size();
4727 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004728
Douglas Gregor6d880b12010-07-01 22:31:05 +00004729 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004730 CanQualType ClassType
4731 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00004732 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004733 DeclarationName Name
4734 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004735 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004736 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00004737 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004738 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004739 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004740 /*TInfo=*/0,
4741 /*isExplicit=*/false,
4742 /*isInline=*/true,
4743 /*isImplicitlyDeclared=*/true);
4744 DefaultCon->setAccess(AS_public);
4745 DefaultCon->setImplicit();
4746 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004747
4748 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004749 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4750
Douglas Gregor0be31a22010-07-02 17:43:08 +00004751 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004752 PushOnScopeChains(DefaultCon, S, false);
4753 ClassDecl->addDecl(DefaultCon);
4754
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004755 return DefaultCon;
4756}
4757
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004758void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4759 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004760 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004761 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004762 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004763
Anders Carlsson423f5d82010-04-23 16:04:08 +00004764 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004765 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004766
Douglas Gregora57478e2010-05-01 15:04:51 +00004767 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004768 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004769 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004770 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004771 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004772 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004773 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004774 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004775 }
Douglas Gregor73193272010-09-20 16:48:21 +00004776
4777 SourceLocation Loc = Constructor->getLocation();
4778 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4779
4780 Constructor->setUsed();
4781 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004782}
4783
Sebastian Redl08905022011-02-05 19:23:19 +00004784void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4785 // We start with an initial pass over the base classes to collect those that
4786 // inherit constructors from. If there are none, we can forgo all further
4787 // processing.
4788 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4789 BasesVector BasesToInheritFrom;
4790 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4791 BaseE = ClassDecl->bases_end();
4792 BaseIt != BaseE; ++BaseIt) {
4793 if (BaseIt->getInheritConstructors()) {
4794 QualType Base = BaseIt->getType();
4795 if (Base->isDependentType()) {
4796 // If we inherit constructors from anything that is dependent, just
4797 // abort processing altogether. We'll get another chance for the
4798 // instantiations.
4799 return;
4800 }
4801 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4802 }
4803 }
4804 if (BasesToInheritFrom.empty())
4805 return;
4806
4807 // Now collect the constructors that we already have in the current class.
4808 // Those take precedence over inherited constructors.
4809 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4810 // unless there is a user-declared constructor with the same signature in
4811 // the class where the using-declaration appears.
4812 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4813 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4814 CtorE = ClassDecl->ctor_end();
4815 CtorIt != CtorE; ++CtorIt) {
4816 ExistingConstructors.insert(
4817 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4818 }
4819
4820 Scope *S = getScopeForContext(ClassDecl);
4821 DeclarationName CreatedCtorName =
4822 Context.DeclarationNames.getCXXConstructorName(
4823 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4824
4825 // Now comes the true work.
4826 // First, we keep a map from constructor types to the base that introduced
4827 // them. Needed for finding conflicting constructors. We also keep the
4828 // actually inserted declarations in there, for pretty diagnostics.
4829 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4830 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4831 ConstructorToSourceMap InheritedConstructors;
4832 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4833 BaseE = BasesToInheritFrom.end();
4834 BaseIt != BaseE; ++BaseIt) {
4835 const RecordType *Base = *BaseIt;
4836 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4837 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4838 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4839 CtorE = BaseDecl->ctor_end();
4840 CtorIt != CtorE; ++CtorIt) {
4841 // Find the using declaration for inheriting this base's constructors.
4842 DeclarationName Name =
4843 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4844 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4845 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4846 SourceLocation UsingLoc = UD ? UD->getLocation() :
4847 ClassDecl->getLocation();
4848
4849 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4850 // from the class X named in the using-declaration consists of actual
4851 // constructors and notional constructors that result from the
4852 // transformation of defaulted parameters as follows:
4853 // - all non-template default constructors of X, and
4854 // - for each non-template constructor of X that has at least one
4855 // parameter with a default argument, the set of constructors that
4856 // results from omitting any ellipsis parameter specification and
4857 // successively omitting parameters with a default argument from the
4858 // end of the parameter-type-list.
4859 CXXConstructorDecl *BaseCtor = *CtorIt;
4860 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4861 const FunctionProtoType *BaseCtorType =
4862 BaseCtor->getType()->getAs<FunctionProtoType>();
4863
4864 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4865 maxParams = BaseCtor->getNumParams();
4866 params <= maxParams; ++params) {
4867 // Skip default constructors. They're never inherited.
4868 if (params == 0)
4869 continue;
4870 // Skip copy and move constructors for the same reason.
4871 if (CanBeCopyOrMove && params == 1)
4872 continue;
4873
4874 // Build up a function type for this particular constructor.
4875 // FIXME: The working paper does not consider that the exception spec
4876 // for the inheriting constructor might be larger than that of the
4877 // source. This code doesn't yet, either.
4878 const Type *NewCtorType;
4879 if (params == maxParams)
4880 NewCtorType = BaseCtorType;
4881 else {
4882 llvm::SmallVector<QualType, 16> Args;
4883 for (unsigned i = 0; i < params; ++i) {
4884 Args.push_back(BaseCtorType->getArgType(i));
4885 }
4886 FunctionProtoType::ExtProtoInfo ExtInfo =
4887 BaseCtorType->getExtProtoInfo();
4888 ExtInfo.Variadic = false;
4889 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4890 Args.data(), params, ExtInfo)
4891 .getTypePtr();
4892 }
4893 const Type *CanonicalNewCtorType =
4894 Context.getCanonicalType(NewCtorType);
4895
4896 // Now that we have the type, first check if the class already has a
4897 // constructor with this signature.
4898 if (ExistingConstructors.count(CanonicalNewCtorType))
4899 continue;
4900
4901 // Then we check if we have already declared an inherited constructor
4902 // with this signature.
4903 std::pair<ConstructorToSourceMap::iterator, bool> result =
4904 InheritedConstructors.insert(std::make_pair(
4905 CanonicalNewCtorType,
4906 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
4907 if (!result.second) {
4908 // Already in the map. If it came from a different class, that's an
4909 // error. Not if it's from the same.
4910 CanQualType PreviousBase = result.first->second.first;
4911 if (CanonicalBase != PreviousBase) {
4912 const CXXConstructorDecl *PrevCtor = result.first->second.second;
4913 const CXXConstructorDecl *PrevBaseCtor =
4914 PrevCtor->getInheritedConstructor();
4915 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
4916
4917 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
4918 Diag(BaseCtor->getLocation(),
4919 diag::note_using_decl_constructor_conflict_current_ctor);
4920 Diag(PrevBaseCtor->getLocation(),
4921 diag::note_using_decl_constructor_conflict_previous_ctor);
4922 Diag(PrevCtor->getLocation(),
4923 diag::note_using_decl_constructor_conflict_previous_using);
4924 }
4925 continue;
4926 }
4927
4928 // OK, we're there, now add the constructor.
4929 // C++0x [class.inhctor]p8: [...] that would be performed by a
4930 // user-writtern inline constructor [...]
4931 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
4932 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00004933 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
4934 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redl08905022011-02-05 19:23:19 +00004935 /*ImplicitlyDeclared=*/true);
4936 NewCtor->setAccess(BaseCtor->getAccess());
4937
4938 // Build up the parameter decls and add them.
4939 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
4940 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004941 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
4942 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00004943 /*IdentifierInfo=*/0,
4944 BaseCtorType->getArgType(i),
4945 /*TInfo=*/0, SC_None,
4946 SC_None, /*DefaultArg=*/0));
4947 }
4948 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
4949 NewCtor->setInheritedConstructor(BaseCtor);
4950
4951 PushOnScopeChains(NewCtor, S, false);
4952 ClassDecl->addDecl(NewCtor);
4953 result.first->second.second = NewCtor;
4954 }
4955 }
4956 }
4957}
4958
Douglas Gregor0be31a22010-07-02 17:43:08 +00004959CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004960 // C++ [class.dtor]p2:
4961 // If a class has no user-declared destructor, a destructor is
4962 // declared implicitly. An implicitly-declared destructor is an
4963 // inline public member of its class.
4964
4965 // C++ [except.spec]p14:
4966 // An implicitly declared special member function (Clause 12) shall have
4967 // an exception-specification.
4968 ImplicitExceptionSpecification ExceptSpec(Context);
4969
4970 // Direct base-class destructors.
4971 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4972 BEnd = ClassDecl->bases_end();
4973 B != BEnd; ++B) {
4974 if (B->isVirtual()) // Handled below.
4975 continue;
4976
4977 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4978 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004979 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004980 }
4981
4982 // Virtual base-class destructors.
4983 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4984 BEnd = ClassDecl->vbases_end();
4985 B != BEnd; ++B) {
4986 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4987 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004988 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004989 }
4990
4991 // Field destructors.
4992 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4993 FEnd = ClassDecl->field_end();
4994 F != FEnd; ++F) {
4995 if (const RecordType *RecordTy
4996 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4997 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004998 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004999 }
5000
Douglas Gregor7454c562010-07-02 20:37:36 +00005001 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00005002 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005003 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
5004 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
5005 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005006 EPI.NumExceptions = ExceptSpec.size();
5007 EPI.Exceptions = ExceptSpec.data();
5008 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00005009
5010 CanQualType ClassType
5011 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005012 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00005013 DeclarationName Name
5014 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005015 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00005016 CXXDestructorDecl *Destructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00005017 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00005018 /*isInline=*/true,
5019 /*isImplicitlyDeclared=*/true);
5020 Destructor->setAccess(AS_public);
5021 Destructor->setImplicit();
5022 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00005023
5024 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00005025 ++ASTContext::NumImplicitDestructorsDeclared;
5026
5027 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005028 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00005029 PushOnScopeChains(Destructor, S, false);
5030 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00005031
5032 // This could be uniqued if it ever proves significant.
5033 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5034
5035 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00005036
Douglas Gregorf1203042010-07-01 19:09:28 +00005037 return Destructor;
5038}
5039
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005040void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00005041 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00005042 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005043 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00005044 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005045 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005046
Douglas Gregor54818f02010-05-12 16:39:35 +00005047 if (Destructor->isInvalidDecl())
5048 return;
5049
Douglas Gregora57478e2010-05-01 15:04:51 +00005050 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005051
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005052 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00005053 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5054 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00005055
Douglas Gregor54818f02010-05-12 16:39:35 +00005056 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005057 Diag(CurrentLocation, diag::note_member_synthesized_at)
5058 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5059
5060 Destructor->setInvalidDecl();
5061 return;
5062 }
5063
Douglas Gregor73193272010-09-20 16:48:21 +00005064 SourceLocation Loc = Destructor->getLocation();
5065 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5066
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005067 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005068 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005069}
5070
Douglas Gregorb139cd52010-05-01 20:49:11 +00005071/// \brief Builds a statement that copies the given entity from \p From to
5072/// \c To.
5073///
5074/// This routine is used to copy the members of a class with an
5075/// implicitly-declared copy assignment operator. When the entities being
5076/// copied are arrays, this routine builds for loops to copy them.
5077///
5078/// \param S The Sema object used for type-checking.
5079///
5080/// \param Loc The location where the implicit copy is being generated.
5081///
5082/// \param T The type of the expressions being copied. Both expressions must
5083/// have this type.
5084///
5085/// \param To The expression we are copying to.
5086///
5087/// \param From The expression we are copying from.
5088///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005089/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5090/// Otherwise, it's a non-static member subobject.
5091///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005092/// \param Depth Internal parameter recording the depth of the recursion.
5093///
5094/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005095static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005096BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005097 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005098 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005099 // C++0x [class.copy]p30:
5100 // Each subobject is assigned in the manner appropriate to its type:
5101 //
5102 // - if the subobject is of class type, the copy assignment operator
5103 // for the class is used (as if by explicit qualification; that is,
5104 // ignoring any possible virtual overriding functions in more derived
5105 // classes);
5106 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5107 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5108
5109 // Look for operator=.
5110 DeclarationName Name
5111 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5112 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5113 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5114
5115 // Filter out any result that isn't a copy-assignment operator.
5116 LookupResult::Filter F = OpLookup.makeFilter();
5117 while (F.hasNext()) {
5118 NamedDecl *D = F.next();
5119 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5120 if (Method->isCopyAssignmentOperator())
5121 continue;
5122
5123 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005124 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005125 F.done();
5126
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005127 // Suppress the protected check (C++ [class.protected]) for each of the
5128 // assignment operators we found. This strange dance is required when
5129 // we're assigning via a base classes's copy-assignment operator. To
5130 // ensure that we're getting the right base class subobject (without
5131 // ambiguities), we need to cast "this" to that subobject type; to
5132 // ensure that we don't go through the virtual call mechanism, we need
5133 // to qualify the operator= name with the base class (see below). However,
5134 // this means that if the base class has a protected copy assignment
5135 // operator, the protected member access check will fail. So, we
5136 // rewrite "protected" access to "public" access in this case, since we
5137 // know by construction that we're calling from a derived class.
5138 if (CopyingBaseSubobject) {
5139 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5140 L != LEnd; ++L) {
5141 if (L.getAccess() == AS_protected)
5142 L.setAccess(AS_public);
5143 }
5144 }
5145
Douglas Gregorb139cd52010-05-01 20:49:11 +00005146 // Create the nested-name-specifier that will be used to qualify the
5147 // reference to operator=; this is required to suppress the virtual
5148 // call mechanism.
5149 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005150 SS.MakeTrivial(S.Context,
5151 NestedNameSpecifier::Create(S.Context, 0, false,
5152 T.getTypePtr()),
5153 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005154
5155 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005156 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005157 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005158 /*FirstQualifierInScope=*/0, OpLookup,
5159 /*TemplateArgs=*/0,
5160 /*SuppressQualifierCheck=*/true);
5161 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005162 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005163
5164 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005165
John McCalldadc5752010-08-24 06:29:42 +00005166 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005167 OpEqualRef.takeAs<Expr>(),
5168 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005169 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005170 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005171
5172 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005173 }
John McCallab8c2732010-03-16 06:11:48 +00005174
Douglas Gregorb139cd52010-05-01 20:49:11 +00005175 // - if the subobject is of scalar type, the built-in assignment
5176 // operator is used.
5177 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5178 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005179 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005180 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005181 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005182
5183 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005184 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005185
5186 // - if the subobject is an array, each element is assigned, in the
5187 // manner appropriate to the element type;
5188
5189 // Construct a loop over the array bounds, e.g.,
5190 //
5191 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5192 //
5193 // that will copy each of the array elements.
5194 QualType SizeType = S.Context.getSizeType();
5195
5196 // Create the iteration variable.
5197 IdentifierInfo *IterationVarName = 0;
5198 {
5199 llvm::SmallString<8> Str;
5200 llvm::raw_svector_ostream OS(Str);
5201 OS << "__i" << Depth;
5202 IterationVarName = &S.Context.Idents.get(OS.str());
5203 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00005204 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005205 IterationVarName, SizeType,
5206 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005207 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005208
5209 // Initialize the iteration variable to zero.
5210 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005211 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005212
5213 // Create a reference to the iteration variable; we'll use this several
5214 // times throughout.
5215 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005216 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005217 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5218
5219 // Create the DeclStmt that holds the iteration variable.
5220 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5221
5222 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005223 llvm::APInt Upper
5224 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005225 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005226 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005227 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5228 BO_NE, S.Context.BoolTy,
5229 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005230
5231 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005232 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005233 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5234 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005235
5236 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005237 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5238 IterationVarRef, Loc));
5239 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5240 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005241
5242 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005243 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5244 To, From, CopyingBaseSubobject,
5245 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005246 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005247 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005248
5249 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005250 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005251 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005252 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005253 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005254}
5255
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005256/// \brief Determine whether the given class has a copy assignment operator
5257/// that accepts a const-qualified argument.
5258static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5259 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5260
5261 if (!Class->hasDeclaredCopyAssignment())
5262 S.DeclareImplicitCopyAssignment(Class);
5263
5264 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5265 DeclarationName OpName
5266 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5267
5268 DeclContext::lookup_const_iterator Op, OpEnd;
5269 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5270 // C++ [class.copy]p9:
5271 // A user-declared copy assignment operator is a non-static non-template
5272 // member function of class X with exactly one parameter of type X, X&,
5273 // const X&, volatile X& or const volatile X&.
5274 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5275 if (!Method)
5276 continue;
5277
5278 if (Method->isStatic())
5279 continue;
5280 if (Method->getPrimaryTemplate())
5281 continue;
5282 const FunctionProtoType *FnType =
5283 Method->getType()->getAs<FunctionProtoType>();
5284 assert(FnType && "Overloaded operator has no prototype.");
5285 // Don't assert on this; an invalid decl might have been left in the AST.
5286 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5287 continue;
5288 bool AcceptsConst = true;
5289 QualType ArgType = FnType->getArgType(0);
5290 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5291 ArgType = Ref->getPointeeType();
5292 // Is it a non-const lvalue reference?
5293 if (!ArgType.isConstQualified())
5294 AcceptsConst = false;
5295 }
5296 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5297 continue;
5298
5299 // We have a single argument of type cv X or cv X&, i.e. we've found the
5300 // copy assignment operator. Return whether it accepts const arguments.
5301 return AcceptsConst;
5302 }
5303 assert(Class->isInvalidDecl() &&
5304 "No copy assignment operator declared in valid code.");
5305 return false;
5306}
5307
Douglas Gregor0be31a22010-07-02 17:43:08 +00005308CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005309 // Note: The following rules are largely analoguous to the copy
5310 // constructor rules. Note that virtual bases are not taken into account
5311 // for determining the argument type of the operator. Note also that
5312 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005313
5314
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005315 // C++ [class.copy]p10:
5316 // If the class definition does not explicitly declare a copy
5317 // assignment operator, one is declared implicitly.
5318 // The implicitly-defined copy assignment operator for a class X
5319 // will have the form
5320 //
5321 // X& X::operator=(const X&)
5322 //
5323 // if
5324 bool HasConstCopyAssignment = true;
5325
5326 // -- each direct base class B of X has a copy assignment operator
5327 // whose parameter is of type const B&, const volatile B& or B,
5328 // and
5329 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5330 BaseEnd = ClassDecl->bases_end();
5331 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5332 assert(!Base->getType()->isDependentType() &&
5333 "Cannot generate implicit members for class with dependent bases.");
5334 const CXXRecordDecl *BaseClassDecl
5335 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005336 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005337 }
5338
5339 // -- for all the nonstatic data members of X that are of a class
5340 // type M (or array thereof), each such class type has a copy
5341 // assignment operator whose parameter is of type const M&,
5342 // const volatile M& or M.
5343 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5344 FieldEnd = ClassDecl->field_end();
5345 HasConstCopyAssignment && Field != FieldEnd;
5346 ++Field) {
5347 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5348 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5349 const CXXRecordDecl *FieldClassDecl
5350 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005351 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005352 }
5353 }
5354
5355 // Otherwise, the implicitly declared copy assignment operator will
5356 // have the form
5357 //
5358 // X& X::operator=(X&)
5359 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5360 QualType RetType = Context.getLValueReferenceType(ArgType);
5361 if (HasConstCopyAssignment)
5362 ArgType = ArgType.withConst();
5363 ArgType = Context.getLValueReferenceType(ArgType);
5364
Douglas Gregor68e11362010-07-01 17:48:08 +00005365 // C++ [except.spec]p14:
5366 // An implicitly declared special member function (Clause 12) shall have an
5367 // exception-specification. [...]
5368 ImplicitExceptionSpecification ExceptSpec(Context);
5369 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5370 BaseEnd = ClassDecl->bases_end();
5371 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005372 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005373 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005374
5375 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5376 DeclareImplicitCopyAssignment(BaseClassDecl);
5377
Douglas Gregor68e11362010-07-01 17:48:08 +00005378 if (CXXMethodDecl *CopyAssign
5379 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5380 ExceptSpec.CalledDecl(CopyAssign);
5381 }
5382 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5383 FieldEnd = ClassDecl->field_end();
5384 Field != FieldEnd;
5385 ++Field) {
5386 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5387 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005388 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005389 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005390
5391 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5392 DeclareImplicitCopyAssignment(FieldClassDecl);
5393
Douglas Gregor68e11362010-07-01 17:48:08 +00005394 if (CXXMethodDecl *CopyAssign
5395 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5396 ExceptSpec.CalledDecl(CopyAssign);
5397 }
5398 }
5399
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005400 // An implicitly-declared copy assignment operator is an inline public
5401 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005402 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005403 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
5404 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
5405 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005406 EPI.NumExceptions = ExceptSpec.size();
5407 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005408 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005409 SourceLocation ClassLoc = ClassDecl->getLocation();
5410 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005411 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00005412 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005413 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005414 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005415 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00005416 /*isInline=*/true,
5417 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005418 CopyAssignment->setAccess(AS_public);
5419 CopyAssignment->setImplicit();
5420 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005421
5422 // Add the parameter to the operator.
5423 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005424 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005425 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005426 SC_None,
5427 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005428 CopyAssignment->setParams(&FromParam, 1);
5429
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005430 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005431 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5432
Douglas Gregor0be31a22010-07-02 17:43:08 +00005433 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005434 PushOnScopeChains(CopyAssignment, S, false);
5435 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005436
5437 AddOverriddenMethods(ClassDecl, CopyAssignment);
5438 return CopyAssignment;
5439}
5440
Douglas Gregorb139cd52010-05-01 20:49:11 +00005441void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5442 CXXMethodDecl *CopyAssignOperator) {
5443 assert((CopyAssignOperator->isImplicit() &&
5444 CopyAssignOperator->isOverloadedOperator() &&
5445 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005446 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005447 "DefineImplicitCopyAssignment called for wrong function");
5448
5449 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5450
5451 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5452 CopyAssignOperator->setInvalidDecl();
5453 return;
5454 }
5455
5456 CopyAssignOperator->setUsed();
5457
5458 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005459 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005460
5461 // C++0x [class.copy]p30:
5462 // The implicitly-defined or explicitly-defaulted copy assignment operator
5463 // for a non-union class X performs memberwise copy assignment of its
5464 // subobjects. The direct base classes of X are assigned first, in the
5465 // order of their declaration in the base-specifier-list, and then the
5466 // immediate non-static data members of X are assigned, in the order in
5467 // which they were declared in the class definition.
5468
5469 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005470 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005471
5472 // The parameter for the "other" object, which we are copying from.
5473 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5474 Qualifiers OtherQuals = Other->getType().getQualifiers();
5475 QualType OtherRefType = Other->getType();
5476 if (const LValueReferenceType *OtherRef
5477 = OtherRefType->getAs<LValueReferenceType>()) {
5478 OtherRefType = OtherRef->getPointeeType();
5479 OtherQuals = OtherRefType.getQualifiers();
5480 }
5481
5482 // Our location for everything implicitly-generated.
5483 SourceLocation Loc = CopyAssignOperator->getLocation();
5484
5485 // Construct a reference to the "other" object. We'll be using this
5486 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005487 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005488 assert(OtherRef && "Reference to parameter cannot fail!");
5489
5490 // Construct the "this" pointer. We'll be using this throughout the generated
5491 // ASTs.
5492 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5493 assert(This && "Reference to this cannot fail!");
5494
5495 // Assign base classes.
5496 bool Invalid = false;
5497 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5498 E = ClassDecl->bases_end(); Base != E; ++Base) {
5499 // Form the assignment:
5500 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5501 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005502 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005503 Invalid = true;
5504 continue;
5505 }
5506
John McCallcf142162010-08-07 06:22:56 +00005507 CXXCastPath BasePath;
5508 BasePath.push_back(Base);
5509
Douglas Gregorb139cd52010-05-01 20:49:11 +00005510 // Construct the "from" expression, which is an implicit cast to the
5511 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005512 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005513 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005514 CK_UncheckedDerivedToBase,
5515 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005516
5517 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005518 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005519
5520 // Implicitly cast "this" to the appropriately-qualified base type.
5521 Expr *ToE = To.takeAs<Expr>();
5522 ImpCastExprToType(ToE,
5523 Context.getCVRQualifiedType(BaseType,
5524 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005525 CK_UncheckedDerivedToBase,
5526 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005527 To = Owned(ToE);
5528
5529 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005530 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005531 To.get(), From,
5532 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005533 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005534 Diag(CurrentLocation, diag::note_member_synthesized_at)
5535 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5536 CopyAssignOperator->setInvalidDecl();
5537 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005538 }
5539
5540 // Success! Record the copy.
5541 Statements.push_back(Copy.takeAs<Expr>());
5542 }
5543
5544 // \brief Reference to the __builtin_memcpy function.
5545 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005546 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005547 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005548
5549 // Assign non-static members.
5550 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5551 FieldEnd = ClassDecl->field_end();
5552 Field != FieldEnd; ++Field) {
5553 // Check for members of reference type; we can't copy those.
5554 if (Field->getType()->isReferenceType()) {
5555 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5556 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5557 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005558 Diag(CurrentLocation, diag::note_member_synthesized_at)
5559 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005560 Invalid = true;
5561 continue;
5562 }
5563
5564 // Check for members of const-qualified, non-class type.
5565 QualType BaseType = Context.getBaseElementType(Field->getType());
5566 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5567 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5568 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5569 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005570 Diag(CurrentLocation, diag::note_member_synthesized_at)
5571 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005572 Invalid = true;
5573 continue;
5574 }
5575
5576 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005577 if (FieldType->isIncompleteArrayType()) {
5578 assert(ClassDecl->hasFlexibleArrayMember() &&
5579 "Incomplete array type is not valid");
5580 continue;
5581 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005582
5583 // Build references to the field in the object we're copying from and to.
5584 CXXScopeSpec SS; // Intentionally empty
5585 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5586 LookupMemberName);
5587 MemberLookup.addDecl(*Field);
5588 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005589 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005590 Loc, /*IsArrow=*/false,
5591 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005592 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005593 Loc, /*IsArrow=*/true,
5594 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005595 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5596 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5597
5598 // If the field should be copied with __builtin_memcpy rather than via
5599 // explicit assignments, do so. This optimization only applies for arrays
5600 // of scalars and arrays of class type with trivial copy-assignment
5601 // operators.
5602 if (FieldType->isArrayType() &&
5603 (!BaseType->isRecordType() ||
5604 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5605 ->hasTrivialCopyAssignment())) {
5606 // Compute the size of the memory buffer to be copied.
5607 QualType SizeType = Context.getSizeType();
5608 llvm::APInt Size(Context.getTypeSize(SizeType),
5609 Context.getTypeSizeInChars(BaseType).getQuantity());
5610 for (const ConstantArrayType *Array
5611 = Context.getAsConstantArrayType(FieldType);
5612 Array;
5613 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005614 llvm::APInt ArraySize
5615 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005616 Size *= ArraySize;
5617 }
5618
5619 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005620 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5621 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005622
5623 bool NeedsCollectableMemCpy =
5624 (BaseType->isRecordType() &&
5625 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5626
5627 if (NeedsCollectableMemCpy) {
5628 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005629 // Create a reference to the __builtin_objc_memmove_collectable function.
5630 LookupResult R(*this,
5631 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005632 Loc, LookupOrdinaryName);
5633 LookupName(R, TUScope, true);
5634
5635 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5636 if (!CollectableMemCpy) {
5637 // Something went horribly wrong earlier, and we will have
5638 // complained about it.
5639 Invalid = true;
5640 continue;
5641 }
5642
5643 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5644 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005645 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005646 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5647 }
5648 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005649 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005650 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005651 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5652 LookupOrdinaryName);
5653 LookupName(R, TUScope, true);
5654
5655 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5656 if (!BuiltinMemCpy) {
5657 // Something went horribly wrong earlier, and we will have complained
5658 // about it.
5659 Invalid = true;
5660 continue;
5661 }
5662
5663 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5664 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005665 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005666 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5667 }
5668
John McCall37ad5512010-08-23 06:44:23 +00005669 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005670 CallArgs.push_back(To.takeAs<Expr>());
5671 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005672 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005673 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005674 if (NeedsCollectableMemCpy)
5675 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005676 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005677 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005678 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005679 else
5680 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005681 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005682 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005683 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005684
Douglas Gregorb139cd52010-05-01 20:49:11 +00005685 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5686 Statements.push_back(Call.takeAs<Expr>());
5687 continue;
5688 }
5689
5690 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005691 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005692 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005693 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005694 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005695 Diag(CurrentLocation, diag::note_member_synthesized_at)
5696 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5697 CopyAssignOperator->setInvalidDecl();
5698 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005699 }
5700
5701 // Success! Record the copy.
5702 Statements.push_back(Copy.takeAs<Stmt>());
5703 }
5704
5705 if (!Invalid) {
5706 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005707 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005708
John McCalldadc5752010-08-24 06:29:42 +00005709 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005710 if (Return.isInvalid())
5711 Invalid = true;
5712 else {
5713 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005714
5715 if (Trap.hasErrorOccurred()) {
5716 Diag(CurrentLocation, diag::note_member_synthesized_at)
5717 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5718 Invalid = true;
5719 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005720 }
5721 }
5722
5723 if (Invalid) {
5724 CopyAssignOperator->setInvalidDecl();
5725 return;
5726 }
5727
John McCalldadc5752010-08-24 06:29:42 +00005728 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005729 /*isStmtExpr=*/false);
5730 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5731 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005732}
5733
Douglas Gregor0be31a22010-07-02 17:43:08 +00005734CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5735 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005736 // C++ [class.copy]p4:
5737 // If the class definition does not explicitly declare a copy
5738 // constructor, one is declared implicitly.
5739
Douglas Gregor54be3392010-07-01 17:57:27 +00005740 // C++ [class.copy]p5:
5741 // The implicitly-declared copy constructor for a class X will
5742 // have the form
5743 //
5744 // X::X(const X&)
5745 //
5746 // if
5747 bool HasConstCopyConstructor = true;
5748
5749 // -- each direct or virtual base class B of X has a copy
5750 // constructor whose first parameter is of type const B& or
5751 // const volatile B&, and
5752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5753 BaseEnd = ClassDecl->bases_end();
5754 HasConstCopyConstructor && Base != BaseEnd;
5755 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005756 // Virtual bases are handled below.
5757 if (Base->isVirtual())
5758 continue;
5759
Douglas Gregora6d69502010-07-02 23:41:54 +00005760 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005762 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5763 DeclareImplicitCopyConstructor(BaseClassDecl);
5764
Douglas Gregorcfe68222010-07-01 18:27:03 +00005765 HasConstCopyConstructor
5766 = BaseClassDecl->hasConstCopyConstructor(Context);
5767 }
5768
5769 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5770 BaseEnd = ClassDecl->vbases_end();
5771 HasConstCopyConstructor && Base != BaseEnd;
5772 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005773 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005774 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005775 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5776 DeclareImplicitCopyConstructor(BaseClassDecl);
5777
Douglas Gregor54be3392010-07-01 17:57:27 +00005778 HasConstCopyConstructor
5779 = BaseClassDecl->hasConstCopyConstructor(Context);
5780 }
5781
5782 // -- for all the nonstatic data members of X that are of a
5783 // class type M (or array thereof), each such class type
5784 // has a copy constructor whose first parameter is of type
5785 // const M& or const volatile M&.
5786 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5787 FieldEnd = ClassDecl->field_end();
5788 HasConstCopyConstructor && Field != FieldEnd;
5789 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005790 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005791 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005792 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005793 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005794 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5795 DeclareImplicitCopyConstructor(FieldClassDecl);
5796
Douglas Gregor54be3392010-07-01 17:57:27 +00005797 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005798 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005799 }
5800 }
5801
5802 // Otherwise, the implicitly declared copy constructor will have
5803 // the form
5804 //
5805 // X::X(X&)
5806 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5807 QualType ArgType = ClassType;
5808 if (HasConstCopyConstructor)
5809 ArgType = ArgType.withConst();
5810 ArgType = Context.getLValueReferenceType(ArgType);
5811
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005812 // C++ [except.spec]p14:
5813 // An implicitly declared special member function (Clause 12) shall have an
5814 // exception-specification. [...]
5815 ImplicitExceptionSpecification ExceptSpec(Context);
5816 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5817 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5818 BaseEnd = ClassDecl->bases_end();
5819 Base != BaseEnd;
5820 ++Base) {
5821 // Virtual bases are handled below.
5822 if (Base->isVirtual())
5823 continue;
5824
Douglas Gregora6d69502010-07-02 23:41:54 +00005825 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005826 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005827 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5828 DeclareImplicitCopyConstructor(BaseClassDecl);
5829
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005830 if (CXXConstructorDecl *CopyConstructor
5831 = BaseClassDecl->getCopyConstructor(Context, Quals))
5832 ExceptSpec.CalledDecl(CopyConstructor);
5833 }
5834 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5835 BaseEnd = ClassDecl->vbases_end();
5836 Base != BaseEnd;
5837 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005838 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005839 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005840 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5841 DeclareImplicitCopyConstructor(BaseClassDecl);
5842
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005843 if (CXXConstructorDecl *CopyConstructor
5844 = BaseClassDecl->getCopyConstructor(Context, Quals))
5845 ExceptSpec.CalledDecl(CopyConstructor);
5846 }
5847 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5848 FieldEnd = ClassDecl->field_end();
5849 Field != FieldEnd;
5850 ++Field) {
5851 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5852 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005853 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005854 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005855 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5856 DeclareImplicitCopyConstructor(FieldClassDecl);
5857
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005858 if (CXXConstructorDecl *CopyConstructor
5859 = FieldClassDecl->getCopyConstructor(Context, Quals))
5860 ExceptSpec.CalledDecl(CopyConstructor);
5861 }
5862 }
5863
Douglas Gregor54be3392010-07-01 17:57:27 +00005864 // An implicitly-declared copy constructor is an inline public
5865 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005866 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005867 EPI.ExceptionSpecType = ExceptSpec.hasExceptionSpecification() ?
5868 (ExceptSpec.hasAnyExceptionSpecification() ? EST_DynamicAny : EST_Dynamic) :
5869 EST_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005870 EPI.NumExceptions = ExceptSpec.size();
5871 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005872 DeclarationName Name
5873 = Context.DeclarationNames.getCXXConstructorName(
5874 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005875 SourceLocation ClassLoc = ClassDecl->getLocation();
5876 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor54be3392010-07-01 17:57:27 +00005877 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00005878 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005879 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005880 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005881 /*TInfo=*/0,
5882 /*isExplicit=*/false,
5883 /*isInline=*/true,
5884 /*isImplicitlyDeclared=*/true);
5885 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00005886 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5887
Douglas Gregora6d69502010-07-02 23:41:54 +00005888 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005889 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5890
Douglas Gregor54be3392010-07-01 17:57:27 +00005891 // Add the parameter to the constructor.
5892 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005893 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00005894 /*IdentifierInfo=*/0,
5895 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005896 SC_None,
5897 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005898 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005899 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005900 PushOnScopeChains(CopyConstructor, S, false);
5901 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005902
5903 return CopyConstructor;
5904}
5905
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005906void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5907 CXXConstructorDecl *CopyConstructor,
5908 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005909 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005910 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005911 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005912 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005913
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005914 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005915 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005916
Douglas Gregora57478e2010-05-01 15:04:51 +00005917 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005918 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005919
Alexis Hunt1d792652011-01-08 20:30:50 +00005920 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005921 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005922 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005923 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005924 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005925 } else {
5926 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5927 CopyConstructor->getLocation(),
5928 MultiStmtArg(*this, 0, 0),
5929 /*isStmtExpr=*/false)
5930 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005931 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005932
5933 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005934}
5935
John McCalldadc5752010-08-24 06:29:42 +00005936ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005937Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005938 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005939 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005940 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005941 unsigned ConstructKind,
5942 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005943 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005944
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005945 // C++0x [class.copy]p34:
5946 // When certain criteria are met, an implementation is allowed to
5947 // omit the copy/move construction of a class object, even if the
5948 // copy/move constructor and/or destructor for the object have
5949 // side effects. [...]
5950 // - when a temporary class object that has not been bound to a
5951 // reference (12.2) would be copied/moved to a class object
5952 // with the same cv-unqualified type, the copy/move operation
5953 // can be omitted by constructing the temporary object
5954 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005955 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00005956 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005957 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005958 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005959 }
Mike Stump11289f42009-09-09 15:08:12 +00005960
5961 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005962 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005963 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005964}
5965
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005966/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5967/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005968ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005969Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5970 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005971 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005972 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005973 unsigned ConstructKind,
5974 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005975 unsigned NumExprs = ExprArgs.size();
5976 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005977
Douglas Gregor27381f32009-11-23 12:27:39 +00005978 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005979 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005980 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005981 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005982 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5983 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005984}
5985
Mike Stump11289f42009-09-09 15:08:12 +00005986bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005987 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005988 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005989 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005990 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005991 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005992 move(Exprs), false, CXXConstructExpr::CK_Complete,
5993 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005994 if (TempResult.isInvalid())
5995 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005996
Anders Carlsson6eb55572009-08-25 05:12:04 +00005997 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005998 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005999 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00006000 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00006001 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00006002
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006003 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00006004}
6005
John McCall03c48482010-02-02 09:10:11 +00006006void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
6007 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00006008 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00006009 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00006010 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00006011 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00006012 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00006013 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00006014 << VD->getDeclName()
6015 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00006016
John McCall386dfc72010-09-18 05:25:11 +00006017 // TODO: this should be re-enabled for static locals by !CXAAtExit
6018 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00006019 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00006020 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006021}
6022
Mike Stump11289f42009-09-09 15:08:12 +00006023/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006024/// ActOnDeclarator, when a C++ direct initializer is present.
6025/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00006026void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00006027 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006028 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00006029 SourceLocation RParenLoc,
6030 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00006031 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006032
6033 // If there is no declaration, there was an error parsing it. Just ignore
6034 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00006035 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006036 return;
Mike Stump11289f42009-09-09 15:08:12 +00006037
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006038 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6039 if (!VDecl) {
6040 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6041 RealDecl->setInvalidDecl();
6042 return;
6043 }
6044
Richard Smith30482bc2011-02-20 03:19:35 +00006045 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6046 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00006047 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6048 if (Exprs.size() > 1) {
6049 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6050 diag::err_auto_var_init_multiple_expressions)
6051 << VDecl->getDeclName() << VDecl->getType()
6052 << VDecl->getSourceRange();
6053 RealDecl->setInvalidDecl();
6054 return;
6055 }
6056
6057 Expr *Init = Exprs.get()[0];
6058 QualType DeducedType;
6059 if (!DeduceAutoType(VDecl->getType(), Init, DeducedType)) {
6060 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6061 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6062 << Init->getSourceRange();
6063 RealDecl->setInvalidDecl();
6064 return;
6065 }
6066 VDecl->setType(DeducedType);
6067
6068 // If this is a redeclaration, check that the type we just deduced matches
6069 // the previously declared type.
6070 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6071 MergeVarDeclTypes(VDecl, Old);
6072 }
6073
Douglas Gregor402250f2009-08-26 21:14:46 +00006074 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006075 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006076 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6077 //
6078 // Clients that want to distinguish between the two forms, can check for
6079 // direct initializer using VarDecl::hasCXXDirectInitializer().
6080 // A major benefit is that clients that don't particularly care about which
6081 // exactly form was it (like the CodeGen) can handle both cases without
6082 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006083
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006084 // C++ 8.5p11:
6085 // The form of initialization (using parentheses or '=') is generally
6086 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006087 // class type.
6088
Douglas Gregor50dc2192010-02-11 22:55:30 +00006089 if (!VDecl->getType()->isDependentType() &&
6090 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006091 diag::err_typecheck_decl_incomplete_type)) {
6092 VDecl->setInvalidDecl();
6093 return;
6094 }
6095
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006096 // The variable can not have an abstract class type.
6097 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6098 diag::err_abstract_type_in_decl,
6099 AbstractVariableType))
6100 VDecl->setInvalidDecl();
6101
Sebastian Redl5ca79842010-02-01 20:16:42 +00006102 const VarDecl *Def;
6103 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006104 Diag(VDecl->getLocation(), diag::err_redefinition)
6105 << VDecl->getDeclName();
6106 Diag(Def->getLocation(), diag::note_previous_definition);
6107 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006108 return;
6109 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006110
Douglas Gregorf0f83692010-08-24 05:27:49 +00006111 // C++ [class.static.data]p4
6112 // If a static data member is of const integral or const
6113 // enumeration type, its declaration in the class definition can
6114 // specify a constant-initializer which shall be an integral
6115 // constant expression (5.19). In that case, the member can appear
6116 // in integral constant expressions. The member shall still be
6117 // defined in a namespace scope if it is used in the program and the
6118 // namespace scope definition shall not contain an initializer.
6119 //
6120 // We already performed a redefinition check above, but for static
6121 // data members we also need to check whether there was an in-class
6122 // declaration with an initializer.
6123 const VarDecl* PrevInit = 0;
6124 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6125 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6126 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6127 return;
6128 }
6129
Douglas Gregor71f39c92010-12-16 01:31:22 +00006130 bool IsDependent = false;
6131 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6132 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6133 VDecl->setInvalidDecl();
6134 return;
6135 }
6136
6137 if (Exprs.get()[I]->isTypeDependent())
6138 IsDependent = true;
6139 }
6140
Douglas Gregor50dc2192010-02-11 22:55:30 +00006141 // If either the declaration has a dependent type or if any of the
6142 // expressions is type-dependent, we represent the initialization
6143 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006144 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006145 // Let clients know that initialization was done with a direct initializer.
6146 VDecl->setCXXDirectInitializer(true);
6147
6148 // Store the initialization expressions as a ParenListExpr.
6149 unsigned NumExprs = Exprs.size();
6150 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6151 (Expr **)Exprs.release(),
6152 NumExprs, RParenLoc));
6153 return;
6154 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006155
6156 // Capture the variable that is being initialized and the style of
6157 // initialization.
6158 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6159
6160 // FIXME: Poor source location information.
6161 InitializationKind Kind
6162 = InitializationKind::CreateDirect(VDecl->getLocation(),
6163 LParenLoc, RParenLoc);
6164
6165 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006166 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006167 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006168 if (Result.isInvalid()) {
6169 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006170 return;
6171 }
John McCallacf0ee52010-10-08 02:01:28 +00006172
6173 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006174
Douglas Gregora40433a2010-12-07 00:41:46 +00006175 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006176 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006177 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006178
John McCall8b7fd8f12011-01-19 11:48:09 +00006179 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006180}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006181
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006182/// \brief Given a constructor and the set of arguments provided for the
6183/// constructor, convert the arguments and add any required default arguments
6184/// to form a proper call to this constructor.
6185///
6186/// \returns true if an error occurred, false otherwise.
6187bool
6188Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6189 MultiExprArg ArgsPtr,
6190 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006191 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006192 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6193 unsigned NumArgs = ArgsPtr.size();
6194 Expr **Args = (Expr **)ArgsPtr.get();
6195
6196 const FunctionProtoType *Proto
6197 = Constructor->getType()->getAs<FunctionProtoType>();
6198 assert(Proto && "Constructor without a prototype?");
6199 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006200
6201 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006202 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006203 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006204 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006205 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006206
6207 VariadicCallType CallType =
6208 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6209 llvm::SmallVector<Expr *, 8> AllArgs;
6210 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6211 Proto, 0, Args, NumArgs, AllArgs,
6212 CallType);
6213 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6214 ConvertedArgs.push_back(AllArgs[i]);
6215 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006216}
6217
Anders Carlssone363c8e2009-12-12 00:32:00 +00006218static inline bool
6219CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6220 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006221 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006222 if (isa<NamespaceDecl>(DC)) {
6223 return SemaRef.Diag(FnDecl->getLocation(),
6224 diag::err_operator_new_delete_declared_in_namespace)
6225 << FnDecl->getDeclName();
6226 }
6227
6228 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006229 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006230 return SemaRef.Diag(FnDecl->getLocation(),
6231 diag::err_operator_new_delete_declared_static)
6232 << FnDecl->getDeclName();
6233 }
6234
Anders Carlsson60659a82009-12-12 02:43:16 +00006235 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006236}
6237
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006238static inline bool
6239CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6240 CanQualType ExpectedResultType,
6241 CanQualType ExpectedFirstParamType,
6242 unsigned DependentParamTypeDiag,
6243 unsigned InvalidParamTypeDiag) {
6244 QualType ResultType =
6245 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6246
6247 // Check that the result type is not dependent.
6248 if (ResultType->isDependentType())
6249 return SemaRef.Diag(FnDecl->getLocation(),
6250 diag::err_operator_new_delete_dependent_result_type)
6251 << FnDecl->getDeclName() << ExpectedResultType;
6252
6253 // Check that the result type is what we expect.
6254 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6255 return SemaRef.Diag(FnDecl->getLocation(),
6256 diag::err_operator_new_delete_invalid_result_type)
6257 << FnDecl->getDeclName() << ExpectedResultType;
6258
6259 // A function template must have at least 2 parameters.
6260 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6261 return SemaRef.Diag(FnDecl->getLocation(),
6262 diag::err_operator_new_delete_template_too_few_parameters)
6263 << FnDecl->getDeclName();
6264
6265 // The function decl must have at least 1 parameter.
6266 if (FnDecl->getNumParams() == 0)
6267 return SemaRef.Diag(FnDecl->getLocation(),
6268 diag::err_operator_new_delete_too_few_parameters)
6269 << FnDecl->getDeclName();
6270
6271 // Check the the first parameter type is not dependent.
6272 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6273 if (FirstParamType->isDependentType())
6274 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6275 << FnDecl->getDeclName() << ExpectedFirstParamType;
6276
6277 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006278 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006279 ExpectedFirstParamType)
6280 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6281 << FnDecl->getDeclName() << ExpectedFirstParamType;
6282
6283 return false;
6284}
6285
Anders Carlsson12308f42009-12-11 23:23:22 +00006286static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006287CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006288 // C++ [basic.stc.dynamic.allocation]p1:
6289 // A program is ill-formed if an allocation function is declared in a
6290 // namespace scope other than global scope or declared static in global
6291 // scope.
6292 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6293 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006294
6295 CanQualType SizeTy =
6296 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6297
6298 // C++ [basic.stc.dynamic.allocation]p1:
6299 // The return type shall be void*. The first parameter shall have type
6300 // std::size_t.
6301 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6302 SizeTy,
6303 diag::err_operator_new_dependent_param_type,
6304 diag::err_operator_new_param_type))
6305 return true;
6306
6307 // C++ [basic.stc.dynamic.allocation]p1:
6308 // The first parameter shall not have an associated default argument.
6309 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006310 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006311 diag::err_operator_new_default_arg)
6312 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6313
6314 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006315}
6316
6317static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006318CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6319 // C++ [basic.stc.dynamic.deallocation]p1:
6320 // A program is ill-formed if deallocation functions are declared in a
6321 // namespace scope other than global scope or declared static in global
6322 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006323 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6324 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006325
6326 // C++ [basic.stc.dynamic.deallocation]p2:
6327 // Each deallocation function shall return void and its first parameter
6328 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006329 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6330 SemaRef.Context.VoidPtrTy,
6331 diag::err_operator_delete_dependent_param_type,
6332 diag::err_operator_delete_param_type))
6333 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006334
Anders Carlsson12308f42009-12-11 23:23:22 +00006335 return false;
6336}
6337
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006338/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6339/// of this overloaded operator is well-formed. If so, returns false;
6340/// otherwise, emits appropriate diagnostics and returns true.
6341bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006342 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006343 "Expected an overloaded operator declaration");
6344
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006345 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6346
Mike Stump11289f42009-09-09 15:08:12 +00006347 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006348 // The allocation and deallocation functions, operator new,
6349 // operator new[], operator delete and operator delete[], are
6350 // described completely in 3.7.3. The attributes and restrictions
6351 // found in the rest of this subclause do not apply to them unless
6352 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006353 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006354 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006355
Anders Carlsson22f443f2009-12-12 00:26:23 +00006356 if (Op == OO_New || Op == OO_Array_New)
6357 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006358
6359 // C++ [over.oper]p6:
6360 // An operator function shall either be a non-static member
6361 // function or be a non-member function and have at least one
6362 // parameter whose type is a class, a reference to a class, an
6363 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006364 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6365 if (MethodDecl->isStatic())
6366 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006367 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006368 } else {
6369 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006370 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6371 ParamEnd = FnDecl->param_end();
6372 Param != ParamEnd; ++Param) {
6373 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006374 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6375 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006376 ClassOrEnumParam = true;
6377 break;
6378 }
6379 }
6380
Douglas Gregord69246b2008-11-17 16:14:12 +00006381 if (!ClassOrEnumParam)
6382 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006383 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006384 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006385 }
6386
6387 // C++ [over.oper]p8:
6388 // An operator function cannot have default arguments (8.3.6),
6389 // except where explicitly stated below.
6390 //
Mike Stump11289f42009-09-09 15:08:12 +00006391 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006392 // (C++ [over.call]p1).
6393 if (Op != OO_Call) {
6394 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6395 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006396 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006397 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006398 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006399 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006400 }
6401 }
6402
Douglas Gregor6cf08062008-11-10 13:38:07 +00006403 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6404 { false, false, false }
6405#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6406 , { Unary, Binary, MemberOnly }
6407#include "clang/Basic/OperatorKinds.def"
6408 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006409
Douglas Gregor6cf08062008-11-10 13:38:07 +00006410 bool CanBeUnaryOperator = OperatorUses[Op][0];
6411 bool CanBeBinaryOperator = OperatorUses[Op][1];
6412 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006413
6414 // C++ [over.oper]p8:
6415 // [...] Operator functions cannot have more or fewer parameters
6416 // than the number required for the corresponding operator, as
6417 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006418 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006419 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006420 if (Op != OO_Call &&
6421 ((NumParams == 1 && !CanBeUnaryOperator) ||
6422 (NumParams == 2 && !CanBeBinaryOperator) ||
6423 (NumParams < 1) || (NumParams > 2))) {
6424 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006425 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006426 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006427 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006428 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006429 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006430 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006431 assert(CanBeBinaryOperator &&
6432 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006433 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006434 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006435
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006436 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006437 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006438 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006439
Douglas Gregord69246b2008-11-17 16:14:12 +00006440 // Overloaded operators other than operator() cannot be variadic.
6441 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006442 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006443 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006444 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006445 }
6446
6447 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006448 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6449 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006450 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006451 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006452 }
6453
6454 // C++ [over.inc]p1:
6455 // The user-defined function called operator++ implements the
6456 // prefix and postfix ++ operator. If this function is a member
6457 // function with no parameters, or a non-member function with one
6458 // parameter of class or enumeration type, it defines the prefix
6459 // increment operator ++ for objects of that type. If the function
6460 // is a member function with one parameter (which shall be of type
6461 // int) or a non-member function with two parameters (the second
6462 // of which shall be of type int), it defines the postfix
6463 // increment operator ++ for objects of that type.
6464 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6465 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6466 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006467 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006468 ParamIsInt = BT->getKind() == BuiltinType::Int;
6469
Chris Lattner2b786902008-11-21 07:50:02 +00006470 if (!ParamIsInt)
6471 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006472 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006473 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006474 }
6475
Douglas Gregord69246b2008-11-17 16:14:12 +00006476 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006477}
Chris Lattner3b024a32008-12-17 07:09:26 +00006478
Alexis Huntc88db062010-01-13 09:01:02 +00006479/// CheckLiteralOperatorDeclaration - Check whether the declaration
6480/// of this literal operator function is well-formed. If so, returns
6481/// false; otherwise, emits appropriate diagnostics and returns true.
6482bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6483 DeclContext *DC = FnDecl->getDeclContext();
6484 Decl::Kind Kind = DC->getDeclKind();
6485 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6486 Kind != Decl::LinkageSpec) {
6487 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6488 << FnDecl->getDeclName();
6489 return true;
6490 }
6491
6492 bool Valid = false;
6493
Alexis Hunt7dd26172010-04-07 23:11:06 +00006494 // template <char...> type operator "" name() is the only valid template
6495 // signature, and the only valid signature with no parameters.
6496 if (FnDecl->param_size() == 0) {
6497 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6498 // Must have only one template parameter
6499 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6500 if (Params->size() == 1) {
6501 NonTypeTemplateParmDecl *PmDecl =
6502 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006503
Alexis Hunt7dd26172010-04-07 23:11:06 +00006504 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006505 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6506 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6507 Valid = true;
6508 }
6509 }
6510 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006511 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006512 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6513
Alexis Huntc88db062010-01-13 09:01:02 +00006514 QualType T = (*Param)->getType();
6515
Alexis Hunt079a6f72010-04-07 22:57:35 +00006516 // unsigned long long int, long double, and any character type are allowed
6517 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006518 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6519 Context.hasSameType(T, Context.LongDoubleTy) ||
6520 Context.hasSameType(T, Context.CharTy) ||
6521 Context.hasSameType(T, Context.WCharTy) ||
6522 Context.hasSameType(T, Context.Char16Ty) ||
6523 Context.hasSameType(T, Context.Char32Ty)) {
6524 if (++Param == FnDecl->param_end())
6525 Valid = true;
6526 goto FinishedParams;
6527 }
6528
Alexis Hunt079a6f72010-04-07 22:57:35 +00006529 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006530 const PointerType *PT = T->getAs<PointerType>();
6531 if (!PT)
6532 goto FinishedParams;
6533 T = PT->getPointeeType();
6534 if (!T.isConstQualified())
6535 goto FinishedParams;
6536 T = T.getUnqualifiedType();
6537
6538 // Move on to the second parameter;
6539 ++Param;
6540
6541 // If there is no second parameter, the first must be a const char *
6542 if (Param == FnDecl->param_end()) {
6543 if (Context.hasSameType(T, Context.CharTy))
6544 Valid = true;
6545 goto FinishedParams;
6546 }
6547
6548 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6549 // are allowed as the first parameter to a two-parameter function
6550 if (!(Context.hasSameType(T, Context.CharTy) ||
6551 Context.hasSameType(T, Context.WCharTy) ||
6552 Context.hasSameType(T, Context.Char16Ty) ||
6553 Context.hasSameType(T, Context.Char32Ty)))
6554 goto FinishedParams;
6555
6556 // The second and final parameter must be an std::size_t
6557 T = (*Param)->getType().getUnqualifiedType();
6558 if (Context.hasSameType(T, Context.getSizeType()) &&
6559 ++Param == FnDecl->param_end())
6560 Valid = true;
6561 }
6562
6563 // FIXME: This diagnostic is absolutely terrible.
6564FinishedParams:
6565 if (!Valid) {
6566 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6567 << FnDecl->getDeclName();
6568 return true;
6569 }
6570
6571 return false;
6572}
6573
Douglas Gregor07665a62009-01-05 19:45:36 +00006574/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6575/// linkage specification, including the language and (if present)
6576/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6577/// the location of the language string literal, which is provided
6578/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6579/// the '{' brace. Otherwise, this linkage specification does not
6580/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006581Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6582 SourceLocation LangLoc,
6583 llvm::StringRef Lang,
6584 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006585 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006586 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006587 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006588 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006589 Language = LinkageSpecDecl::lang_cxx;
6590 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006591 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006592 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006593 }
Mike Stump11289f42009-09-09 15:08:12 +00006594
Chris Lattner438e5012008-12-17 07:13:27 +00006595 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006596
Douglas Gregor07665a62009-01-05 19:45:36 +00006597 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006598 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006599 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006600 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006601 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006602}
6603
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006604/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006605/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6606/// valid, it's the position of the closing '}' brace in a linkage
6607/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006608Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006609 Decl *LinkageSpec,
6610 SourceLocation RBraceLoc) {
6611 if (LinkageSpec) {
6612 if (RBraceLoc.isValid()) {
6613 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6614 LSDecl->setRBraceLoc(RBraceLoc);
6615 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006616 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006617 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006618 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006619}
6620
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006621/// \brief Perform semantic analysis for the variable declaration that
6622/// occurs within a C++ catch clause, returning the newly-created
6623/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00006624VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006625 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006626 SourceLocation StartLoc,
6627 SourceLocation Loc,
6628 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006629 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006630 QualType ExDeclType = TInfo->getType();
6631
Sebastian Redl54c04d42008-12-22 19:15:10 +00006632 // Arrays and functions decay.
6633 if (ExDeclType->isArrayType())
6634 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6635 else if (ExDeclType->isFunctionType())
6636 ExDeclType = Context.getPointerType(ExDeclType);
6637
6638 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6639 // The exception-declaration shall not denote a pointer or reference to an
6640 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006641 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006642 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006643 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006644 Invalid = true;
6645 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006646
Douglas Gregor104ee002010-03-08 01:47:36 +00006647 // GCC allows catching pointers and references to incomplete types
6648 // as an extension; so do we, but we warn by default.
6649
Sebastian Redl54c04d42008-12-22 19:15:10 +00006650 QualType BaseType = ExDeclType;
6651 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006652 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006653 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006654 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006655 BaseType = Ptr->getPointeeType();
6656 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006657 DK = diag::ext_catch_incomplete_ptr;
6658 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006659 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006660 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006661 BaseType = Ref->getPointeeType();
6662 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006663 DK = diag::ext_catch_incomplete_ref;
6664 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006665 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006666 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006667 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6668 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006669 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006670
Mike Stump11289f42009-09-09 15:08:12 +00006671 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006672 RequireNonAbstractType(Loc, ExDeclType,
6673 diag::err_abstract_type_in_decl,
6674 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006675 Invalid = true;
6676
John McCall2ca705e2010-07-24 00:37:23 +00006677 // Only the non-fragile NeXT runtime currently supports C++ catches
6678 // of ObjC types, and no runtime supports catching ObjC types by value.
6679 if (!Invalid && getLangOptions().ObjC1) {
6680 QualType T = ExDeclType;
6681 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6682 T = RT->getPointeeType();
6683
6684 if (T->isObjCObjectType()) {
6685 Diag(Loc, diag::err_objc_object_catch);
6686 Invalid = true;
6687 } else if (T->isObjCObjectPointerType()) {
6688 if (!getLangOptions().NeXTRuntime) {
6689 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6690 Invalid = true;
6691 } else if (!getLangOptions().ObjCNonFragileABI) {
6692 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6693 Invalid = true;
6694 }
6695 }
6696 }
6697
Abramo Bagnaradff19302011-03-08 08:55:46 +00006698 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6699 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006700 ExDecl->setExceptionVariable(true);
6701
Douglas Gregor6de584c2010-03-05 23:38:39 +00006702 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00006703 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00006704 // C++ [except.handle]p16:
6705 // The object declared in an exception-declaration or, if the
6706 // exception-declaration does not specify a name, a temporary (12.2) is
6707 // copy-initialized (8.5) from the exception object. [...]
6708 // The object is destroyed when the handler exits, after the destruction
6709 // of any automatic objects initialized within the handler.
6710 //
6711 // We just pretend to initialize the object with itself, then make sure
6712 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00006713 QualType initType = ExDeclType;
6714
6715 InitializedEntity entity =
6716 InitializedEntity::InitializeVariable(ExDecl);
6717 InitializationKind initKind =
6718 InitializationKind::CreateCopy(Loc, SourceLocation());
6719
6720 Expr *opaqueValue =
6721 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6722 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6723 ExprResult result = sequence.Perform(*this, entity, initKind,
6724 MultiExprArg(&opaqueValue, 1));
6725 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00006726 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00006727 else {
6728 // If the constructor used was non-trivial, set this as the
6729 // "initializer".
6730 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6731 if (!construct->getConstructor()->isTrivial()) {
6732 Expr *init = MaybeCreateExprWithCleanups(construct);
6733 ExDecl->setInit(init);
6734 }
6735
6736 // And make sure it's destructable.
6737 FinalizeVarWithDestructor(ExDecl, recordType);
6738 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00006739 }
6740 }
6741
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006742 if (Invalid)
6743 ExDecl->setInvalidDecl();
6744
6745 return ExDecl;
6746}
6747
6748/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6749/// handler.
John McCall48871652010-08-21 09:40:31 +00006750Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006751 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006752 bool Invalid = D.isInvalidType();
6753
6754 // Check for unexpanded parameter packs.
6755 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6756 UPPC_ExceptionType)) {
6757 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6758 D.getIdentifierLoc());
6759 Invalid = true;
6760 }
6761
Sebastian Redl54c04d42008-12-22 19:15:10 +00006762 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006763 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006764 LookupOrdinaryName,
6765 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006766 // The scope should be freshly made just for us. There is just no way
6767 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006768 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006769 if (PrevDecl->isTemplateParameter()) {
6770 // Maybe we will complain about the shadowed template parameter.
6771 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006772 }
6773 }
6774
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006775 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006776 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6777 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006778 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006779 }
6780
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006781 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006782 D.getSourceRange().getBegin(),
6783 D.getIdentifierLoc(),
6784 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006785 if (Invalid)
6786 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006787
Sebastian Redl54c04d42008-12-22 19:15:10 +00006788 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006789 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006790 PushOnScopeChains(ExDecl, S);
6791 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006792 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006793
Douglas Gregor758a8692009-06-17 21:51:59 +00006794 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006795 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006796}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006797
Abramo Bagnaraea947882011-03-08 16:41:52 +00006798Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006799 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006800 Expr *AssertMessageExpr_,
6801 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00006802 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006803
Anders Carlsson54b26982009-03-14 00:33:21 +00006804 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6805 llvm::APSInt Value(32);
6806 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00006807 Diag(StaticAssertLoc,
6808 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00006809 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006810 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006811 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006812
Anders Carlsson54b26982009-03-14 00:33:21 +00006813 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00006814 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006815 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006816 }
6817 }
Mike Stump11289f42009-09-09 15:08:12 +00006818
Douglas Gregoref68fee2010-12-15 23:55:21 +00006819 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6820 return 0;
6821
Abramo Bagnaraea947882011-03-08 16:41:52 +00006822 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
6823 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006824
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006825 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006826 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006827}
Sebastian Redlf769df52009-03-24 22:27:57 +00006828
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006829/// \brief Perform semantic analysis of the given friend type declaration.
6830///
6831/// \returns A friend declaration that.
6832FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6833 TypeSourceInfo *TSInfo) {
6834 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6835
6836 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006837 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006838
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006839 if (!getLangOptions().CPlusPlus0x) {
6840 // C++03 [class.friend]p2:
6841 // An elaborated-type-specifier shall be used in a friend declaration
6842 // for a class.*
6843 //
6844 // * The class-key of the elaborated-type-specifier is required.
6845 if (!ActiveTemplateInstantiations.empty()) {
6846 // Do not complain about the form of friend template types during
6847 // template instantiation; we will already have complained when the
6848 // template was declared.
6849 } else if (!T->isElaboratedTypeSpecifier()) {
6850 // If we evaluated the type to a record type, suggest putting
6851 // a tag in front.
6852 if (const RecordType *RT = T->getAs<RecordType>()) {
6853 RecordDecl *RD = RT->getDecl();
6854
6855 std::string InsertionText = std::string(" ") + RD->getKindName();
6856
6857 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6858 << (unsigned) RD->getTagKind()
6859 << T
6860 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6861 InsertionText);
6862 } else {
6863 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6864 << T
6865 << SourceRange(FriendLoc, TypeRange.getEnd());
6866 }
6867 } else if (T->getAs<EnumType>()) {
6868 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006869 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006870 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006871 }
6872 }
6873
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006874 // C++0x [class.friend]p3:
6875 // If the type specifier in a friend declaration designates a (possibly
6876 // cv-qualified) class type, that class is declared as a friend; otherwise,
6877 // the friend declaration is ignored.
6878
6879 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6880 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006881
6882 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6883}
6884
John McCallace48cd2010-10-19 01:40:49 +00006885/// Handle a friend tag declaration where the scope specifier was
6886/// templated.
6887Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6888 unsigned TagSpec, SourceLocation TagLoc,
6889 CXXScopeSpec &SS,
6890 IdentifierInfo *Name, SourceLocation NameLoc,
6891 AttributeList *Attr,
6892 MultiTemplateParamsArg TempParamLists) {
6893 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6894
6895 bool isExplicitSpecialization = false;
6896 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6897 bool Invalid = false;
6898
6899 if (TemplateParameterList *TemplateParams
6900 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6901 TempParamLists.get(),
6902 TempParamLists.size(),
6903 /*friend*/ true,
6904 isExplicitSpecialization,
6905 Invalid)) {
6906 --NumMatchedTemplateParamLists;
6907
6908 if (TemplateParams->size() > 0) {
6909 // This is a declaration of a class template.
6910 if (Invalid)
6911 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006912
John McCallace48cd2010-10-19 01:40:49 +00006913 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6914 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006915 TemplateParams, AS_public,
6916 NumMatchedTemplateParamLists,
6917 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00006918 } else {
6919 // The "template<>" header is extraneous.
6920 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6921 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6922 isExplicitSpecialization = true;
6923 }
6924 }
6925
6926 if (Invalid) return 0;
6927
6928 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6929
6930 bool isAllExplicitSpecializations = true;
6931 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6932 if (TempParamLists.get()[I]->size()) {
6933 isAllExplicitSpecializations = false;
6934 break;
6935 }
6936 }
6937
6938 // FIXME: don't ignore attributes.
6939
6940 // If it's explicit specializations all the way down, just forget
6941 // about the template header and build an appropriate non-templated
6942 // friend. TODO: for source fidelity, remember the headers.
6943 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006944 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00006945 ElaboratedTypeKeyword Keyword
6946 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006947 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00006948 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00006949 if (T.isNull())
6950 return 0;
6951
6952 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6953 if (isa<DependentNameType>(T)) {
6954 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6955 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006956 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00006957 TL.setNameLoc(NameLoc);
6958 } else {
6959 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6960 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00006961 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00006962 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6963 }
6964
6965 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6966 TSI, FriendLoc);
6967 Friend->setAccess(AS_public);
6968 CurContext->addDecl(Friend);
6969 return Friend;
6970 }
6971
6972 // Handle the case of a templated-scope friend class. e.g.
6973 // template <class T> class A<T>::B;
6974 // FIXME: we don't support these right now.
6975 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6976 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6977 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6978 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6979 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00006980 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00006981 TL.setNameLoc(NameLoc);
6982
6983 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6984 TSI, FriendLoc);
6985 Friend->setAccess(AS_public);
6986 Friend->setUnsupportedFriend(true);
6987 CurContext->addDecl(Friend);
6988 return Friend;
6989}
6990
6991
John McCall11083da2009-09-16 22:47:08 +00006992/// Handle a friend type declaration. This works in tandem with
6993/// ActOnTag.
6994///
6995/// Notes on friend class templates:
6996///
6997/// We generally treat friend class declarations as if they were
6998/// declaring a class. So, for example, the elaborated type specifier
6999/// in a friend declaration is required to obey the restrictions of a
7000/// class-head (i.e. no typedefs in the scope chain), template
7001/// parameters are required to match up with simple template-ids, &c.
7002/// However, unlike when declaring a template specialization, it's
7003/// okay to refer to a template specialization without an empty
7004/// template parameter declaration, e.g.
7005/// friend class A<T>::B<unsigned>;
7006/// We permit this as a special case; if there are any template
7007/// parameters present at all, require proper matching, i.e.
7008/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00007009Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00007010 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007011 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00007012
7013 assert(DS.isFriendSpecified());
7014 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7015
John McCall11083da2009-09-16 22:47:08 +00007016 // Try to convert the decl specifier to a type. This works for
7017 // friend templates because ActOnTag never produces a ClassTemplateDecl
7018 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00007019 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00007020 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7021 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00007022 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00007023 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007024
Douglas Gregor6c110f32010-12-16 01:14:37 +00007025 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7026 return 0;
7027
John McCall11083da2009-09-16 22:47:08 +00007028 // This is definitely an error in C++98. It's probably meant to
7029 // be forbidden in C++0x, too, but the specification is just
7030 // poorly written.
7031 //
7032 // The problem is with declarations like the following:
7033 // template <T> friend A<T>::foo;
7034 // where deciding whether a class C is a friend or not now hinges
7035 // on whether there exists an instantiation of A that causes
7036 // 'foo' to equal C. There are restrictions on class-heads
7037 // (which we declare (by fiat) elaborated friend declarations to
7038 // be) that makes this tractable.
7039 //
7040 // FIXME: handle "template <> friend class A<T>;", which
7041 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00007042 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00007043 Diag(Loc, diag::err_tagless_friend_type_template)
7044 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007045 return 0;
John McCall11083da2009-09-16 22:47:08 +00007046 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007047
John McCallaa74a0c2009-08-28 07:59:38 +00007048 // C++98 [class.friend]p1: A friend of a class is a function
7049 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00007050 // This is fixed in DR77, which just barely didn't make the C++03
7051 // deadline. It's also a very silly restriction that seriously
7052 // affects inner classes and which nobody else seems to implement;
7053 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00007054 //
7055 // But note that we could warn about it: it's always useless to
7056 // friend one of your own members (it's not, however, worthless to
7057 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00007058
John McCall11083da2009-09-16 22:47:08 +00007059 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007060 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00007061 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007062 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00007063 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00007064 TSI,
John McCall11083da2009-09-16 22:47:08 +00007065 DS.getFriendSpecLoc());
7066 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007067 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7068
7069 if (!D)
John McCall48871652010-08-21 09:40:31 +00007070 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007071
John McCall11083da2009-09-16 22:47:08 +00007072 D->setAccess(AS_public);
7073 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00007074
John McCall48871652010-08-21 09:40:31 +00007075 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00007076}
7077
John McCallde3fd222010-10-12 23:13:28 +00007078Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7079 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007080 const DeclSpec &DS = D.getDeclSpec();
7081
7082 assert(DS.isFriendSpecified());
7083 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7084
7085 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007086 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7087 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007088
7089 // C++ [class.friend]p1
7090 // A friend of a class is a function or class....
7091 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007092 // It *doesn't* see through dependent types, which is correct
7093 // according to [temp.arg.type]p3:
7094 // If a declaration acquires a function type through a
7095 // type dependent on a template-parameter and this causes
7096 // a declaration that does not use the syntactic form of a
7097 // function declarator to have a function type, the program
7098 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007099 if (!T->isFunctionType()) {
7100 Diag(Loc, diag::err_unexpected_friend);
7101
7102 // It might be worthwhile to try to recover by creating an
7103 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007104 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007105 }
7106
7107 // C++ [namespace.memdef]p3
7108 // - If a friend declaration in a non-local class first declares a
7109 // class or function, the friend class or function is a member
7110 // of the innermost enclosing namespace.
7111 // - The name of the friend is not found by simple name lookup
7112 // until a matching declaration is provided in that namespace
7113 // scope (either before or after the class declaration granting
7114 // friendship).
7115 // - If a friend function is called, its name may be found by the
7116 // name lookup that considers functions from namespaces and
7117 // classes associated with the types of the function arguments.
7118 // - When looking for a prior declaration of a class or a function
7119 // declared as a friend, scopes outside the innermost enclosing
7120 // namespace scope are not considered.
7121
John McCallde3fd222010-10-12 23:13:28 +00007122 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007123 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7124 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007125 assert(Name);
7126
Douglas Gregor6c110f32010-12-16 01:14:37 +00007127 // Check for unexpanded parameter packs.
7128 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7129 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7130 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7131 return 0;
7132
John McCall07e91c02009-08-06 02:15:43 +00007133 // The context we found the declaration in, or in which we should
7134 // create the declaration.
7135 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007136 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007137 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007138 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007139
John McCallde3fd222010-10-12 23:13:28 +00007140 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007141
John McCallde3fd222010-10-12 23:13:28 +00007142 // There are four cases here.
7143 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007144 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007145 // there as appropriate.
7146 // Recover from invalid scope qualifiers as if they just weren't there.
7147 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007148 // C++0x [namespace.memdef]p3:
7149 // If the name in a friend declaration is neither qualified nor
7150 // a template-id and the declaration is a function or an
7151 // elaborated-type-specifier, the lookup to determine whether
7152 // the entity has been previously declared shall not consider
7153 // any scopes outside the innermost enclosing namespace.
7154 // C++0x [class.friend]p11:
7155 // If a friend declaration appears in a local class and the name
7156 // specified is an unqualified name, a prior declaration is
7157 // looked up without considering scopes that are outside the
7158 // innermost enclosing non-class scope. For a friend function
7159 // declaration, if there is no prior declaration, the program is
7160 // ill-formed.
7161 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007162 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007163
John McCallf7cfb222010-10-13 05:45:15 +00007164 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007165 DC = CurContext;
7166 while (true) {
7167 // Skip class contexts. If someone can cite chapter and verse
7168 // for this behavior, that would be nice --- it's what GCC and
7169 // EDG do, and it seems like a reasonable intent, but the spec
7170 // really only says that checks for unqualified existing
7171 // declarations should stop at the nearest enclosing namespace,
7172 // not that they should only consider the nearest enclosing
7173 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007174 while (DC->isRecord())
7175 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007176
John McCall1f82f242009-11-18 22:49:29 +00007177 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007178
7179 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007180 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007181 break;
John McCallf7cfb222010-10-13 05:45:15 +00007182
John McCallf4776592010-10-14 22:22:28 +00007183 if (isTemplateId) {
7184 if (isa<TranslationUnitDecl>(DC)) break;
7185 } else {
7186 if (DC->isFileContext()) break;
7187 }
John McCall07e91c02009-08-06 02:15:43 +00007188 DC = DC->getParent();
7189 }
7190
7191 // C++ [class.friend]p1: A friend of a class is a function or
7192 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007193 // C++0x changes this for both friend types and functions.
7194 // Most C++ 98 compilers do seem to give an error here, so
7195 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007196 if (!Previous.empty() && DC->Equals(CurContext)
7197 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007198 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007199
John McCallccbc0322010-10-13 06:22:15 +00007200 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007201
John McCallde3fd222010-10-12 23:13:28 +00007202 // - There's a non-dependent scope specifier, in which case we
7203 // compute it and do a previous lookup there for a function
7204 // or function template.
7205 } else if (!SS.getScopeRep()->isDependent()) {
7206 DC = computeDeclContext(SS);
7207 if (!DC) return 0;
7208
7209 if (RequireCompleteDeclContext(SS, DC)) return 0;
7210
7211 LookupQualifiedName(Previous, DC);
7212
7213 // Ignore things found implicitly in the wrong scope.
7214 // TODO: better diagnostics for this case. Suggesting the right
7215 // qualified scope would be nice...
7216 LookupResult::Filter F = Previous.makeFilter();
7217 while (F.hasNext()) {
7218 NamedDecl *D = F.next();
7219 if (!DC->InEnclosingNamespaceSetOf(
7220 D->getDeclContext()->getRedeclContext()))
7221 F.erase();
7222 }
7223 F.done();
7224
7225 if (Previous.empty()) {
7226 D.setInvalidType();
7227 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7228 return 0;
7229 }
7230
7231 // C++ [class.friend]p1: A friend of a class is a function or
7232 // class that is not a member of the class . . .
7233 if (DC->Equals(CurContext))
7234 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7235
7236 // - There's a scope specifier that does not match any template
7237 // parameter lists, in which case we use some arbitrary context,
7238 // create a method or method template, and wait for instantiation.
7239 // - There's a scope specifier that does match some template
7240 // parameter lists, which we don't handle right now.
7241 } else {
7242 DC = CurContext;
7243 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007244 }
7245
John McCallf7cfb222010-10-13 05:45:15 +00007246 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007247 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007248 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7249 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7250 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007251 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007252 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7253 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007254 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007255 }
John McCall07e91c02009-08-06 02:15:43 +00007256 }
7257
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007258 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007259 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007260 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007261 IsDefinition,
7262 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007263 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007264
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007265 assert(ND->getDeclContext() == DC);
7266 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007267
John McCall759e32b2009-08-31 22:39:49 +00007268 // Add the function declaration to the appropriate lookup tables,
7269 // adjusting the redeclarations list as necessary. We don't
7270 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007271 //
John McCall759e32b2009-08-31 22:39:49 +00007272 // Also update the scope-based lookup if the target context's
7273 // lookup context is in lexical scope.
7274 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007275 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007276 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007277 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007278 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007279 }
John McCallaa74a0c2009-08-28 07:59:38 +00007280
7281 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007282 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007283 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007284 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007285 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007286
John McCallde3fd222010-10-12 23:13:28 +00007287 if (ND->isInvalidDecl())
7288 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007289 else {
7290 FunctionDecl *FD;
7291 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7292 FD = FTD->getTemplatedDecl();
7293 else
7294 FD = cast<FunctionDecl>(ND);
7295
7296 // Mark templated-scope function declarations as unsupported.
7297 if (FD->getNumTemplateParameterLists())
7298 FrD->setUnsupportedFriend(true);
7299 }
John McCallde3fd222010-10-12 23:13:28 +00007300
John McCall48871652010-08-21 09:40:31 +00007301 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007302}
7303
John McCall48871652010-08-21 09:40:31 +00007304void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7305 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007306
Sebastian Redlf769df52009-03-24 22:27:57 +00007307 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7308 if (!Fn) {
7309 Diag(DelLoc, diag::err_deleted_non_function);
7310 return;
7311 }
7312 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7313 Diag(DelLoc, diag::err_deleted_decl_not_first);
7314 Diag(Prev->getLocation(), diag::note_previous_declaration);
7315 // If the declaration wasn't the first, we delete the function anyway for
7316 // recovery.
7317 }
7318 Fn->setDeleted();
7319}
Sebastian Redl4c018662009-04-27 21:33:24 +00007320
7321static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007322 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007323 Stmt *SubStmt = *CI;
7324 if (!SubStmt)
7325 continue;
7326 if (isa<ReturnStmt>(SubStmt))
7327 Self.Diag(SubStmt->getSourceRange().getBegin(),
7328 diag::err_return_in_constructor_handler);
7329 if (!isa<Expr>(SubStmt))
7330 SearchForReturnInStmt(Self, SubStmt);
7331 }
7332}
7333
7334void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7335 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7336 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7337 SearchForReturnInStmt(*this, Handler);
7338 }
7339}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007340
Mike Stump11289f42009-09-09 15:08:12 +00007341bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007342 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007343 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7344 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007345
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007346 if (Context.hasSameType(NewTy, OldTy) ||
7347 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007348 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007349
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007350 // Check if the return types are covariant
7351 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007352
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007353 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007354 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7355 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007356 NewClassTy = NewPT->getPointeeType();
7357 OldClassTy = OldPT->getPointeeType();
7358 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007359 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7360 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7361 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7362 NewClassTy = NewRT->getPointeeType();
7363 OldClassTy = OldRT->getPointeeType();
7364 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007365 }
7366 }
Mike Stump11289f42009-09-09 15:08:12 +00007367
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007368 // The return types aren't either both pointers or references to a class type.
7369 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007370 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007371 diag::err_different_return_type_for_overriding_virtual_function)
7372 << New->getDeclName() << NewTy << OldTy;
7373 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007374
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007375 return true;
7376 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007377
Anders Carlssone60365b2009-12-31 18:34:24 +00007378 // C++ [class.virtual]p6:
7379 // If the return type of D::f differs from the return type of B::f, the
7380 // class type in the return type of D::f shall be complete at the point of
7381 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007382 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7383 if (!RT->isBeingDefined() &&
7384 RequireCompleteType(New->getLocation(), NewClassTy,
7385 PDiag(diag::err_covariant_return_incomplete)
7386 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007387 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007388 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007389
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007390 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007391 // Check if the new class derives from the old class.
7392 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7393 Diag(New->getLocation(),
7394 diag::err_covariant_return_not_derived)
7395 << New->getDeclName() << NewTy << OldTy;
7396 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7397 return true;
7398 }
Mike Stump11289f42009-09-09 15:08:12 +00007399
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007400 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007401 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007402 diag::err_covariant_return_inaccessible_base,
7403 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7404 // FIXME: Should this point to the return type?
7405 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007406 // FIXME: this note won't trigger for delayed access control
7407 // diagnostics, and it's impossible to get an undelayed error
7408 // here from access control during the original parse because
7409 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007410 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7411 return true;
7412 }
7413 }
Mike Stump11289f42009-09-09 15:08:12 +00007414
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007415 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007416 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007417 Diag(New->getLocation(),
7418 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007419 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007420 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7421 return true;
7422 };
Mike Stump11289f42009-09-09 15:08:12 +00007423
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007424
7425 // The new class type must have the same or less qualifiers as the old type.
7426 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7427 Diag(New->getLocation(),
7428 diag::err_covariant_return_type_class_type_more_qualified)
7429 << New->getDeclName() << NewTy << OldTy;
7430 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7431 return true;
7432 };
Mike Stump11289f42009-09-09 15:08:12 +00007433
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007434 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007435}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007436
Douglas Gregor21920e372009-12-01 17:24:26 +00007437/// \brief Mark the given method pure.
7438///
7439/// \param Method the method to be marked pure.
7440///
7441/// \param InitRange the source range that covers the "0" initializer.
7442bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7443 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7444 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007445 return false;
7446 }
7447
7448 if (!Method->isInvalidDecl())
7449 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7450 << Method->getDeclName() << InitRange;
7451 return true;
7452}
7453
John McCall1f4ee7b2009-12-19 09:28:58 +00007454/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7455/// an initializer for the out-of-line declaration 'Dcl'. The scope
7456/// is a fresh scope pushed for just this purpose.
7457///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007458/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7459/// static data member of class X, names should be looked up in the scope of
7460/// class X.
John McCall48871652010-08-21 09:40:31 +00007461void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007462 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007463 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007464
John McCall1f4ee7b2009-12-19 09:28:58 +00007465 // We should only get called for declarations with scope specifiers, like:
7466 // int foo::bar;
7467 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007468 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007469}
7470
7471/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007472/// initializer for the out-of-line declaration 'D'.
7473void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007474 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007475 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007476
John McCall1f4ee7b2009-12-19 09:28:58 +00007477 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007478 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007479}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007480
7481/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7482/// C++ if/switch/while/for statement.
7483/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007484DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007485 // C++ 6.4p2:
7486 // The declarator shall not specify a function or an array.
7487 // The type-specifier-seq shall not contain typedef and shall not declare a
7488 // new class or enumeration.
7489 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7490 "Parser allowed 'typedef' as storage class of condition decl.");
7491
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007492 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007493 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7494 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007495
7496 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7497 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7498 // would be created and CXXConditionDeclExpr wants a VarDecl.
7499 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7500 << D.getSourceRange();
7501 return DeclResult();
7502 } else if (OwnedTag && OwnedTag->isDefinition()) {
7503 // The type-specifier-seq shall not declare a new class or enumeration.
7504 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7505 }
7506
John McCall48871652010-08-21 09:40:31 +00007507 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007508 if (!Dcl)
7509 return DeclResult();
7510
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007511 return Dcl;
7512}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007513
Douglas Gregor88d292c2010-05-13 16:44:06 +00007514void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7515 bool DefinitionRequired) {
7516 // Ignore any vtable uses in unevaluated operands or for classes that do
7517 // not have a vtable.
7518 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7519 CurContext->isDependentContext() ||
7520 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007521 return;
7522
Douglas Gregor88d292c2010-05-13 16:44:06 +00007523 // Try to insert this class into the map.
7524 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7525 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7526 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7527 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007528 // If we already had an entry, check to see if we are promoting this vtable
7529 // to required a definition. If so, we need to reappend to the VTableUses
7530 // list, since we may have already processed the first entry.
7531 if (DefinitionRequired && !Pos.first->second) {
7532 Pos.first->second = true;
7533 } else {
7534 // Otherwise, we can early exit.
7535 return;
7536 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007537 }
7538
7539 // Local classes need to have their virtual members marked
7540 // immediately. For all other classes, we mark their virtual members
7541 // at the end of the translation unit.
7542 if (Class->isLocalClass())
7543 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007544 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007545 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007546}
7547
Douglas Gregor88d292c2010-05-13 16:44:06 +00007548bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007549 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007550 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007551
Douglas Gregor88d292c2010-05-13 16:44:06 +00007552 // Note: The VTableUses vector could grow as a result of marking
7553 // the members of a class as "used", so we check the size each
7554 // time through the loop and prefer indices (with are stable) to
7555 // iterators (which are not).
7556 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007557 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007558 if (!Class)
7559 continue;
7560
7561 SourceLocation Loc = VTableUses[I].second;
7562
7563 // If this class has a key function, but that key function is
7564 // defined in another translation unit, we don't need to emit the
7565 // vtable even though we're using it.
7566 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007567 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007568 switch (KeyFunction->getTemplateSpecializationKind()) {
7569 case TSK_Undeclared:
7570 case TSK_ExplicitSpecialization:
7571 case TSK_ExplicitInstantiationDeclaration:
7572 // The key function is in another translation unit.
7573 continue;
7574
7575 case TSK_ExplicitInstantiationDefinition:
7576 case TSK_ImplicitInstantiation:
7577 // We will be instantiating the key function.
7578 break;
7579 }
7580 } else if (!KeyFunction) {
7581 // If we have a class with no key function that is the subject
7582 // of an explicit instantiation declaration, suppress the
7583 // vtable; it will live with the explicit instantiation
7584 // definition.
7585 bool IsExplicitInstantiationDeclaration
7586 = Class->getTemplateSpecializationKind()
7587 == TSK_ExplicitInstantiationDeclaration;
7588 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7589 REnd = Class->redecls_end();
7590 R != REnd; ++R) {
7591 TemplateSpecializationKind TSK
7592 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7593 if (TSK == TSK_ExplicitInstantiationDeclaration)
7594 IsExplicitInstantiationDeclaration = true;
7595 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7596 IsExplicitInstantiationDeclaration = false;
7597 break;
7598 }
7599 }
7600
7601 if (IsExplicitInstantiationDeclaration)
7602 continue;
7603 }
7604
7605 // Mark all of the virtual members of this class as referenced, so
7606 // that we can build a vtable. Then, tell the AST consumer that a
7607 // vtable for this class is required.
7608 MarkVirtualMembersReferenced(Loc, Class);
7609 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7610 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7611
7612 // Optionally warn if we're emitting a weak vtable.
7613 if (Class->getLinkage() == ExternalLinkage &&
7614 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007615 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007616 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7617 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007618 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007619 VTableUses.clear();
7620
Anders Carlsson82fccd02009-12-07 08:24:59 +00007621 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007622}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007623
Rafael Espindola5b334082010-03-26 00:36:59 +00007624void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7625 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007626 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7627 e = RD->method_end(); i != e; ++i) {
7628 CXXMethodDecl *MD = *i;
7629
7630 // C++ [basic.def.odr]p2:
7631 // [...] A virtual member function is used if it is not pure. [...]
7632 if (MD->isVirtual() && !MD->isPure())
7633 MarkDeclarationReferenced(Loc, MD);
7634 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007635
7636 // Only classes that have virtual bases need a VTT.
7637 if (RD->getNumVBases() == 0)
7638 return;
7639
7640 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7641 e = RD->bases_end(); i != e; ++i) {
7642 const CXXRecordDecl *Base =
7643 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007644 if (Base->getNumVBases() == 0)
7645 continue;
7646 MarkVirtualMembersReferenced(Loc, Base);
7647 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007648}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007649
7650/// SetIvarInitializers - This routine builds initialization ASTs for the
7651/// Objective-C implementation whose ivars need be initialized.
7652void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7653 if (!getLangOptions().CPlusPlus)
7654 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007655 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007656 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7657 CollectIvarsToConstructOrDestruct(OID, ivars);
7658 if (ivars.empty())
7659 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007660 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007661 for (unsigned i = 0; i < ivars.size(); i++) {
7662 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007663 if (Field->isInvalidDecl())
7664 continue;
7665
Alexis Hunt1d792652011-01-08 20:30:50 +00007666 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007667 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7668 InitializationKind InitKind =
7669 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7670
7671 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007672 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007673 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007674 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007675 // Note, MemberInit could actually come back empty if no initialization
7676 // is required (e.g., because it would call a trivial default constructor)
7677 if (!MemberInit.get() || MemberInit.isInvalid())
7678 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007679
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007680 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007681 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7682 SourceLocation(),
7683 MemberInit.takeAs<Expr>(),
7684 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007685 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007686
7687 // Be sure that the destructor is accessible and is marked as referenced.
7688 if (const RecordType *RecordTy
7689 = Context.getBaseElementType(Field->getType())
7690 ->getAs<RecordType>()) {
7691 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007692 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007693 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7694 CheckDestructorAccess(Field->getLocation(), Destructor,
7695 PDiag(diag::err_access_dtor_ivar)
7696 << Context.getBaseElementType(Field->getType()));
7697 }
7698 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007699 }
7700 ObjCImplementation->setIvarInitializers(Context,
7701 AllToInit.data(), AllToInit.size());
7702 }
7703}