blob: e2067de96452a422942ae5526dc8925180ef9bd2 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregor752a5952011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Alexis Hunt96d5c762009-11-21 08:43:09 +0000524 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
525 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
526 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000531
John McCall3696dcb2010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539}
540
Douglas Gregor556877c2008-04-13 21:30:24 +0000541/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
542/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000546BaseResult
John McCall48871652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregorc40290e2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky19b9f952010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000561
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000573}
Douglas Gregor556877c2008-04-13 21:30:24 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575/// \brief Performs the actual work of attaching the given base class
576/// specifiers to a C++ class.
577bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
578 unsigned NumBases) {
579 if (NumBases == 0)
580 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000581
582 // Used to keep track of which base types we have already seen, so
583 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000595 if (!Class->hasObjectMember()) {
596 if (const RecordType *FDTTy =
597 NewBaseType.getTypePtr()->getAs<RecordType>())
598 if (FDTTy->getDecl()->hasObjectMember())
599 Class->setHasObjectMember(true);
600 }
601
Douglas Gregor29a92472008-10-22 17:49:05 +0000602 if (KnownBaseTypes[NewBaseType]) {
603 // C++ [class.mi]p3:
604 // A class shall not be specified as a direct base class of a
605 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
626 // Delete the remaining (good) base class specifiers, since their
627 // data has been copied into the CXXRecordDecl.
628 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000630
631 return Invalid;
632}
633
634/// ActOnBaseSpecifiers - Attach the given base specifiers to the
635/// class, after checking whether there are any duplicate base
636/// classes.
John McCall48871652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000646
John McCalle78aac42010-03-10 03:28:59 +0000647static CXXRecordDecl *GetClassForType(QualType T) {
648 if (const RecordType *RT = T->getAs<RecordType>())
649 return cast<CXXRecordDecl>(RT->getDecl());
650 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
651 return ICT->getDecl();
652 else
653 return 0;
654}
655
Douglas Gregor36d1b142009-10-06 17:59:45 +0000656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
John McCalle78aac42010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
John McCalle78aac42010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCall67da35c2010-02-04 22:26:26 +0000670 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
671 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672}
673
674/// \brief Determine whether the type \p Derived is a C++ class that is
675/// derived from the type \p Base.
676bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
677 if (!getLangOptions().CPlusPlus)
678 return false;
679
John McCalle78aac42010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlssona70cff62010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000693 assert(BasePathArray.empty() && "Base path array must be empty!");
694 assert(Paths.isRecordingPaths() && "Must record paths!");
695
696 const CXXBasePath &Path = Paths.front();
697
698 // We first go backward and check if we have a virtual base.
699 // FIXME: It would be better if CXXBasePath had the base specifier for
700 // the nearest virtual base.
701 unsigned Start = 0;
702 for (unsigned I = Path.size(); I != 0; --I) {
703 if (Path[I - 1].Base->isVirtual()) {
704 Start = I - 1;
705 break;
706 }
707 }
708
709 // Now add all bases.
710 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000712}
713
Douglas Gregor88d292c2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallcf142162010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregor36d1b142009-10-06 17:59:45 +0000726/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
727/// conversion (where Derived and Base are class types) is
728/// well-formed, meaning that the conversion is unambiguous (and
729/// that all of the base classes are accessible). Returns true
730/// and emits a diagnostic if the code is ill-formed, returns false
731/// otherwise. Loc is the location where this routine should point to
732/// if there is an error, and Range is the source range to highlight
733/// if there is an error.
734bool
735Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 // First, determine whether the path from Derived to Base is
742 // ambiguous. This is slightly more expensive than checking whether
743 // the Derived to Base conversion exists, because here we need to
744 // explore multiple paths to determine if there is an ambiguity.
745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
746 /*DetectVirtual=*/false);
747 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(DerivationOkay &&
749 "Can only be used with a derived-to-base conversion");
750 (void)DerivationOkay;
751
752 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000753 if (InaccessibleBaseID) {
754 // Check that the base class can be accessed.
755 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
756 InaccessibleBaseID)) {
757 case AR_inaccessible:
758 return true;
759 case AR_accessible:
760 case AR_dependent:
761 case AR_delayed:
762 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000763 }
John McCall5b0829a2010-02-10 09:31:12 +0000764 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000770 }
771
772 // We know that the derived-to-base conversion is ambiguous, and
773 // we're going to produce a diagnostic. Perform the derived-to-base
774 // search just one more time to compute all of the possible paths so
775 // that we can print them out. This is more expensive than any of
776 // the previous derived-to-base checks we've done, but at this point
777 // performance isn't as much of an issue.
778 Paths.clear();
779 Paths.setRecordingPaths(true);
780 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(StillOkay && "Can only be used with a derived-to-base conversion");
782 (void)StillOkay;
783
784 // Build up a textual representation of the ambiguous paths, e.g.,
785 // D -> B -> A, that will be used to illustrate the ambiguous
786 // conversions in the diagnostic. We only print one of the paths
787 // to each base class subobject.
788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
789
790 Diag(Loc, AmbigiousBaseConvID)
791 << Derived << Base << PathDisplayStr << Range << Name;
792 return true;
793}
794
795bool
796Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806}
807
808
809/// @brief Builds a string representing ambiguous paths from a
810/// specific derived class to different subobjects of the same base
811/// class.
812///
813/// This function builds a string that can be used in error messages
814/// to show the different paths that one can take through the
815/// inheritance hierarchy to go from the derived class to different
816/// subobjects of a base class. The result looks something like this:
817/// @code
818/// struct D -> struct B -> struct A
819/// struct D -> struct C -> struct A
820/// @endcode
821std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
822 std::string PathDisplayStr;
823 std::set<unsigned> DisplayedPaths;
824 for (CXXBasePaths::paths_iterator Path = Paths.begin();
825 Path != Paths.end(); ++Path) {
826 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
827 // We haven't displayed a path to this particular base
828 // class subobject yet.
829 PathDisplayStr += "\n ";
830 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
831 for (CXXBasePath::const_iterator Element = Path->begin();
832 Element != Path->end(); ++Element)
833 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
834 }
835 }
836
837 return PathDisplayStr;
838}
839
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnarad7340582010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853}
854
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000855/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
856/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
857/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000858/// any.
John McCall48871652010-08-21 09:40:31 +0000859Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000862 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
863 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000864 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000865 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
866 DeclarationName Name = NameInfo.getName();
867 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000868
869 // For anonymous bitfields, the location should point to the type.
870 if (Loc.isInvalid())
871 Loc = D.getSourceRange().getBegin();
872
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000873 Expr *BitWidth = static_cast<Expr*>(BW);
874 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000875
John McCallb1cd7da2010-06-04 08:34:12 +0000876 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000877 assert(!DS.isFriendSpecified());
878
John McCallb1cd7da2010-06-04 08:34:12 +0000879 bool isFunc = false;
880 if (D.isFunctionDeclarator())
881 isFunc = true;
882 else if (D.getNumTypeObjects() == 0 &&
883 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000884 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000885 isFunc = TDType->isFunctionType();
886 }
887
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000888 // C++ 9.2p6: A member shall not be declared to have automatic storage
889 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000890 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
891 // data members and cannot be applied to names declared const or static,
892 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893 switch (DS.getStorageClassSpec()) {
894 case DeclSpec::SCS_unspecified:
895 case DeclSpec::SCS_typedef:
896 case DeclSpec::SCS_static:
897 // FALL THROUGH.
898 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000899 case DeclSpec::SCS_mutable:
900 if (isFunc) {
901 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000902 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000903 else
Chris Lattner3b054132008-11-19 05:08:23 +0000904 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Sebastian Redl8071edb2008-11-17 23:24:37 +0000906 // FIXME: It would be nicer if the keyword was ignored only for this
907 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000908 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000909 }
910 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000911 default:
912 if (DS.getStorageClassSpecLoc().isValid())
913 Diag(DS.getStorageClassSpecLoc(),
914 diag::err_storageclass_invalid_for_member);
915 else
916 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
917 D.getMutableDeclSpec().ClearStorageClassSpecs();
918 }
919
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000920 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
921 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000922 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000923
924 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000925 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000926 CXXScopeSpec &SS = D.getCXXScopeSpec();
927
928
929 if (SS.isSet() && !SS.isInvalid()) {
930 // The user provided a superfluous scope specifier inside a class
931 // definition:
932 //
933 // class X {
934 // int X::member;
935 // };
936 DeclContext *DC = 0;
937 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
938 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
939 << Name << FixItHint::CreateRemoval(SS.getRange());
940 else
941 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
942 << Name << SS.getRange();
943
944 SS.clear();
945 }
946
Douglas Gregor3447e762009-08-20 22:52:58 +0000947 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000948 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000949 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
950 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000951 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000952 } else {
John McCall48871652010-08-21 09:40:31 +0000953 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000954 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000955 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000956 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000957
958 // Non-instance-fields can't have a bitfield.
959 if (BitWidth) {
960 if (Member->isInvalidDecl()) {
961 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000962 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000963 // C++ 9.6p3: A bit-field shall not be a static member.
964 // "static member 'A' cannot be a bit-field"
965 Diag(Loc, diag::err_static_not_bitfield)
966 << Name << BitWidth->getSourceRange();
967 } else if (isa<TypedefDecl>(Member)) {
968 // "typedef member 'x' cannot be a bit-field"
969 Diag(Loc, diag::err_typedef_not_bitfield)
970 << Name << BitWidth->getSourceRange();
971 } else {
972 // A function typedef ("typedef int f(); f a;").
973 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
974 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000975 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000976 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerd26760a2009-03-05 23:01:03 +0000979 BitWidth = 0;
980 Member->setInvalidDecl();
981 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000982
983 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor3447e762009-08-20 22:52:58 +0000985 // If we have declared a member function template, set the access of the
986 // templated declaration as well.
987 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
988 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000989 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000990
Douglas Gregor92751d42008-11-17 22:58:34 +0000991 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000992
Douglas Gregor0c880302009-03-11 23:00:04 +0000993 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000994 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000995 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000996 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000999 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001000 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001001 }
John McCall48871652010-08-21 09:40:31 +00001002 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001003}
1004
Douglas Gregor15e77a22009-12-31 09:10:24 +00001005/// \brief Find the direct and/or virtual base specifiers that
1006/// correspond to the given base type, for use in base initialization
1007/// within a constructor.
1008static bool FindBaseInitializer(Sema &SemaRef,
1009 CXXRecordDecl *ClassDecl,
1010 QualType BaseType,
1011 const CXXBaseSpecifier *&DirectBaseSpec,
1012 const CXXBaseSpecifier *&VirtualBaseSpec) {
1013 // First, check for a direct base class.
1014 DirectBaseSpec = 0;
1015 for (CXXRecordDecl::base_class_const_iterator Base
1016 = ClassDecl->bases_begin();
1017 Base != ClassDecl->bases_end(); ++Base) {
1018 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1019 // We found a direct base of this type. That's what we're
1020 // initializing.
1021 DirectBaseSpec = &*Base;
1022 break;
1023 }
1024 }
1025
1026 // Check for a virtual base class.
1027 // FIXME: We might be able to short-circuit this if we know in advance that
1028 // there are no virtual bases.
1029 VirtualBaseSpec = 0;
1030 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1031 // We haven't found a base yet; search the class hierarchy for a
1032 // virtual base class.
1033 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1034 /*DetectVirtual=*/false);
1035 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1036 BaseType, Paths)) {
1037 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1038 Path != Paths.end(); ++Path) {
1039 if (Path->back().Base->isVirtual()) {
1040 VirtualBaseSpec = Path->back().Base;
1041 break;
1042 }
1043 }
1044 }
1045 }
1046
1047 return DirectBaseSpec || VirtualBaseSpec;
1048}
1049
Douglas Gregore8381c02008-11-05 04:29:56 +00001050/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001051MemInitResult
John McCall48871652010-08-21 09:40:31 +00001052Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001053 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001054 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001055 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001056 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001057 SourceLocation IdLoc,
1058 SourceLocation LParenLoc,
1059 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001060 SourceLocation RParenLoc,
1061 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001062 if (!ConstructorD)
1063 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001065 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001066
1067 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001068 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001069 if (!Constructor) {
1070 // The user wrote a constructor initializer on a function that is
1071 // not a C++ constructor. Ignore the error for now, because we may
1072 // have more member initializers coming; we'll diagnose it just
1073 // once in ActOnMemInitializers.
1074 return true;
1075 }
1076
1077 CXXRecordDecl *ClassDecl = Constructor->getParent();
1078
1079 // C++ [class.base.init]p2:
1080 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001081 // constructor's class and, if not found in that scope, are looked
1082 // up in the scope containing the constructor's definition.
1083 // [Note: if the constructor's class contains a member with the
1084 // same name as a direct or virtual base class of the class, a
1085 // mem-initializer-id naming the member or base class and composed
1086 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001087 // mem-initializer-id for the hidden base class may be specified
1088 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001089 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001090 // Look for a member, first.
1091 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001092 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001093 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001094 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001095 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001096
Douglas Gregor44e7df62011-01-04 00:32:56 +00001097 if (Member) {
1098 if (EllipsisLoc.isValid())
1099 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1100 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1101
Francois Pichetd583da02010-12-04 09:14:42 +00001102 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001103 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001104 }
1105
Francois Pichetd583da02010-12-04 09:14:42 +00001106 // Handle anonymous union case.
1107 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001108 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1109 if (EllipsisLoc.isValid())
1110 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1111 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1112
Francois Pichetd583da02010-12-04 09:14:42 +00001113 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1114 NumArgs, IdLoc,
1115 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001116 }
Francois Pichetd583da02010-12-04 09:14:42 +00001117 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001118 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001119 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001120 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001121 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001122
1123 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001124 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001125 } else {
1126 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1127 LookupParsedName(R, S, &SS);
1128
1129 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1130 if (!TyD) {
1131 if (R.isAmbiguous()) return true;
1132
John McCallda6841b2010-04-09 19:01:14 +00001133 // We don't want access-control diagnostics here.
1134 R.suppressDiagnostics();
1135
Douglas Gregora3b624a2010-01-19 06:46:48 +00001136 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1137 bool NotUnknownSpecialization = false;
1138 DeclContext *DC = computeDeclContext(SS, false);
1139 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1140 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1141
1142 if (!NotUnknownSpecialization) {
1143 // When the scope specifier can refer to a member of an unknown
1144 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001145 BaseType = CheckTypenameType(ETK_None,
1146 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001147 *MemberOrBase, SourceLocation(),
1148 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001149 if (BaseType.isNull())
1150 return true;
1151
Douglas Gregora3b624a2010-01-19 06:46:48 +00001152 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001153 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001154 }
1155 }
1156
Douglas Gregor15e77a22009-12-31 09:10:24 +00001157 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001158 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001159 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1160 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001161 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001162 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001163 // We have found a non-static data member with a similar
1164 // name to what was typed; complain and initialize that
1165 // member.
1166 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1167 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001168 << FixItHint::CreateReplacement(R.getNameLoc(),
1169 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001170 Diag(Member->getLocation(), diag::note_previous_decl)
1171 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001172
1173 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1174 LParenLoc, RParenLoc);
1175 }
1176 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1177 const CXXBaseSpecifier *DirectBaseSpec;
1178 const CXXBaseSpecifier *VirtualBaseSpec;
1179 if (FindBaseInitializer(*this, ClassDecl,
1180 Context.getTypeDeclType(Type),
1181 DirectBaseSpec, VirtualBaseSpec)) {
1182 // We have found a direct or virtual base class with a
1183 // similar name to what was typed; complain and initialize
1184 // that base class.
1185 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1186 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001187 << FixItHint::CreateReplacement(R.getNameLoc(),
1188 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001189
1190 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1191 : VirtualBaseSpec;
1192 Diag(BaseSpec->getSourceRange().getBegin(),
1193 diag::note_base_class_specified_here)
1194 << BaseSpec->getType()
1195 << BaseSpec->getSourceRange();
1196
Douglas Gregor15e77a22009-12-31 09:10:24 +00001197 TyD = Type;
1198 }
1199 }
1200 }
1201
Douglas Gregora3b624a2010-01-19 06:46:48 +00001202 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001203 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1204 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1205 return true;
1206 }
John McCallb5a0d312009-12-21 10:41:20 +00001207 }
1208
Douglas Gregora3b624a2010-01-19 06:46:48 +00001209 if (BaseType.isNull()) {
1210 BaseType = Context.getTypeDeclType(TyD);
1211 if (SS.isSet()) {
1212 NestedNameSpecifier *Qualifier =
1213 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001214
Douglas Gregora3b624a2010-01-19 06:46:48 +00001215 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001216 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001217 }
John McCallb5a0d312009-12-21 10:41:20 +00001218 }
1219 }
Mike Stump11289f42009-09-09 15:08:12 +00001220
John McCallbcd03502009-12-07 02:54:59 +00001221 if (!TInfo)
1222 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001223
John McCallbcd03502009-12-07 02:54:59 +00001224 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001225 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001226}
1227
John McCalle22a04a2009-11-04 23:02:40 +00001228/// Checks an initializer expression for use of uninitialized fields, such as
1229/// containing the field that is being initialized. Returns true if there is an
1230/// uninitialized field was used an updates the SourceLocation parameter; false
1231/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001232static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001233 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001234 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001235 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1236
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001237 if (isa<CallExpr>(S)) {
1238 // Do not descend into function calls or constructors, as the use
1239 // of an uninitialized field may be valid. One would have to inspect
1240 // the contents of the function/ctor to determine if it is safe or not.
1241 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1242 // may be safe, depending on what the function/ctor does.
1243 return false;
1244 }
1245 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1246 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001247
1248 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1249 // The member expression points to a static data member.
1250 assert(VD->isStaticDataMember() &&
1251 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001252 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001253 return false;
1254 }
1255
1256 if (isa<EnumConstantDecl>(RhsField)) {
1257 // The member expression points to an enum.
1258 return false;
1259 }
1260
John McCalle22a04a2009-11-04 23:02:40 +00001261 if (RhsField == LhsField) {
1262 // Initializing a field with itself. Throw a warning.
1263 // But wait; there are exceptions!
1264 // Exception #1: The field may not belong to this record.
1265 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001266 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001267 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1268 // Even though the field matches, it does not belong to this record.
1269 return false;
1270 }
1271 // None of the exceptions triggered; return true to indicate an
1272 // uninitialized field was used.
1273 *L = ME->getMemberLoc();
1274 return true;
1275 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001276 } else if (isa<SizeOfAlignOfExpr>(S)) {
1277 // sizeof/alignof doesn't reference contents, do not warn.
1278 return false;
1279 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1280 // address-of doesn't reference contents (the pointer may be dereferenced
1281 // in the same expression but it would be rare; and weird).
1282 if (UOE->getOpcode() == UO_AddrOf)
1283 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001284 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001285 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1286 it != e; ++it) {
1287 if (!*it) {
1288 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001289 continue;
1290 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001291 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1292 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001293 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001294 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001295}
1296
John McCallfaf5fb42010-08-26 23:41:50 +00001297MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001298Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001299 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001300 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001301 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001302 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1303 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1304 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001305 "Member must be a FieldDecl or IndirectFieldDecl");
1306
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001307 if (Member->isInvalidDecl())
1308 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001309
John McCalle22a04a2009-11-04 23:02:40 +00001310 // Diagnose value-uses of fields to initialize themselves, e.g.
1311 // foo(foo)
1312 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001313 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001314 for (unsigned i = 0; i < NumArgs; ++i) {
1315 SourceLocation L;
1316 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1317 // FIXME: Return true in the case when other fields are used before being
1318 // uninitialized. For example, let this field be the i'th field. When
1319 // initializing the i'th field, throw a warning if any of the >= i'th
1320 // fields are used, as they are not yet initialized.
1321 // Right now we are only handling the case where the i'th field uses
1322 // itself in its initializer.
1323 Diag(L, diag::warn_field_is_uninit);
1324 }
1325 }
1326
Eli Friedman8e1433b2009-07-29 19:44:27 +00001327 bool HasDependentArg = false;
1328 for (unsigned i = 0; i < NumArgs; i++)
1329 HasDependentArg |= Args[i]->isTypeDependent();
1330
Chandler Carruthd44c3102010-12-06 09:23:57 +00001331 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001332 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001333 // Can't check initialization for a member of dependent type or when
1334 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001335 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1336 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001337
1338 // Erase any temporaries within this evaluation context; we're not
1339 // going to track them in the AST, since we'll be rebuilding the
1340 // ASTs during template instantiation.
1341 ExprTemporaries.erase(
1342 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1343 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001344 } else {
1345 // Initialize the member.
1346 InitializedEntity MemberEntity =
1347 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1348 : InitializedEntity::InitializeMember(IndirectMember, 0);
1349 InitializationKind Kind =
1350 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001351
Chandler Carruthd44c3102010-12-06 09:23:57 +00001352 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1353
1354 ExprResult MemberInit =
1355 InitSeq.Perform(*this, MemberEntity, Kind,
1356 MultiExprArg(*this, Args, NumArgs), 0);
1357 if (MemberInit.isInvalid())
1358 return true;
1359
1360 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1361
1362 // C++0x [class.base.init]p7:
1363 // The initialization of each base and member constitutes a
1364 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001365 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001366 if (MemberInit.isInvalid())
1367 return true;
1368
1369 // If we are in a dependent context, template instantiation will
1370 // perform this type-checking again. Just save the arguments that we
1371 // received in a ParenListExpr.
1372 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1373 // of the information that we have about the member
1374 // initializer. However, deconstructing the ASTs is a dicey process,
1375 // and this approach is far more likely to get the corner cases right.
1376 if (CurContext->isDependentContext())
1377 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1378 RParenLoc);
1379 else
1380 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001381 }
1382
Chandler Carruthd44c3102010-12-06 09:23:57 +00001383 if (DirectMember) {
1384 return new (Context) CXXBaseOrMemberInitializer(Context, DirectMember,
1385 IdLoc, LParenLoc, Init,
1386 RParenLoc);
1387 } else {
1388 return new (Context) CXXBaseOrMemberInitializer(Context, IndirectMember,
1389 IdLoc, LParenLoc, Init,
1390 RParenLoc);
1391 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001392}
1393
John McCallfaf5fb42010-08-26 23:41:50 +00001394MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001395Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001396 Expr **Args, unsigned NumArgs,
1397 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001398 CXXRecordDecl *ClassDecl,
1399 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001400 bool HasDependentArg = false;
1401 for (unsigned i = 0; i < NumArgs; i++)
1402 HasDependentArg |= Args[i]->isTypeDependent();
1403
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001404 SourceLocation BaseLoc
1405 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1406
1407 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1408 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1409 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1410
1411 // C++ [class.base.init]p2:
1412 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001413 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001414 // of that class, the mem-initializer is ill-formed. A
1415 // mem-initializer-list can initialize a base class using any
1416 // name that denotes that base class type.
1417 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1418
Douglas Gregor44e7df62011-01-04 00:32:56 +00001419 if (EllipsisLoc.isValid()) {
1420 // This is a pack expansion.
1421 if (!BaseType->containsUnexpandedParameterPack()) {
1422 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1423 << SourceRange(BaseLoc, RParenLoc);
1424
1425 EllipsisLoc = SourceLocation();
1426 }
1427 } else {
1428 // Check for any unexpanded parameter packs.
1429 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1430 return true;
1431
1432 for (unsigned I = 0; I != NumArgs; ++I)
1433 if (DiagnoseUnexpandedParameterPack(Args[I]))
1434 return true;
1435 }
1436
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001437 // Check for direct and virtual base classes.
1438 const CXXBaseSpecifier *DirectBaseSpec = 0;
1439 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1440 if (!Dependent) {
1441 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1442 VirtualBaseSpec);
1443
1444 // C++ [base.class.init]p2:
1445 // Unless the mem-initializer-id names a nonstatic data member of the
1446 // constructor's class or a direct or virtual base of that class, the
1447 // mem-initializer is ill-formed.
1448 if (!DirectBaseSpec && !VirtualBaseSpec) {
1449 // If the class has any dependent bases, then it's possible that
1450 // one of those types will resolve to the same type as
1451 // BaseType. Therefore, just treat this as a dependent base
1452 // class initialization. FIXME: Should we try to check the
1453 // initialization anyway? It seems odd.
1454 if (ClassDecl->hasAnyDependentBases())
1455 Dependent = true;
1456 else
1457 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1458 << BaseType << Context.getTypeDeclType(ClassDecl)
1459 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1460 }
1461 }
1462
1463 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001464 // Can't check initialization for a base of dependent type or when
1465 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001466 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001467 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1468 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001469
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001470 // Erase any temporaries within this evaluation context; we're not
1471 // going to track them in the AST, since we'll be rebuilding the
1472 // ASTs during template instantiation.
1473 ExprTemporaries.erase(
1474 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1475 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001476
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001477 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001478 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001479 LParenLoc,
1480 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001481 RParenLoc,
1482 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001483 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001484
1485 // C++ [base.class.init]p2:
1486 // If a mem-initializer-id is ambiguous because it designates both
1487 // a direct non-virtual base class and an inherited virtual base
1488 // class, the mem-initializer is ill-formed.
1489 if (DirectBaseSpec && VirtualBaseSpec)
1490 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001491 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001492
1493 CXXBaseSpecifier *BaseSpec
1494 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1495 if (!BaseSpec)
1496 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1497
1498 // Initialize the base.
1499 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001500 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001501 InitializationKind Kind =
1502 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1503
1504 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1505
John McCalldadc5752010-08-24 06:29:42 +00001506 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001507 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001508 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001509 if (BaseInit.isInvalid())
1510 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001511
1512 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001513
1514 // C++0x [class.base.init]p7:
1515 // The initialization of each base and member constitutes a
1516 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001517 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001518 if (BaseInit.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()) {
John McCalldadc5752010-08-24 06:29:42 +00001529 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001530 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1531 RParenLoc));
1532 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001533 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001534 LParenLoc,
1535 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001536 RParenLoc,
1537 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001538 }
1539
1540 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001541 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001542 LParenLoc,
1543 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001544 RParenLoc,
1545 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001546}
1547
Anders Carlsson1b00e242010-04-23 03:10:23 +00001548/// ImplicitInitializerKind - How an implicit base or member initializer should
1549/// initialize its base or member.
1550enum ImplicitInitializerKind {
1551 IIK_Default,
1552 IIK_Copy,
1553 IIK_Move
1554};
1555
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001556static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001557BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001558 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001559 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001560 bool IsInheritedVirtualBase,
1561 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001562 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001563 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1564 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001565
John McCalldadc5752010-08-24 06:29:42 +00001566 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001567
1568 switch (ImplicitInitKind) {
1569 case IIK_Default: {
1570 InitializationKind InitKind
1571 = InitializationKind::CreateDefault(Constructor->getLocation());
1572 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1573 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001574 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001575 break;
1576 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001577
Anders Carlsson1b00e242010-04-23 03:10:23 +00001578 case IIK_Copy: {
1579 ParmVarDecl *Param = Constructor->getParamDecl(0);
1580 QualType ParamType = Param->getType().getNonReferenceType();
1581
1582 Expr *CopyCtorArg =
1583 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001584 Constructor->getLocation(), ParamType,
1585 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001586
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001587 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001588 QualType ArgTy =
1589 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1590 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001591
1592 CXXCastPath BasePath;
1593 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001594 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001595 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001596 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001597
Anders Carlsson1b00e242010-04-23 03:10:23 +00001598 InitializationKind InitKind
1599 = InitializationKind::CreateDirect(Constructor->getLocation(),
1600 SourceLocation(), SourceLocation());
1601 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1602 &CopyCtorArg, 1);
1603 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001604 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001605 break;
1606 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001607
Anders Carlsson1b00e242010-04-23 03:10:23 +00001608 case IIK_Move:
1609 assert(false && "Unhandled initializer kind!");
1610 }
John McCallb268a282010-08-23 23:25:46 +00001611
Douglas Gregora40433a2010-12-07 00:41:46 +00001612 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001613 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001614 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001615
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001616 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001617 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1618 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1619 SourceLocation()),
1620 BaseSpec->isVirtual(),
1621 SourceLocation(),
1622 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001623 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001624 SourceLocation());
1625
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001626 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001627}
1628
Anders Carlsson3c1db572010-04-23 02:15:47 +00001629static bool
1630BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001631 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001632 FieldDecl *Field,
1633 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001634 if (Field->isInvalidDecl())
1635 return true;
1636
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001637 SourceLocation Loc = Constructor->getLocation();
1638
Anders Carlsson423f5d82010-04-23 16:04:08 +00001639 if (ImplicitInitKind == IIK_Copy) {
1640 ParmVarDecl *Param = Constructor->getParamDecl(0);
1641 QualType ParamType = Param->getType().getNonReferenceType();
1642
1643 Expr *MemberExprBase =
1644 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001645 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001646
1647 // Build a reference to this field within the parameter.
1648 CXXScopeSpec SS;
1649 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1650 Sema::LookupMemberName);
1651 MemberLookup.addDecl(Field, AS_public);
1652 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001653 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001654 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001655 ParamType, Loc,
1656 /*IsArrow=*/false,
1657 SS,
1658 /*FirstQualifierInScope=*/0,
1659 MemberLookup,
1660 /*TemplateArgs=*/0);
1661 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001662 return true;
1663
Douglas Gregor94f9a482010-05-05 05:51:00 +00001664 // When the field we are copying is an array, create index variables for
1665 // each dimension of the array. We use these index variables to subscript
1666 // the source array, and other clients (e.g., CodeGen) will perform the
1667 // necessary iteration with these index variables.
1668 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1669 QualType BaseType = Field->getType();
1670 QualType SizeType = SemaRef.Context.getSizeType();
1671 while (const ConstantArrayType *Array
1672 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1673 // Create the iteration variable for this array index.
1674 IdentifierInfo *IterationVarName = 0;
1675 {
1676 llvm::SmallString<8> Str;
1677 llvm::raw_svector_ostream OS(Str);
1678 OS << "__i" << IndexVariables.size();
1679 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1680 }
1681 VarDecl *IterationVar
1682 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1683 IterationVarName, SizeType,
1684 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001685 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001686 IndexVariables.push_back(IterationVar);
1687
1688 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001689 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001690 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001691 assert(!IterationVarRef.isInvalid() &&
1692 "Reference to invented variable cannot fail!");
1693
1694 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001695 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001696 Loc,
John McCallb268a282010-08-23 23:25:46 +00001697 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001698 Loc);
1699 if (CopyCtorArg.isInvalid())
1700 return true;
1701
1702 BaseType = Array->getElementType();
1703 }
1704
1705 // Construct the entity that we will be initializing. For an array, this
1706 // will be first element in the array, which may require several levels
1707 // of array-subscript entities.
1708 llvm::SmallVector<InitializedEntity, 4> Entities;
1709 Entities.reserve(1 + IndexVariables.size());
1710 Entities.push_back(InitializedEntity::InitializeMember(Field));
1711 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1712 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1713 0,
1714 Entities.back()));
1715
1716 // Direct-initialize to use the copy constructor.
1717 InitializationKind InitKind =
1718 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1719
1720 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1721 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1722 &CopyCtorArgE, 1);
1723
John McCalldadc5752010-08-24 06:29:42 +00001724 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001725 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001726 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001727 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001728 if (MemberInit.isInvalid())
1729 return true;
1730
1731 CXXMemberInit
1732 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1733 MemberInit.takeAs<Expr>(), Loc,
1734 IndexVariables.data(),
1735 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001736 return false;
1737 }
1738
Anders Carlsson423f5d82010-04-23 16:04:08 +00001739 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1740
Anders Carlsson3c1db572010-04-23 02:15:47 +00001741 QualType FieldBaseElementType =
1742 SemaRef.Context.getBaseElementType(Field->getType());
1743
Anders Carlsson3c1db572010-04-23 02:15:47 +00001744 if (FieldBaseElementType->isRecordType()) {
1745 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001746 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001747 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001748
1749 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001750 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001751 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001752
Douglas Gregora40433a2010-12-07 00:41:46 +00001753 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001754 if (MemberInit.isInvalid())
1755 return true;
1756
1757 CXXMemberInit =
1758 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001759 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001760 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001761 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001762 return false;
1763 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001764
1765 if (FieldBaseElementType->isReferenceType()) {
1766 SemaRef.Diag(Constructor->getLocation(),
1767 diag::err_uninitialized_member_in_ctor)
1768 << (int)Constructor->isImplicit()
1769 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1770 << 0 << Field->getDeclName();
1771 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1772 return true;
1773 }
1774
1775 if (FieldBaseElementType.isConstQualified()) {
1776 SemaRef.Diag(Constructor->getLocation(),
1777 diag::err_uninitialized_member_in_ctor)
1778 << (int)Constructor->isImplicit()
1779 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1780 << 1 << Field->getDeclName();
1781 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1782 return true;
1783 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001784
1785 // Nothing to initialize.
1786 CXXMemberInit = 0;
1787 return false;
1788}
John McCallbc83b3f2010-05-20 23:23:51 +00001789
1790namespace {
1791struct BaseAndFieldInfo {
1792 Sema &S;
1793 CXXConstructorDecl *Ctor;
1794 bool AnyErrorsInInits;
1795 ImplicitInitializerKind IIK;
1796 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1797 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1798
1799 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1800 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1801 // FIXME: Handle implicit move constructors.
1802 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1803 IIK = IIK_Copy;
1804 else
1805 IIK = IIK_Default;
1806 }
1807};
1808}
1809
1810static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1811 FieldDecl *Top, FieldDecl *Field) {
1812
Chandler Carruth139e9622010-06-30 02:59:29 +00001813 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001814 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001815 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001816 return false;
1817 }
1818
1819 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1820 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1821 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001822 CXXRecordDecl *FieldClassDecl
1823 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001824
1825 // Even though union members never have non-trivial default
1826 // constructions in C++03, we still build member initializers for aggregate
1827 // record types which can be union members, and C++0x allows non-trivial
1828 // default constructors for union members, so we ensure that only one
1829 // member is initialized for these.
1830 if (FieldClassDecl->isUnion()) {
1831 // First check for an explicit initializer for one field.
1832 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1833 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1834 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001835 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001836
1837 // Once we've initialized a field of an anonymous union, the union
1838 // field in the class is also initialized, so exit immediately.
1839 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001840 } else if ((*FA)->isAnonymousStructOrUnion()) {
1841 if (CollectFieldInitializer(Info, Top, *FA))
1842 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001843 }
1844 }
1845
1846 // Fallthrough and construct a default initializer for the union as
1847 // a whole, which can call its default constructor if such a thing exists
1848 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1849 // behavior going forward with C++0x, when anonymous unions there are
1850 // finalized, we should revisit this.
1851 } else {
1852 // For structs, we simply descend through to initialize all members where
1853 // necessary.
1854 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1855 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1856 if (CollectFieldInitializer(Info, Top, *FA))
1857 return true;
1858 }
1859 }
John McCallbc83b3f2010-05-20 23:23:51 +00001860 }
1861
1862 // Don't try to build an implicit initializer if there were semantic
1863 // errors in any of the initializers (and therefore we might be
1864 // missing some that the user actually wrote).
1865 if (Info.AnyErrorsInInits)
1866 return false;
1867
1868 CXXBaseOrMemberInitializer *Init = 0;
1869 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1870 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001871
Francois Pichetd583da02010-12-04 09:14:42 +00001872 if (Init)
1873 Info.AllToInit.push_back(Init);
1874
John McCallbc83b3f2010-05-20 23:23:51 +00001875 return false;
1876}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001877
Eli Friedman9cf6b592009-11-09 19:20:36 +00001878bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001879Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001880 CXXBaseOrMemberInitializer **Initializers,
1881 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001882 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001883 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001884 // Just store the initializers as written, they will be checked during
1885 // instantiation.
1886 if (NumInitializers > 0) {
1887 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1888 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1889 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1890 memcpy(baseOrMemberInitializers, Initializers,
1891 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1892 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1893 }
1894
1895 return false;
1896 }
1897
John McCallbc83b3f2010-05-20 23:23:51 +00001898 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001899
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001900 // We need to build the initializer AST according to order of construction
1901 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001902 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001903 if (!ClassDecl)
1904 return true;
1905
Eli Friedman9cf6b592009-11-09 19:20:36 +00001906 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001907
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001908 for (unsigned i = 0; i < NumInitializers; i++) {
1909 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001910
1911 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001912 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001913 else
Francois Pichetd583da02010-12-04 09:14:42 +00001914 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001915 }
1916
Anders Carlsson43c64af2010-04-21 19:52:01 +00001917 // Keep track of the direct virtual bases.
1918 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1919 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1920 E = ClassDecl->bases_end(); I != E; ++I) {
1921 if (I->isVirtual())
1922 DirectVBases.insert(I);
1923 }
1924
Anders Carlssondb0a9652010-04-02 06:26:44 +00001925 // Push virtual bases before others.
1926 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1927 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1928
1929 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001930 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1931 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001932 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001933 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001934 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001935 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001936 VBase, IsInheritedVirtualBase,
1937 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001938 HadError = true;
1939 continue;
1940 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001941
John McCallbc83b3f2010-05-20 23:23:51 +00001942 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001943 }
1944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
John McCallbc83b3f2010-05-20 23:23:51 +00001946 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001947 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1948 E = ClassDecl->bases_end(); Base != E; ++Base) {
1949 // Virtuals are in the virtual base list and already constructed.
1950 if (Base->isVirtual())
1951 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001952
Anders Carlssondb0a9652010-04-02 06:26:44 +00001953 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001954 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1955 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001956 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001957 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001958 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001959 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001960 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001961 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001962 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001963 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001964
John McCallbc83b3f2010-05-20 23:23:51 +00001965 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001966 }
1967 }
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCallbc83b3f2010-05-20 23:23:51 +00001969 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001970 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001971 E = ClassDecl->field_end(); Field != E; ++Field) {
1972 if ((*Field)->getType()->isIncompleteArrayType()) {
1973 assert(ClassDecl->hasFlexibleArrayMember() &&
1974 "Incomplete array type is not valid");
1975 continue;
1976 }
John McCallbc83b3f2010-05-20 23:23:51 +00001977 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001978 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980
John McCallbc83b3f2010-05-20 23:23:51 +00001981 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001982 if (NumInitializers > 0) {
1983 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1984 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1985 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001986 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001987 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001988 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001989
John McCalla6309952010-03-16 21:39:52 +00001990 // Constructors implicitly reference the base and member
1991 // destructors.
1992 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1993 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001994 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001995
1996 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001997}
1998
Eli Friedman952c15d2009-07-21 19:28:10 +00001999static void *GetKeyForTopLevelField(FieldDecl *Field) {
2000 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002001 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002002 if (RT->getDecl()->isAnonymousStructOrUnion())
2003 return static_cast<void *>(RT->getDecl());
2004 }
2005 return static_cast<void *>(Field);
2006}
2007
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002008static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2009 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002010}
2011
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002012static void *GetKeyForMember(ASTContext &Context,
Francois Pichetd583da02010-12-04 09:14:42 +00002013 CXXBaseOrMemberInitializer *Member) {
2014 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002015 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002016
Eli Friedman952c15d2009-07-21 19:28:10 +00002017 // For fields injected into the class via declaration of an anonymous union,
2018 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002019 FieldDecl *Field = Member->getAnyMember();
2020
John McCall23eebd92010-04-10 09:28:51 +00002021 // If the field is a member of an anonymous struct or union, our key
2022 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002023 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002024 if (RD->isAnonymousStructOrUnion()) {
2025 while (true) {
2026 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2027 if (Parent->isAnonymousStructOrUnion())
2028 RD = Parent;
2029 else
2030 break;
2031 }
2032
Anders Carlsson83ac3122010-03-30 16:19:37 +00002033 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Anders Carlssona942dcd2010-03-30 15:39:27 +00002036 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002037}
2038
Anders Carlssone857b292010-04-02 03:37:03 +00002039static void
2040DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002041 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00002042 CXXBaseOrMemberInitializer **Inits,
2043 unsigned NumInits) {
2044 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002045 return;
Mike Stump11289f42009-09-09 15:08:12 +00002046
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002047 // Don't check initializers order unless the warning is enabled at the
2048 // location of at least one initializer.
2049 bool ShouldCheckOrder = false;
2050 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2051 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2052 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2053 Init->getSourceLocation())
2054 != Diagnostic::Ignored) {
2055 ShouldCheckOrder = true;
2056 break;
2057 }
2058 }
2059 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002060 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002061
John McCallbb7b6582010-04-10 07:37:23 +00002062 // Build the list of bases and members in the order that they'll
2063 // actually be initialized. The explicit initializers should be in
2064 // this same order but may be missing things.
2065 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002066
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002067 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2068
John McCallbb7b6582010-04-10 07:37:23 +00002069 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002070 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002071 ClassDecl->vbases_begin(),
2072 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002073 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002074
John McCallbb7b6582010-04-10 07:37:23 +00002075 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002076 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002077 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002078 if (Base->isVirtual())
2079 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002080 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002081 }
Mike Stump11289f42009-09-09 15:08:12 +00002082
John McCallbb7b6582010-04-10 07:37:23 +00002083 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002084 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2085 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002086 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002087
John McCallbb7b6582010-04-10 07:37:23 +00002088 unsigned NumIdealInits = IdealInitKeys.size();
2089 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002090
John McCallbb7b6582010-04-10 07:37:23 +00002091 CXXBaseOrMemberInitializer *PrevInit = 0;
2092 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2093 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002094 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002095
2096 // Scan forward to try to find this initializer in the idealized
2097 // initializers list.
2098 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2099 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002100 break;
John McCallbb7b6582010-04-10 07:37:23 +00002101
2102 // If we didn't find this initializer, it must be because we
2103 // scanned past it on a previous iteration. That can only
2104 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002105 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002106 Sema::SemaDiagnosticBuilder D =
2107 SemaRef.Diag(PrevInit->getSourceLocation(),
2108 diag::warn_initializer_out_of_order);
2109
Francois Pichetd583da02010-12-04 09:14:42 +00002110 if (PrevInit->isAnyMemberInitializer())
2111 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002112 else
2113 D << 1 << PrevInit->getBaseClassInfo()->getType();
2114
Francois Pichetd583da02010-12-04 09:14:42 +00002115 if (Init->isAnyMemberInitializer())
2116 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002117 else
2118 D << 1 << Init->getBaseClassInfo()->getType();
2119
2120 // Move back to the initializer's location in the ideal list.
2121 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2122 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002123 break;
John McCallbb7b6582010-04-10 07:37:23 +00002124
2125 assert(IdealIndex != NumIdealInits &&
2126 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002127 }
John McCallbb7b6582010-04-10 07:37:23 +00002128
2129 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002130 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002131}
2132
John McCall23eebd92010-04-10 09:28:51 +00002133namespace {
2134bool CheckRedundantInit(Sema &S,
2135 CXXBaseOrMemberInitializer *Init,
2136 CXXBaseOrMemberInitializer *&PrevInit) {
2137 if (!PrevInit) {
2138 PrevInit = Init;
2139 return false;
2140 }
2141
2142 if (FieldDecl *Field = Init->getMember())
2143 S.Diag(Init->getSourceLocation(),
2144 diag::err_multiple_mem_initialization)
2145 << Field->getDeclName()
2146 << Init->getSourceRange();
2147 else {
2148 Type *BaseClass = Init->getBaseClass();
2149 assert(BaseClass && "neither field nor base");
2150 S.Diag(Init->getSourceLocation(),
2151 diag::err_multiple_base_initialization)
2152 << QualType(BaseClass, 0)
2153 << Init->getSourceRange();
2154 }
2155 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2156 << 0 << PrevInit->getSourceRange();
2157
2158 return true;
2159}
2160
2161typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2162typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2163
2164bool CheckRedundantUnionInit(Sema &S,
2165 CXXBaseOrMemberInitializer *Init,
2166 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002167 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002168 RecordDecl *Parent = Field->getParent();
2169 if (!Parent->isAnonymousStructOrUnion())
2170 return false;
2171
2172 NamedDecl *Child = Field;
2173 do {
2174 if (Parent->isUnion()) {
2175 UnionEntry &En = Unions[Parent];
2176 if (En.first && En.first != Child) {
2177 S.Diag(Init->getSourceLocation(),
2178 diag::err_multiple_mem_union_initialization)
2179 << Field->getDeclName()
2180 << Init->getSourceRange();
2181 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2182 << 0 << En.second->getSourceRange();
2183 return true;
2184 } else if (!En.first) {
2185 En.first = Child;
2186 En.second = Init;
2187 }
2188 }
2189
2190 Child = Parent;
2191 Parent = cast<RecordDecl>(Parent->getDeclContext());
2192 } while (Parent->isAnonymousStructOrUnion());
2193
2194 return false;
2195}
2196}
2197
Anders Carlssone857b292010-04-02 03:37:03 +00002198/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002199void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002200 SourceLocation ColonLoc,
2201 MemInitTy **meminits, unsigned NumMemInits,
2202 bool AnyErrors) {
2203 if (!ConstructorDecl)
2204 return;
2205
2206 AdjustDeclIfTemplate(ConstructorDecl);
2207
2208 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002209 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002210
2211 if (!Constructor) {
2212 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2213 return;
2214 }
2215
2216 CXXBaseOrMemberInitializer **MemInits =
2217 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002218
2219 // Mapping for the duplicate initializers check.
2220 // For member initializers, this is keyed with a FieldDecl*.
2221 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002222 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002223
2224 // Mapping for the inconsistent anonymous-union initializers check.
2225 RedundantUnionMap MemberUnions;
2226
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002227 bool HadError = false;
2228 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002229 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002230
Abramo Bagnara341d7832010-05-26 18:09:23 +00002231 // Set the source order index.
2232 Init->setSourceOrder(i);
2233
Francois Pichetd583da02010-12-04 09:14:42 +00002234 if (Init->isAnyMemberInitializer()) {
2235 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002236 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2237 CheckRedundantUnionInit(*this, Init, MemberUnions))
2238 HadError = true;
2239 } else {
2240 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2241 if (CheckRedundantInit(*this, Init, Members[Key]))
2242 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002243 }
Anders Carlssone857b292010-04-02 03:37:03 +00002244 }
2245
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002246 if (HadError)
2247 return;
2248
Anders Carlssone857b292010-04-02 03:37:03 +00002249 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002250
2251 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002252}
2253
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002254void
John McCalla6309952010-03-16 21:39:52 +00002255Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2256 CXXRecordDecl *ClassDecl) {
2257 // Ignore dependent contexts.
2258 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002259 return;
John McCall1064d7e2010-03-16 05:22:47 +00002260
2261 // FIXME: all the access-control diagnostics are positioned on the
2262 // field/base declaration. That's probably good; that said, the
2263 // user might reasonably want to know why the destructor is being
2264 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002265
Anders Carlssondee9a302009-11-17 04:44:12 +00002266 // Non-static data members.
2267 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2268 E = ClassDecl->field_end(); I != E; ++I) {
2269 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002270 if (Field->isInvalidDecl())
2271 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002272 QualType FieldType = Context.getBaseElementType(Field->getType());
2273
2274 const RecordType* RT = FieldType->getAs<RecordType>();
2275 if (!RT)
2276 continue;
2277
2278 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2279 if (FieldClassDecl->hasTrivialDestructor())
2280 continue;
2281
Douglas Gregore71edda2010-07-01 22:47:18 +00002282 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002283 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002284 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002285 << Field->getDeclName()
2286 << FieldType);
2287
John McCalla6309952010-03-16 21:39:52 +00002288 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002289 }
2290
John McCall1064d7e2010-03-16 05:22:47 +00002291 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2292
Anders Carlssondee9a302009-11-17 04:44:12 +00002293 // Bases.
2294 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2295 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002296 // Bases are always records in a well-formed non-dependent class.
2297 const RecordType *RT = Base->getType()->getAs<RecordType>();
2298
2299 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002300 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002301 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002302
2303 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002304 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002305 if (BaseClassDecl->hasTrivialDestructor())
2306 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002307
Douglas Gregore71edda2010-07-01 22:47:18 +00002308 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002309
2310 // FIXME: caret should be on the start of the class name
2311 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002312 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002313 << Base->getType()
2314 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002315
John McCalla6309952010-03-16 21:39:52 +00002316 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002317 }
2318
2319 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002320 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2321 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002322
2323 // Bases are always records in a well-formed non-dependent class.
2324 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2325
2326 // Ignore direct virtual bases.
2327 if (DirectVirtualBases.count(RT))
2328 continue;
2329
Anders Carlssondee9a302009-11-17 04:44:12 +00002330 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002331 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002332 if (BaseClassDecl->hasTrivialDestructor())
2333 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002334
Douglas Gregore71edda2010-07-01 22:47:18 +00002335 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002336 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002337 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002338 << VBase->getType());
2339
John McCalla6309952010-03-16 21:39:52 +00002340 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002341 }
2342}
2343
John McCall48871652010-08-21 09:40:31 +00002344void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002345 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002346 return;
Mike Stump11289f42009-09-09 15:08:12 +00002347
Mike Stump11289f42009-09-09 15:08:12 +00002348 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002349 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002350 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002351}
2352
Mike Stump11289f42009-09-09 15:08:12 +00002353bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002354 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002355 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002356 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002357 else
John McCall02db245d2010-08-18 09:41:07 +00002358 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002359}
2360
Anders Carlssoneabf7702009-08-27 00:13:57 +00002361bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002362 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002363 if (!getLangOptions().CPlusPlus)
2364 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002365
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002366 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002367 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002368
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002369 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002370 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002371 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002372 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002373
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002374 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002375 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002376 }
Mike Stump11289f42009-09-09 15:08:12 +00002377
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002378 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002379 if (!RT)
2380 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002381
John McCall67da35c2010-02-04 22:26:26 +00002382 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002383
John McCall02db245d2010-08-18 09:41:07 +00002384 // We can't answer whether something is abstract until it has a
2385 // definition. If it's currently being defined, we'll walk back
2386 // over all the declarations when we have a full definition.
2387 const CXXRecordDecl *Def = RD->getDefinition();
2388 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002389 return false;
2390
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002391 if (!RD->isAbstract())
2392 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002393
Anders Carlssoneabf7702009-08-27 00:13:57 +00002394 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002395 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002396
John McCall02db245d2010-08-18 09:41:07 +00002397 return true;
2398}
2399
2400void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2401 // Check if we've already emitted the list of pure virtual functions
2402 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002403 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002404 return;
Mike Stump11289f42009-09-09 15:08:12 +00002405
Douglas Gregor4165bd62010-03-23 23:47:56 +00002406 CXXFinalOverriderMap FinalOverriders;
2407 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002408
Anders Carlssona2f74f32010-06-03 01:00:02 +00002409 // Keep a set of seen pure methods so we won't diagnose the same method
2410 // more than once.
2411 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2412
Douglas Gregor4165bd62010-03-23 23:47:56 +00002413 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2414 MEnd = FinalOverriders.end();
2415 M != MEnd;
2416 ++M) {
2417 for (OverridingMethods::iterator SO = M->second.begin(),
2418 SOEnd = M->second.end();
2419 SO != SOEnd; ++SO) {
2420 // C++ [class.abstract]p4:
2421 // A class is abstract if it contains or inherits at least one
2422 // pure virtual function for which the final overrider is pure
2423 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002424
Douglas Gregor4165bd62010-03-23 23:47:56 +00002425 //
2426 if (SO->second.size() != 1)
2427 continue;
2428
2429 if (!SO->second.front().Method->isPure())
2430 continue;
2431
Anders Carlssona2f74f32010-06-03 01:00:02 +00002432 if (!SeenPureMethods.insert(SO->second.front().Method))
2433 continue;
2434
Douglas Gregor4165bd62010-03-23 23:47:56 +00002435 Diag(SO->second.front().Method->getLocation(),
2436 diag::note_pure_virtual_function)
2437 << SO->second.front().Method->getDeclName();
2438 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002439 }
2440
2441 if (!PureVirtualClassDiagSet)
2442 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2443 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002444}
2445
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002446namespace {
John McCall02db245d2010-08-18 09:41:07 +00002447struct AbstractUsageInfo {
2448 Sema &S;
2449 CXXRecordDecl *Record;
2450 CanQualType AbstractType;
2451 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002452
John McCall02db245d2010-08-18 09:41:07 +00002453 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2454 : S(S), Record(Record),
2455 AbstractType(S.Context.getCanonicalType(
2456 S.Context.getTypeDeclType(Record))),
2457 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002458
John McCall02db245d2010-08-18 09:41:07 +00002459 void DiagnoseAbstractType() {
2460 if (Invalid) return;
2461 S.DiagnoseAbstractType(Record);
2462 Invalid = true;
2463 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002464
John McCall02db245d2010-08-18 09:41:07 +00002465 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2466};
2467
2468struct CheckAbstractUsage {
2469 AbstractUsageInfo &Info;
2470 const NamedDecl *Ctx;
2471
2472 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2473 : Info(Info), Ctx(Ctx) {}
2474
2475 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2476 switch (TL.getTypeLocClass()) {
2477#define ABSTRACT_TYPELOC(CLASS, PARENT)
2478#define TYPELOC(CLASS, PARENT) \
2479 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2480#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002481 }
John McCall02db245d2010-08-18 09:41:07 +00002482 }
Mike Stump11289f42009-09-09 15:08:12 +00002483
John McCall02db245d2010-08-18 09:41:07 +00002484 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2485 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2486 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2487 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2488 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002489 }
John McCall02db245d2010-08-18 09:41:07 +00002490 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002491
John McCall02db245d2010-08-18 09:41:07 +00002492 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2493 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2494 }
Mike Stump11289f42009-09-09 15:08:12 +00002495
John McCall02db245d2010-08-18 09:41:07 +00002496 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2497 // Visit the type parameters from a permissive context.
2498 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2499 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2500 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2501 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2502 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2503 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002504 }
John McCall02db245d2010-08-18 09:41:07 +00002505 }
Mike Stump11289f42009-09-09 15:08:12 +00002506
John McCall02db245d2010-08-18 09:41:07 +00002507 // Visit pointee types from a permissive context.
2508#define CheckPolymorphic(Type) \
2509 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2510 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2511 }
2512 CheckPolymorphic(PointerTypeLoc)
2513 CheckPolymorphic(ReferenceTypeLoc)
2514 CheckPolymorphic(MemberPointerTypeLoc)
2515 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002516
John McCall02db245d2010-08-18 09:41:07 +00002517 /// Handle all the types we haven't given a more specific
2518 /// implementation for above.
2519 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2520 // Every other kind of type that we haven't called out already
2521 // that has an inner type is either (1) sugar or (2) contains that
2522 // inner type in some way as a subobject.
2523 if (TypeLoc Next = TL.getNextTypeLoc())
2524 return Visit(Next, Sel);
2525
2526 // If there's no inner type and we're in a permissive context,
2527 // don't diagnose.
2528 if (Sel == Sema::AbstractNone) return;
2529
2530 // Check whether the type matches the abstract type.
2531 QualType T = TL.getType();
2532 if (T->isArrayType()) {
2533 Sel = Sema::AbstractArrayType;
2534 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002535 }
John McCall02db245d2010-08-18 09:41:07 +00002536 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2537 if (CT != Info.AbstractType) return;
2538
2539 // It matched; do some magic.
2540 if (Sel == Sema::AbstractArrayType) {
2541 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2542 << T << TL.getSourceRange();
2543 } else {
2544 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2545 << Sel << T << TL.getSourceRange();
2546 }
2547 Info.DiagnoseAbstractType();
2548 }
2549};
2550
2551void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2552 Sema::AbstractDiagSelID Sel) {
2553 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2554}
2555
2556}
2557
2558/// Check for invalid uses of an abstract type in a method declaration.
2559static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2560 CXXMethodDecl *MD) {
2561 // No need to do the check on definitions, which require that
2562 // the return/param types be complete.
2563 if (MD->isThisDeclarationADefinition())
2564 return;
2565
2566 // For safety's sake, just ignore it if we don't have type source
2567 // information. This should never happen for non-implicit methods,
2568 // but...
2569 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2570 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2571}
2572
2573/// Check for invalid uses of an abstract type within a class definition.
2574static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2575 CXXRecordDecl *RD) {
2576 for (CXXRecordDecl::decl_iterator
2577 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2578 Decl *D = *I;
2579 if (D->isImplicit()) continue;
2580
2581 // Methods and method templates.
2582 if (isa<CXXMethodDecl>(D)) {
2583 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2584 } else if (isa<FunctionTemplateDecl>(D)) {
2585 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2586 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2587
2588 // Fields and static variables.
2589 } else if (isa<FieldDecl>(D)) {
2590 FieldDecl *FD = cast<FieldDecl>(D);
2591 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2592 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2593 } else if (isa<VarDecl>(D)) {
2594 VarDecl *VD = cast<VarDecl>(D);
2595 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2596 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2597
2598 // Nested classes and class templates.
2599 } else if (isa<CXXRecordDecl>(D)) {
2600 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2601 } else if (isa<ClassTemplateDecl>(D)) {
2602 CheckAbstractClassUsage(Info,
2603 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2604 }
2605 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002606}
2607
Douglas Gregorc99f1552009-12-03 18:33:45 +00002608/// \brief Perform semantic checks on a class definition that has been
2609/// completing, introducing implicitly-declared members, checking for
2610/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002611void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002612 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002613 return;
2614
John McCall02db245d2010-08-18 09:41:07 +00002615 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2616 AbstractUsageInfo Info(*this, Record);
2617 CheckAbstractClassUsage(Info, Record);
2618 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002619
2620 // If this is not an aggregate type and has no user-declared constructor,
2621 // complain about any non-static data members of reference or const scalar
2622 // type, since they will never get initializers.
2623 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2624 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2625 bool Complained = false;
2626 for (RecordDecl::field_iterator F = Record->field_begin(),
2627 FEnd = Record->field_end();
2628 F != FEnd; ++F) {
2629 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002630 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002631 if (!Complained) {
2632 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2633 << Record->getTagKind() << Record;
2634 Complained = true;
2635 }
2636
2637 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2638 << F->getType()->isReferenceType()
2639 << F->getDeclName();
2640 }
2641 }
2642 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002643
2644 if (Record->isDynamicClass())
2645 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002646
2647 if (Record->getIdentifier()) {
2648 // C++ [class.mem]p13:
2649 // If T is the name of a class, then each of the following shall have a
2650 // name different from T:
2651 // - every member of every anonymous union that is a member of class T.
2652 //
2653 // C++ [class.mem]p14:
2654 // In addition, if class T has a user-declared constructor (12.1), every
2655 // non-static data member of class T shall have a name different from T.
2656 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002657 R.first != R.second; ++R.first) {
2658 NamedDecl *D = *R.first;
2659 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2660 isa<IndirectFieldDecl>(D)) {
2661 Diag(D->getLocation(), diag::err_member_name_of_class)
2662 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002663 break;
2664 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002665 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002666 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002667}
2668
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002669void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002670 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002671 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002672 SourceLocation RBrac,
2673 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002674 if (!TagDecl)
2675 return;
Mike Stump11289f42009-09-09 15:08:12 +00002676
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002677 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002678
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002679 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002680 // strict aliasing violation!
2681 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002682 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002683
Douglas Gregor0be31a22010-07-02 17:43:08 +00002684 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002685 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002686}
2687
Douglas Gregor95755162010-07-01 05:10:53 +00002688namespace {
2689 /// \brief Helper class that collects exception specifications for
2690 /// implicitly-declared special member functions.
2691 class ImplicitExceptionSpecification {
2692 ASTContext &Context;
2693 bool AllowsAllExceptions;
2694 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2695 llvm::SmallVector<QualType, 4> Exceptions;
2696
2697 public:
2698 explicit ImplicitExceptionSpecification(ASTContext &Context)
2699 : Context(Context), AllowsAllExceptions(false) { }
2700
2701 /// \brief Whether the special member function should have any
2702 /// exception specification at all.
2703 bool hasExceptionSpecification() const {
2704 return !AllowsAllExceptions;
2705 }
2706
2707 /// \brief Whether the special member function should have a
2708 /// throw(...) exception specification (a Microsoft extension).
2709 bool hasAnyExceptionSpecification() const {
2710 return false;
2711 }
2712
2713 /// \brief The number of exceptions in the exception specification.
2714 unsigned size() const { return Exceptions.size(); }
2715
2716 /// \brief The set of exceptions in the exception specification.
2717 const QualType *data() const { return Exceptions.data(); }
2718
2719 /// \brief Note that
2720 void CalledDecl(CXXMethodDecl *Method) {
2721 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002722 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002723 return;
2724
2725 const FunctionProtoType *Proto
2726 = Method->getType()->getAs<FunctionProtoType>();
2727
2728 // If this function can throw any exceptions, make a note of that.
2729 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2730 AllowsAllExceptions = true;
2731 ExceptionsSeen.clear();
2732 Exceptions.clear();
2733 return;
2734 }
2735
2736 // Record the exceptions in this function's exception specification.
2737 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2738 EEnd = Proto->exception_end();
2739 E != EEnd; ++E)
2740 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2741 Exceptions.push_back(*E);
2742 }
2743 };
2744}
2745
2746
Douglas Gregor05379422008-11-03 17:51:48 +00002747/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2748/// special functions, such as the default constructor, copy
2749/// constructor, or destructor, to the given C++ class (C++
2750/// [special]p1). This routine can only be executed just before the
2751/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002752void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002753 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002754 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002755
Douglas Gregor54be3392010-07-01 17:57:27 +00002756 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002757 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002758
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002759 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2760 ++ASTContext::NumImplicitCopyAssignmentOperators;
2761
2762 // If we have a dynamic class, then the copy assignment operator may be
2763 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2764 // it shows up in the right place in the vtable and that we diagnose
2765 // problems with the implicit exception specification.
2766 if (ClassDecl->isDynamicClass())
2767 DeclareImplicitCopyAssignment(ClassDecl);
2768 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002769
Douglas Gregor7454c562010-07-02 20:37:36 +00002770 if (!ClassDecl->hasUserDeclaredDestructor()) {
2771 ++ASTContext::NumImplicitDestructors;
2772
2773 // If we have a dynamic class, then the destructor may be virtual, so we
2774 // have to declare the destructor immediately. This ensures that, e.g., it
2775 // shows up in the right place in the vtable and that we diagnose problems
2776 // with the implicit exception specification.
2777 if (ClassDecl->isDynamicClass())
2778 DeclareImplicitDestructor(ClassDecl);
2779 }
Douglas Gregor05379422008-11-03 17:51:48 +00002780}
2781
John McCall48871652010-08-21 09:40:31 +00002782void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002783 if (!D)
2784 return;
2785
2786 TemplateParameterList *Params = 0;
2787 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2788 Params = Template->getTemplateParameters();
2789 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2790 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2791 Params = PartialSpec->getTemplateParameters();
2792 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002793 return;
2794
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002795 for (TemplateParameterList::iterator Param = Params->begin(),
2796 ParamEnd = Params->end();
2797 Param != ParamEnd; ++Param) {
2798 NamedDecl *Named = cast<NamedDecl>(*Param);
2799 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002800 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002801 IdResolver.AddDecl(Named);
2802 }
2803 }
2804}
2805
John McCall48871652010-08-21 09:40:31 +00002806void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002807 if (!RecordD) return;
2808 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002809 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002810 PushDeclContext(S, Record);
2811}
2812
John McCall48871652010-08-21 09:40:31 +00002813void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002814 if (!RecordD) return;
2815 PopDeclContext();
2816}
2817
Douglas Gregor4d87df52008-12-16 21:30:33 +00002818/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2819/// parsing a top-level (non-nested) C++ class, and we are now
2820/// parsing those parts of the given Method declaration that could
2821/// not be parsed earlier (C++ [class.mem]p2), such as default
2822/// arguments. This action should enter the scope of the given
2823/// Method declaration as if we had just parsed the qualified method
2824/// name. However, it should not bring the parameters into scope;
2825/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002826void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002827}
2828
2829/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2830/// C++ method declaration. We're (re-)introducing the given
2831/// function parameter into scope for use in parsing later parts of
2832/// the method declaration. For example, we could see an
2833/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002834void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002835 if (!ParamD)
2836 return;
Mike Stump11289f42009-09-09 15:08:12 +00002837
John McCall48871652010-08-21 09:40:31 +00002838 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002839
2840 // If this parameter has an unparsed default argument, clear it out
2841 // to make way for the parsed default argument.
2842 if (Param->hasUnparsedDefaultArg())
2843 Param->setDefaultArg(0);
2844
John McCall48871652010-08-21 09:40:31 +00002845 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002846 if (Param->getDeclName())
2847 IdResolver.AddDecl(Param);
2848}
2849
2850/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2851/// processing the delayed method declaration for Method. The method
2852/// declaration is now considered finished. There may be a separate
2853/// ActOnStartOfFunctionDef action later (not necessarily
2854/// immediately!) for this method, if it was also defined inside the
2855/// class body.
John McCall48871652010-08-21 09:40:31 +00002856void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002857 if (!MethodD)
2858 return;
Mike Stump11289f42009-09-09 15:08:12 +00002859
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002860 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002861
John McCall48871652010-08-21 09:40:31 +00002862 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002863
2864 // Now that we have our default arguments, check the constructor
2865 // again. It could produce additional diagnostics or affect whether
2866 // the class has implicitly-declared destructors, among other
2867 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002868 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2869 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002870
2871 // Check the default arguments, which we may have added.
2872 if (!Method->isInvalidDecl())
2873 CheckCXXDefaultArguments(Method);
2874}
2875
Douglas Gregor831c93f2008-11-05 20:51:48 +00002876/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002877/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002878/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002879/// emit diagnostics and set the invalid bit to true. In any case, the type
2880/// will be updated to reflect a well-formed type for the constructor and
2881/// returned.
2882QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002883 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002884 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002885
2886 // C++ [class.ctor]p3:
2887 // A constructor shall not be virtual (10.3) or static (9.4). A
2888 // constructor can be invoked for a const, volatile or const
2889 // volatile object. A constructor shall not be declared const,
2890 // volatile, or const volatile (9.3.2).
2891 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002892 if (!D.isInvalidType())
2893 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2894 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2895 << SourceRange(D.getIdentifierLoc());
2896 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002897 }
John McCall8e7d6562010-08-26 03:08:43 +00002898 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002899 if (!D.isInvalidType())
2900 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2901 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2902 << SourceRange(D.getIdentifierLoc());
2903 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002904 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002905 }
Mike Stump11289f42009-09-09 15:08:12 +00002906
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002907 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002908 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002909 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002910 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2911 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002912 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002913 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2914 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002915 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002916 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2917 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002918 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002919 }
Mike Stump11289f42009-09-09 15:08:12 +00002920
Douglas Gregor831c93f2008-11-05 20:51:48 +00002921 // Rebuild the function type "R" without any type qualifiers (in
2922 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002923 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002924 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002925 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2926 return R;
2927
2928 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2929 EPI.TypeQuals = 0;
2930
Chris Lattner38378bf2009-04-25 08:28:21 +00002931 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002932 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002933}
2934
Douglas Gregor4d87df52008-12-16 21:30:33 +00002935/// CheckConstructor - Checks a fully-formed constructor for
2936/// well-formedness, issuing any diagnostics required. Returns true if
2937/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002938void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002939 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002940 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2941 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002942 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002943
2944 // C++ [class.copy]p3:
2945 // A declaration of a constructor for a class X is ill-formed if
2946 // its first parameter is of type (optionally cv-qualified) X and
2947 // either there are no other parameters or else all other
2948 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002949 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002950 ((Constructor->getNumParams() == 1) ||
2951 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002952 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2953 Constructor->getTemplateSpecializationKind()
2954 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002955 QualType ParamType = Constructor->getParamDecl(0)->getType();
2956 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2957 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002958 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002959 const char *ConstRef
2960 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2961 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002962 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002963 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002964
2965 // FIXME: Rather that making the constructor invalid, we should endeavor
2966 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002967 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002968 }
2969 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002970}
2971
John McCalldeb646e2010-08-04 01:04:25 +00002972/// CheckDestructor - Checks a fully-formed destructor definition for
2973/// well-formedness, issuing any diagnostics required. Returns true
2974/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002975bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002976 CXXRecordDecl *RD = Destructor->getParent();
2977
2978 if (Destructor->isVirtual()) {
2979 SourceLocation Loc;
2980
2981 if (!Destructor->isImplicit())
2982 Loc = Destructor->getLocation();
2983 else
2984 Loc = RD->getLocation();
2985
2986 // If we have a virtual destructor, look up the deallocation function
2987 FunctionDecl *OperatorDelete = 0;
2988 DeclarationName Name =
2989 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002990 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002991 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002992
2993 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002994
2995 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002996 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002997
2998 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002999}
3000
Mike Stump11289f42009-09-09 15:08:12 +00003001static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003002FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3003 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3004 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003005 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003006}
3007
Douglas Gregor831c93f2008-11-05 20:51:48 +00003008/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3009/// the well-formednes of the destructor declarator @p D with type @p
3010/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003011/// emit diagnostics and set the declarator to invalid. Even if this happens,
3012/// will be updated to reflect a well-formed type for the destructor and
3013/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003014QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003015 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003016 // C++ [class.dtor]p1:
3017 // [...] A typedef-name that names a class is a class-name
3018 // (7.1.3); however, a typedef-name that names a class shall not
3019 // be used as the identifier in the declarator for a destructor
3020 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003021 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003022 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003023 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003024 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003025
3026 // C++ [class.dtor]p2:
3027 // A destructor is used to destroy objects of its class type. A
3028 // destructor takes no parameters, and no return type can be
3029 // specified for it (not even void). The address of a destructor
3030 // shall not be taken. A destructor shall not be static. A
3031 // destructor can be invoked for a const, volatile or const
3032 // volatile object. A destructor shall not be declared const,
3033 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003034 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003035 if (!D.isInvalidType())
3036 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3037 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003038 << SourceRange(D.getIdentifierLoc())
3039 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3040
John McCall8e7d6562010-08-26 03:08:43 +00003041 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003042 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003043 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003044 // Destructors don't have return types, but the parser will
3045 // happily parse something like:
3046 //
3047 // class X {
3048 // float ~X();
3049 // };
3050 //
3051 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003052 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3053 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3054 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003055 }
Mike Stump11289f42009-09-09 15:08:12 +00003056
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003057 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003058 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003059 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003060 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3061 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003062 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003063 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3064 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003065 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003066 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3067 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003068 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003069 }
3070
3071 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003072 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003073 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3074
3075 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003076 FTI.freeArgs();
3077 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003078 }
3079
Mike Stump11289f42009-09-09 15:08:12 +00003080 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003081 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003082 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003083 D.setInvalidType();
3084 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003085
3086 // Rebuild the function type "R" without any type qualifiers or
3087 // parameters (in case any of the errors above fired) and with
3088 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003089 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003090 if (!D.isInvalidType())
3091 return R;
3092
Douglas Gregor95755162010-07-01 05:10:53 +00003093 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003094 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3095 EPI.Variadic = false;
3096 EPI.TypeQuals = 0;
3097 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003098}
3099
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003100/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3101/// well-formednes of the conversion function declarator @p D with
3102/// type @p R. If there are any errors in the declarator, this routine
3103/// will emit diagnostics and return true. Otherwise, it will return
3104/// false. Either way, the type @p R will be updated to reflect a
3105/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003106void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003107 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003108 // C++ [class.conv.fct]p1:
3109 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003110 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003111 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003112 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003113 if (!D.isInvalidType())
3114 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3115 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3116 << SourceRange(D.getIdentifierLoc());
3117 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003118 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003119 }
John McCall212fa2e2010-04-13 00:04:31 +00003120
3121 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3122
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003123 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003124 // Conversion functions don't have return types, but the parser will
3125 // happily parse something like:
3126 //
3127 // class X {
3128 // float operator bool();
3129 // };
3130 //
3131 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003132 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3133 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3134 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003135 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003136 }
3137
John McCall212fa2e2010-04-13 00:04:31 +00003138 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3139
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003140 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003141 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003142 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3143
3144 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003145 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003146 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003147 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003148 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003149 D.setInvalidType();
3150 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003151
John McCall212fa2e2010-04-13 00:04:31 +00003152 // Diagnose "&operator bool()" and other such nonsense. This
3153 // is actually a gcc extension which we don't support.
3154 if (Proto->getResultType() != ConvType) {
3155 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3156 << Proto->getResultType();
3157 D.setInvalidType();
3158 ConvType = Proto->getResultType();
3159 }
3160
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003161 // C++ [class.conv.fct]p4:
3162 // The conversion-type-id shall not represent a function type nor
3163 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003164 if (ConvType->isArrayType()) {
3165 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3166 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003167 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003168 } else if (ConvType->isFunctionType()) {
3169 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3170 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003171 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003172 }
3173
3174 // Rebuild the function type "R" without any parameters (in case any
3175 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003176 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003177 if (D.isInvalidType())
3178 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003179
Douglas Gregor5fb53972009-01-14 15:45:31 +00003180 // C++0x explicit conversion operators.
3181 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003182 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003183 diag::warn_explicit_conversion_functions)
3184 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003185}
3186
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003187/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3188/// the declaration of the given C++ conversion function. This routine
3189/// is responsible for recording the conversion function in the C++
3190/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003191Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003192 assert(Conversion && "Expected to receive a conversion function declaration");
3193
Douglas Gregor4287b372008-12-12 08:25:50 +00003194 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003195
3196 // Make sure we aren't redeclaring the conversion function.
3197 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003198
3199 // C++ [class.conv.fct]p1:
3200 // [...] A conversion function is never used to convert a
3201 // (possibly cv-qualified) object to the (possibly cv-qualified)
3202 // same object type (or a reference to it), to a (possibly
3203 // cv-qualified) base class of that type (or a reference to it),
3204 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003205 // FIXME: Suppress this warning if the conversion function ends up being a
3206 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003207 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003208 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003209 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003210 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003211 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3212 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003213 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003214 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003215 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3216 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003217 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003218 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003219 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003220 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003221 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003222 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003223 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003224 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003225 }
3226
Douglas Gregor457104e2010-09-29 04:25:11 +00003227 if (FunctionTemplateDecl *ConversionTemplate
3228 = Conversion->getDescribedFunctionTemplate())
3229 return ConversionTemplate;
3230
John McCall48871652010-08-21 09:40:31 +00003231 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003232}
3233
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003234//===----------------------------------------------------------------------===//
3235// Namespace Handling
3236//===----------------------------------------------------------------------===//
3237
John McCallb1be5232010-08-26 09:15:37 +00003238
3239
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003240/// ActOnStartNamespaceDef - This is called at the start of a namespace
3241/// definition.
John McCall48871652010-08-21 09:40:31 +00003242Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003243 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003244 SourceLocation IdentLoc,
3245 IdentifierInfo *II,
3246 SourceLocation LBrace,
3247 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003248 // anonymous namespace starts at its left brace
3249 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3250 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003251 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003252 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003253
3254 Scope *DeclRegionScope = NamespcScope->getParent();
3255
Anders Carlssona7bcade2010-02-07 01:09:23 +00003256 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3257
John McCall2faf32c2010-12-10 02:59:44 +00003258 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3259 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003260
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003261 if (II) {
3262 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003263 // The identifier in an original-namespace-definition shall not
3264 // have been previously defined in the declarative region in
3265 // which the original-namespace-definition appears. The
3266 // identifier in an original-namespace-definition is the name of
3267 // the namespace. Subsequently in that declarative region, it is
3268 // treated as an original-namespace-name.
3269 //
3270 // Since namespace names are unique in their scope, and we don't
3271 // look through using directives, just
3272 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3273 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregor91f84212008-12-11 16:49:14 +00003275 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3276 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003277 if (Namespc->isInline() != OrigNS->isInline()) {
3278 // inline-ness must match
3279 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3280 << Namespc->isInline();
3281 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3282 Namespc->setInvalidDecl();
3283 // Recover by ignoring the new namespace's inline status.
3284 Namespc->setInline(OrigNS->isInline());
3285 }
3286
Douglas Gregor91f84212008-12-11 16:49:14 +00003287 // Attach this namespace decl to the chain of extended namespace
3288 // definitions.
3289 OrigNS->setNextNamespace(Namespc);
3290 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003291
Mike Stump11289f42009-09-09 15:08:12 +00003292 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003293 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003294 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003295 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003296 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003297 } else if (PrevDecl) {
3298 // This is an invalid name redefinition.
3299 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3300 << Namespc->getDeclName();
3301 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3302 Namespc->setInvalidDecl();
3303 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003304 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003305 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003306 // This is the first "real" definition of the namespace "std", so update
3307 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003308 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003309 // We had already defined a dummy namespace "std". Link this new
3310 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003311 StdNS->setNextNamespace(Namespc);
3312 StdNS->setLocation(IdentLoc);
3313 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003314 }
3315
3316 // Make our StdNamespace cache point at the first real definition of the
3317 // "std" namespace.
3318 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003319 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003320
3321 PushOnScopeChains(Namespc, DeclRegionScope);
3322 } else {
John McCall4fa53422009-10-01 00:25:31 +00003323 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003324 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003325
3326 // Link the anonymous namespace into its parent.
3327 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003328 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003329 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3330 PrevDecl = TU->getAnonymousNamespace();
3331 TU->setAnonymousNamespace(Namespc);
3332 } else {
3333 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3334 PrevDecl = ND->getAnonymousNamespace();
3335 ND->setAnonymousNamespace(Namespc);
3336 }
3337
3338 // Link the anonymous namespace with its previous declaration.
3339 if (PrevDecl) {
3340 assert(PrevDecl->isAnonymousNamespace());
3341 assert(!PrevDecl->getNextNamespace());
3342 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3343 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003344
3345 if (Namespc->isInline() != PrevDecl->isInline()) {
3346 // inline-ness must match
3347 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3348 << Namespc->isInline();
3349 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3350 Namespc->setInvalidDecl();
3351 // Recover by ignoring the new namespace's inline status.
3352 Namespc->setInline(PrevDecl->isInline());
3353 }
John McCall0db42252009-12-16 02:06:49 +00003354 }
John McCall4fa53422009-10-01 00:25:31 +00003355
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003356 CurContext->addDecl(Namespc);
3357
John McCall4fa53422009-10-01 00:25:31 +00003358 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3359 // behaves as if it were replaced by
3360 // namespace unique { /* empty body */ }
3361 // using namespace unique;
3362 // namespace unique { namespace-body }
3363 // where all occurrences of 'unique' in a translation unit are
3364 // replaced by the same identifier and this identifier differs
3365 // from all other identifiers in the entire program.
3366
3367 // We just create the namespace with an empty name and then add an
3368 // implicit using declaration, just like the standard suggests.
3369 //
3370 // CodeGen enforces the "universally unique" aspect by giving all
3371 // declarations semantically contained within an anonymous
3372 // namespace internal linkage.
3373
John McCall0db42252009-12-16 02:06:49 +00003374 if (!PrevDecl) {
3375 UsingDirectiveDecl* UD
3376 = UsingDirectiveDecl::Create(Context, CurContext,
3377 /* 'using' */ LBrace,
3378 /* 'namespace' */ SourceLocation(),
3379 /* qualifier */ SourceRange(),
3380 /* NNS */ NULL,
3381 /* identifier */ SourceLocation(),
3382 Namespc,
3383 /* Ancestor */ CurContext);
3384 UD->setImplicit();
3385 CurContext->addDecl(UD);
3386 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003387 }
3388
3389 // Although we could have an invalid decl (i.e. the namespace name is a
3390 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003391 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3392 // for the namespace has the declarations that showed up in that particular
3393 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003394 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003395 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003396}
3397
Sebastian Redla6602e92009-11-23 15:34:23 +00003398/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3399/// is a namespace alias, returns the namespace it points to.
3400static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3401 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3402 return AD->getNamespace();
3403 return dyn_cast_or_null<NamespaceDecl>(D);
3404}
3405
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003406/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3407/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003408void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003409 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3410 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3411 Namespc->setRBracLoc(RBrace);
3412 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003413 if (Namespc->hasAttr<VisibilityAttr>())
3414 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003415}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003416
John McCall28a0cf72010-08-25 07:42:41 +00003417CXXRecordDecl *Sema::getStdBadAlloc() const {
3418 return cast_or_null<CXXRecordDecl>(
3419 StdBadAlloc.get(Context.getExternalSource()));
3420}
3421
3422NamespaceDecl *Sema::getStdNamespace() const {
3423 return cast_or_null<NamespaceDecl>(
3424 StdNamespace.get(Context.getExternalSource()));
3425}
3426
Douglas Gregorcdf87022010-06-29 17:53:46 +00003427/// \brief Retrieve the special "std" namespace, which may require us to
3428/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003429NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003430 if (!StdNamespace) {
3431 // The "std" namespace has not yet been defined, so build one implicitly.
3432 StdNamespace = NamespaceDecl::Create(Context,
3433 Context.getTranslationUnitDecl(),
3434 SourceLocation(),
3435 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003436 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003437 }
3438
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003439 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003440}
3441
John McCall48871652010-08-21 09:40:31 +00003442Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003443 SourceLocation UsingLoc,
3444 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003445 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003446 SourceLocation IdentLoc,
3447 IdentifierInfo *NamespcName,
3448 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003449 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3450 assert(NamespcName && "Invalid NamespcName.");
3451 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003452
3453 // This can only happen along a recovery path.
3454 while (S->getFlags() & Scope::TemplateParamScope)
3455 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003456 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003457
Douglas Gregor889ceb72009-02-03 19:21:40 +00003458 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003459 NestedNameSpecifier *Qualifier = 0;
3460 if (SS.isSet())
3461 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3462
Douglas Gregor34074322009-01-14 22:20:51 +00003463 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003464 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3465 LookupParsedName(R, S, &SS);
3466 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003467 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003468
Douglas Gregorcdf87022010-06-29 17:53:46 +00003469 if (R.empty()) {
3470 // Allow "using namespace std;" or "using namespace ::std;" even if
3471 // "std" hasn't been defined yet, for GCC compatibility.
3472 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3473 NamespcName->isStr("std")) {
3474 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003475 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003476 R.resolveKind();
3477 }
3478 // Otherwise, attempt typo correction.
3479 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3480 CTC_NoKeywords, 0)) {
3481 if (R.getAsSingle<NamespaceDecl>() ||
3482 R.getAsSingle<NamespaceAliasDecl>()) {
3483 if (DeclContext *DC = computeDeclContext(SS, false))
3484 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3485 << NamespcName << DC << Corrected << SS.getRange()
3486 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3487 else
3488 Diag(IdentLoc, diag::err_using_directive_suggest)
3489 << NamespcName << Corrected
3490 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3491 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3492 << Corrected;
3493
3494 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003495 } else {
3496 R.clear();
3497 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003498 }
3499 }
3500 }
3501
John McCall9f3059a2009-10-09 21:13:30 +00003502 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003503 NamedDecl *Named = R.getFoundDecl();
3504 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3505 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003506 // C++ [namespace.udir]p1:
3507 // A using-directive specifies that the names in the nominated
3508 // namespace can be used in the scope in which the
3509 // using-directive appears after the using-directive. During
3510 // unqualified name lookup (3.4.1), the names appear as if they
3511 // were declared in the nearest enclosing namespace which
3512 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003513 // namespace. [Note: in this context, "contains" means "contains
3514 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003515
3516 // Find enclosing context containing both using-directive and
3517 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003518 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003519 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3520 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3521 CommonAncestor = CommonAncestor->getParent();
3522
Sebastian Redla6602e92009-11-23 15:34:23 +00003523 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003524 SS.getRange(),
3525 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003526 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003527 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003528 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003529 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003530 }
3531
Douglas Gregor889ceb72009-02-03 19:21:40 +00003532 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003533 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003534}
3535
3536void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3537 // If scope has associated entity, then using directive is at namespace
3538 // or translation unit scope. We add UsingDirectiveDecls, into
3539 // it's lookup structure.
3540 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003541 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003542 else
3543 // Otherwise it is block-sope. using-directives will affect lookup
3544 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003545 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003546}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003547
Douglas Gregorfec52632009-06-20 00:51:54 +00003548
John McCall48871652010-08-21 09:40:31 +00003549Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003550 AccessSpecifier AS,
3551 bool HasUsingKeyword,
3552 SourceLocation UsingLoc,
3553 CXXScopeSpec &SS,
3554 UnqualifiedId &Name,
3555 AttributeList *AttrList,
3556 bool IsTypeName,
3557 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003558 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003559
Douglas Gregor220f4272009-11-04 16:30:06 +00003560 switch (Name.getKind()) {
3561 case UnqualifiedId::IK_Identifier:
3562 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003563 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003564 case UnqualifiedId::IK_ConversionFunctionId:
3565 break;
3566
3567 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003568 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003569 // C++0x inherited constructors.
3570 if (getLangOptions().CPlusPlus0x) break;
3571
Douglas Gregor220f4272009-11-04 16:30:06 +00003572 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3573 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003574 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003575
3576 case UnqualifiedId::IK_DestructorName:
3577 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3578 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003579 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003580
3581 case UnqualifiedId::IK_TemplateId:
3582 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3583 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003584 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003585 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003586
3587 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3588 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003589 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003590 return 0;
John McCall3969e302009-12-08 07:46:18 +00003591
John McCalla0097262009-12-11 02:10:03 +00003592 // Warn about using declarations.
3593 // TODO: store that the declaration was written without 'using' and
3594 // talk about access decls instead of using decls in the
3595 // diagnostics.
3596 if (!HasUsingKeyword) {
3597 UsingLoc = Name.getSourceRange().getBegin();
3598
3599 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003600 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003601 }
3602
Douglas Gregorc4356532010-12-16 00:46:58 +00003603 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3604 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3605 return 0;
3606
John McCall3f746822009-11-17 05:59:44 +00003607 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003608 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003609 /* IsInstantiation */ false,
3610 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003611 if (UD)
3612 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003613
John McCall48871652010-08-21 09:40:31 +00003614 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003615}
3616
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003617/// \brief Determine whether a using declaration considers the given
3618/// declarations as "equivalent", e.g., if they are redeclarations of
3619/// the same entity or are both typedefs of the same type.
3620static bool
3621IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3622 bool &SuppressRedeclaration) {
3623 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3624 SuppressRedeclaration = false;
3625 return true;
3626 }
3627
3628 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3629 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3630 SuppressRedeclaration = true;
3631 return Context.hasSameType(TD1->getUnderlyingType(),
3632 TD2->getUnderlyingType());
3633 }
3634
3635 return false;
3636}
3637
3638
John McCall84d87672009-12-10 09:41:52 +00003639/// Determines whether to create a using shadow decl for a particular
3640/// decl, given the set of decls existing prior to this using lookup.
3641bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3642 const LookupResult &Previous) {
3643 // Diagnose finding a decl which is not from a base class of the
3644 // current class. We do this now because there are cases where this
3645 // function will silently decide not to build a shadow decl, which
3646 // will pre-empt further diagnostics.
3647 //
3648 // We don't need to do this in C++0x because we do the check once on
3649 // the qualifier.
3650 //
3651 // FIXME: diagnose the following if we care enough:
3652 // struct A { int foo; };
3653 // struct B : A { using A::foo; };
3654 // template <class T> struct C : A {};
3655 // template <class T> struct D : C<T> { using B::foo; } // <---
3656 // This is invalid (during instantiation) in C++03 because B::foo
3657 // resolves to the using decl in B, which is not a base class of D<T>.
3658 // We can't diagnose it immediately because C<T> is an unknown
3659 // specialization. The UsingShadowDecl in D<T> then points directly
3660 // to A::foo, which will look well-formed when we instantiate.
3661 // The right solution is to not collapse the shadow-decl chain.
3662 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3663 DeclContext *OrigDC = Orig->getDeclContext();
3664
3665 // Handle enums and anonymous structs.
3666 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3667 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3668 while (OrigRec->isAnonymousStructOrUnion())
3669 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3670
3671 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3672 if (OrigDC == CurContext) {
3673 Diag(Using->getLocation(),
3674 diag::err_using_decl_nested_name_specifier_is_current_class)
3675 << Using->getNestedNameRange();
3676 Diag(Orig->getLocation(), diag::note_using_decl_target);
3677 return true;
3678 }
3679
3680 Diag(Using->getNestedNameRange().getBegin(),
3681 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3682 << Using->getTargetNestedNameDecl()
3683 << cast<CXXRecordDecl>(CurContext)
3684 << Using->getNestedNameRange();
3685 Diag(Orig->getLocation(), diag::note_using_decl_target);
3686 return true;
3687 }
3688 }
3689
3690 if (Previous.empty()) return false;
3691
3692 NamedDecl *Target = Orig;
3693 if (isa<UsingShadowDecl>(Target))
3694 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3695
John McCalla17e83e2009-12-11 02:33:26 +00003696 // If the target happens to be one of the previous declarations, we
3697 // don't have a conflict.
3698 //
3699 // FIXME: but we might be increasing its access, in which case we
3700 // should redeclare it.
3701 NamedDecl *NonTag = 0, *Tag = 0;
3702 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3703 I != E; ++I) {
3704 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003705 bool Result;
3706 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3707 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003708
3709 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3710 }
3711
John McCall84d87672009-12-10 09:41:52 +00003712 if (Target->isFunctionOrFunctionTemplate()) {
3713 FunctionDecl *FD;
3714 if (isa<FunctionTemplateDecl>(Target))
3715 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3716 else
3717 FD = cast<FunctionDecl>(Target);
3718
3719 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003720 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003721 case Ovl_Overload:
3722 return false;
3723
3724 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003725 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003726 break;
3727
3728 // We found a decl with the exact signature.
3729 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003730 // If we're in a record, we want to hide the target, so we
3731 // return true (without a diagnostic) to tell the caller not to
3732 // build a shadow decl.
3733 if (CurContext->isRecord())
3734 return true;
3735
3736 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003737 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003738 break;
3739 }
3740
3741 Diag(Target->getLocation(), diag::note_using_decl_target);
3742 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3743 return true;
3744 }
3745
3746 // Target is not a function.
3747
John McCall84d87672009-12-10 09:41:52 +00003748 if (isa<TagDecl>(Target)) {
3749 // No conflict between a tag and a non-tag.
3750 if (!Tag) return false;
3751
John McCalle29c5cd2009-12-10 19:51:03 +00003752 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003753 Diag(Target->getLocation(), diag::note_using_decl_target);
3754 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3755 return true;
3756 }
3757
3758 // No conflict between a tag and a non-tag.
3759 if (!NonTag) return false;
3760
John McCalle29c5cd2009-12-10 19:51:03 +00003761 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003762 Diag(Target->getLocation(), diag::note_using_decl_target);
3763 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3764 return true;
3765}
3766
John McCall3f746822009-11-17 05:59:44 +00003767/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003768UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003769 UsingDecl *UD,
3770 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003771
3772 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003773 NamedDecl *Target = Orig;
3774 if (isa<UsingShadowDecl>(Target)) {
3775 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3776 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003777 }
3778
3779 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003780 = UsingShadowDecl::Create(Context, CurContext,
3781 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003782 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003783
3784 Shadow->setAccess(UD->getAccess());
3785 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3786 Shadow->setInvalidDecl();
3787
John McCall3f746822009-11-17 05:59:44 +00003788 if (S)
John McCall3969e302009-12-08 07:46:18 +00003789 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003790 else
John McCall3969e302009-12-08 07:46:18 +00003791 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003792
John McCall3969e302009-12-08 07:46:18 +00003793
John McCall84d87672009-12-10 09:41:52 +00003794 return Shadow;
3795}
John McCall3969e302009-12-08 07:46:18 +00003796
John McCall84d87672009-12-10 09:41:52 +00003797/// Hides a using shadow declaration. This is required by the current
3798/// using-decl implementation when a resolvable using declaration in a
3799/// class is followed by a declaration which would hide or override
3800/// one or more of the using decl's targets; for example:
3801///
3802/// struct Base { void foo(int); };
3803/// struct Derived : Base {
3804/// using Base::foo;
3805/// void foo(int);
3806/// };
3807///
3808/// The governing language is C++03 [namespace.udecl]p12:
3809///
3810/// When a using-declaration brings names from a base class into a
3811/// derived class scope, member functions in the derived class
3812/// override and/or hide member functions with the same name and
3813/// parameter types in a base class (rather than conflicting).
3814///
3815/// There are two ways to implement this:
3816/// (1) optimistically create shadow decls when they're not hidden
3817/// by existing declarations, or
3818/// (2) don't create any shadow decls (or at least don't make them
3819/// visible) until we've fully parsed/instantiated the class.
3820/// The problem with (1) is that we might have to retroactively remove
3821/// a shadow decl, which requires several O(n) operations because the
3822/// decl structures are (very reasonably) not designed for removal.
3823/// (2) avoids this but is very fiddly and phase-dependent.
3824void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003825 if (Shadow->getDeclName().getNameKind() ==
3826 DeclarationName::CXXConversionFunctionName)
3827 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3828
John McCall84d87672009-12-10 09:41:52 +00003829 // Remove it from the DeclContext...
3830 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003831
John McCall84d87672009-12-10 09:41:52 +00003832 // ...and the scope, if applicable...
3833 if (S) {
John McCall48871652010-08-21 09:40:31 +00003834 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003835 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003836 }
3837
John McCall84d87672009-12-10 09:41:52 +00003838 // ...and the using decl.
3839 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3840
3841 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003842 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003843}
3844
John McCalle61f2ba2009-11-18 02:36:19 +00003845/// Builds a using declaration.
3846///
3847/// \param IsInstantiation - Whether this call arises from an
3848/// instantiation of an unresolved using declaration. We treat
3849/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003850NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3851 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003852 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003853 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003854 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003855 bool IsInstantiation,
3856 bool IsTypeName,
3857 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003858 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003859 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003860 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003861
Anders Carlssonf038fc22009-08-28 05:49:21 +00003862 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003863
Anders Carlsson59140b32009-08-28 03:16:11 +00003864 if (SS.isEmpty()) {
3865 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003866 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003867 }
Mike Stump11289f42009-09-09 15:08:12 +00003868
John McCall84d87672009-12-10 09:41:52 +00003869 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003870 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003871 ForRedeclaration);
3872 Previous.setHideTags(false);
3873 if (S) {
3874 LookupName(Previous, S);
3875
3876 // It is really dumb that we have to do this.
3877 LookupResult::Filter F = Previous.makeFilter();
3878 while (F.hasNext()) {
3879 NamedDecl *D = F.next();
3880 if (!isDeclInScope(D, CurContext, S))
3881 F.erase();
3882 }
3883 F.done();
3884 } else {
3885 assert(IsInstantiation && "no scope in non-instantiation");
3886 assert(CurContext->isRecord() && "scope not record in instantiation");
3887 LookupQualifiedName(Previous, CurContext);
3888 }
3889
Mike Stump11289f42009-09-09 15:08:12 +00003890 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003891 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3892
John McCall84d87672009-12-10 09:41:52 +00003893 // Check for invalid redeclarations.
3894 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3895 return 0;
3896
3897 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003898 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3899 return 0;
3900
John McCall84c16cf2009-11-12 03:15:40 +00003901 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003902 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003903 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003904 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003905 // FIXME: not all declaration name kinds are legal here
3906 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3907 UsingLoc, TypenameLoc,
3908 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003909 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003910 } else {
3911 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003912 UsingLoc, SS.getRange(),
3913 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003914 }
John McCallb96ec562009-12-04 22:46:56 +00003915 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003916 D = UsingDecl::Create(Context, CurContext,
3917 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003918 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003919 }
John McCallb96ec562009-12-04 22:46:56 +00003920 D->setAccess(AS);
3921 CurContext->addDecl(D);
3922
3923 if (!LookupContext) return D;
3924 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003925
John McCall0b66eb32010-05-01 00:40:08 +00003926 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003927 UD->setInvalidDecl();
3928 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003929 }
3930
John McCall3969e302009-12-08 07:46:18 +00003931 // Look up the target name.
3932
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003933 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003934
John McCall3969e302009-12-08 07:46:18 +00003935 // Unlike most lookups, we don't always want to hide tag
3936 // declarations: tag names are visible through the using declaration
3937 // even if hidden by ordinary names, *except* in a dependent context
3938 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003939 if (!IsInstantiation)
3940 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003941
John McCall27b18f82009-11-17 02:14:36 +00003942 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003943
John McCall9f3059a2009-10-09 21:13:30 +00003944 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003945 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003946 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003947 UD->setInvalidDecl();
3948 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003949 }
3950
John McCallb96ec562009-12-04 22:46:56 +00003951 if (R.isAmbiguous()) {
3952 UD->setInvalidDecl();
3953 return UD;
3954 }
Mike Stump11289f42009-09-09 15:08:12 +00003955
John McCalle61f2ba2009-11-18 02:36:19 +00003956 if (IsTypeName) {
3957 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003958 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003959 Diag(IdentLoc, diag::err_using_typename_non_type);
3960 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3961 Diag((*I)->getUnderlyingDecl()->getLocation(),
3962 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003963 UD->setInvalidDecl();
3964 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003965 }
3966 } else {
3967 // If we asked for a non-typename and we got a type, error out,
3968 // but only if this is an instantiation of an unresolved using
3969 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003970 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003971 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3972 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003973 UD->setInvalidDecl();
3974 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003975 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003976 }
3977
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003978 // C++0x N2914 [namespace.udecl]p6:
3979 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003980 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003981 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3982 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003983 UD->setInvalidDecl();
3984 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986
John McCall84d87672009-12-10 09:41:52 +00003987 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3988 if (!CheckUsingShadowDecl(UD, *I, Previous))
3989 BuildUsingShadowDecl(S, UD, *I);
3990 }
John McCall3f746822009-11-17 05:59:44 +00003991
3992 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003993}
3994
John McCall84d87672009-12-10 09:41:52 +00003995/// Checks that the given using declaration is not an invalid
3996/// redeclaration. Note that this is checking only for the using decl
3997/// itself, not for any ill-formedness among the UsingShadowDecls.
3998bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3999 bool isTypeName,
4000 const CXXScopeSpec &SS,
4001 SourceLocation NameLoc,
4002 const LookupResult &Prev) {
4003 // C++03 [namespace.udecl]p8:
4004 // C++0x [namespace.udecl]p10:
4005 // A using-declaration is a declaration and can therefore be used
4006 // repeatedly where (and only where) multiple declarations are
4007 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004008 //
John McCall032092f2010-11-29 18:01:58 +00004009 // That's in non-member contexts.
4010 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004011 return false;
4012
4013 NestedNameSpecifier *Qual
4014 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4015
4016 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4017 NamedDecl *D = *I;
4018
4019 bool DTypename;
4020 NestedNameSpecifier *DQual;
4021 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4022 DTypename = UD->isTypeName();
4023 DQual = UD->getTargetNestedNameDecl();
4024 } else if (UnresolvedUsingValueDecl *UD
4025 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4026 DTypename = false;
4027 DQual = UD->getTargetNestedNameSpecifier();
4028 } else if (UnresolvedUsingTypenameDecl *UD
4029 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4030 DTypename = true;
4031 DQual = UD->getTargetNestedNameSpecifier();
4032 } else continue;
4033
4034 // using decls differ if one says 'typename' and the other doesn't.
4035 // FIXME: non-dependent using decls?
4036 if (isTypeName != DTypename) continue;
4037
4038 // using decls differ if they name different scopes (but note that
4039 // template instantiation can cause this check to trigger when it
4040 // didn't before instantiation).
4041 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4042 Context.getCanonicalNestedNameSpecifier(DQual))
4043 continue;
4044
4045 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004046 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004047 return true;
4048 }
4049
4050 return false;
4051}
4052
John McCall3969e302009-12-08 07:46:18 +00004053
John McCallb96ec562009-12-04 22:46:56 +00004054/// Checks that the given nested-name qualifier used in a using decl
4055/// in the current context is appropriately related to the current
4056/// scope. If an error is found, diagnoses it and returns true.
4057bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4058 const CXXScopeSpec &SS,
4059 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004060 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004061
John McCall3969e302009-12-08 07:46:18 +00004062 if (!CurContext->isRecord()) {
4063 // C++03 [namespace.udecl]p3:
4064 // C++0x [namespace.udecl]p8:
4065 // A using-declaration for a class member shall be a member-declaration.
4066
4067 // If we weren't able to compute a valid scope, it must be a
4068 // dependent class scope.
4069 if (!NamedContext || NamedContext->isRecord()) {
4070 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4071 << SS.getRange();
4072 return true;
4073 }
4074
4075 // Otherwise, everything is known to be fine.
4076 return false;
4077 }
4078
4079 // The current scope is a record.
4080
4081 // If the named context is dependent, we can't decide much.
4082 if (!NamedContext) {
4083 // FIXME: in C++0x, we can diagnose if we can prove that the
4084 // nested-name-specifier does not refer to a base class, which is
4085 // still possible in some cases.
4086
4087 // Otherwise we have to conservatively report that things might be
4088 // okay.
4089 return false;
4090 }
4091
4092 if (!NamedContext->isRecord()) {
4093 // Ideally this would point at the last name in the specifier,
4094 // but we don't have that level of source info.
4095 Diag(SS.getRange().getBegin(),
4096 diag::err_using_decl_nested_name_specifier_is_not_class)
4097 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4098 return true;
4099 }
4100
Douglas Gregor7c842292010-12-21 07:41:49 +00004101 if (!NamedContext->isDependentContext() &&
4102 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4103 return true;
4104
John McCall3969e302009-12-08 07:46:18 +00004105 if (getLangOptions().CPlusPlus0x) {
4106 // C++0x [namespace.udecl]p3:
4107 // In a using-declaration used as a member-declaration, the
4108 // nested-name-specifier shall name a base class of the class
4109 // being defined.
4110
4111 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4112 cast<CXXRecordDecl>(NamedContext))) {
4113 if (CurContext == NamedContext) {
4114 Diag(NameLoc,
4115 diag::err_using_decl_nested_name_specifier_is_current_class)
4116 << SS.getRange();
4117 return true;
4118 }
4119
4120 Diag(SS.getRange().getBegin(),
4121 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4122 << (NestedNameSpecifier*) SS.getScopeRep()
4123 << cast<CXXRecordDecl>(CurContext)
4124 << SS.getRange();
4125 return true;
4126 }
4127
4128 return false;
4129 }
4130
4131 // C++03 [namespace.udecl]p4:
4132 // A using-declaration used as a member-declaration shall refer
4133 // to a member of a base class of the class being defined [etc.].
4134
4135 // Salient point: SS doesn't have to name a base class as long as
4136 // lookup only finds members from base classes. Therefore we can
4137 // diagnose here only if we can prove that that can't happen,
4138 // i.e. if the class hierarchies provably don't intersect.
4139
4140 // TODO: it would be nice if "definitely valid" results were cached
4141 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4142 // need to be repeated.
4143
4144 struct UserData {
4145 llvm::DenseSet<const CXXRecordDecl*> Bases;
4146
4147 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4148 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4149 Data->Bases.insert(Base);
4150 return true;
4151 }
4152
4153 bool hasDependentBases(const CXXRecordDecl *Class) {
4154 return !Class->forallBases(collect, this);
4155 }
4156
4157 /// Returns true if the base is dependent or is one of the
4158 /// accumulated base classes.
4159 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4160 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4161 return !Data->Bases.count(Base);
4162 }
4163
4164 bool mightShareBases(const CXXRecordDecl *Class) {
4165 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4166 }
4167 };
4168
4169 UserData Data;
4170
4171 // Returns false if we find a dependent base.
4172 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4173 return false;
4174
4175 // Returns false if the class has a dependent base or if it or one
4176 // of its bases is present in the base set of the current context.
4177 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4178 return false;
4179
4180 Diag(SS.getRange().getBegin(),
4181 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4182 << (NestedNameSpecifier*) SS.getScopeRep()
4183 << cast<CXXRecordDecl>(CurContext)
4184 << SS.getRange();
4185
4186 return true;
John McCallb96ec562009-12-04 22:46:56 +00004187}
4188
John McCall48871652010-08-21 09:40:31 +00004189Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004190 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004191 SourceLocation AliasLoc,
4192 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004193 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004194 SourceLocation IdentLoc,
4195 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004196
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004197 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004198 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4199 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004200
Anders Carlssondca83c42009-03-28 06:23:46 +00004201 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004202 NamedDecl *PrevDecl
4203 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4204 ForRedeclaration);
4205 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4206 PrevDecl = 0;
4207
4208 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004209 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004210 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004211 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004212 // FIXME: At some point, we'll want to create the (redundant)
4213 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004214 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004215 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004216 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004217 }
Mike Stump11289f42009-09-09 15:08:12 +00004218
Anders Carlssondca83c42009-03-28 06:23:46 +00004219 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4220 diag::err_redefinition_different_kind;
4221 Diag(AliasLoc, DiagID) << Alias;
4222 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004223 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004224 }
4225
John McCall27b18f82009-11-17 02:14:36 +00004226 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004227 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004228
John McCall9f3059a2009-10-09 21:13:30 +00004229 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004230 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4231 CTC_NoKeywords, 0)) {
4232 if (R.getAsSingle<NamespaceDecl>() ||
4233 R.getAsSingle<NamespaceAliasDecl>()) {
4234 if (DeclContext *DC = computeDeclContext(SS, false))
4235 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4236 << Ident << DC << Corrected << SS.getRange()
4237 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4238 else
4239 Diag(IdentLoc, diag::err_using_directive_suggest)
4240 << Ident << Corrected
4241 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4242
4243 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4244 << Corrected;
4245
4246 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004247 } else {
4248 R.clear();
4249 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004250 }
4251 }
4252
4253 if (R.empty()) {
4254 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004255 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004256 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004257 }
Mike Stump11289f42009-09-09 15:08:12 +00004258
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004259 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004260 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4261 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004262 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004263 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004264
John McCalld8d0d432010-02-16 06:53:13 +00004265 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004266 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004267}
4268
Douglas Gregora57478e2010-05-01 15:04:51 +00004269namespace {
4270 /// \brief Scoped object used to handle the state changes required in Sema
4271 /// to implicitly define the body of a C++ member function;
4272 class ImplicitlyDefinedFunctionScope {
4273 Sema &S;
4274 DeclContext *PreviousContext;
4275
4276 public:
4277 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4278 : S(S), PreviousContext(S.CurContext)
4279 {
4280 S.CurContext = Method;
4281 S.PushFunctionScope();
4282 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4283 }
4284
4285 ~ImplicitlyDefinedFunctionScope() {
4286 S.PopExpressionEvaluationContext();
4287 S.PopFunctionOrBlockScope();
4288 S.CurContext = PreviousContext;
4289 }
4290 };
4291}
4292
Sebastian Redlc15c3262010-09-13 22:02:47 +00004293static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4294 CXXRecordDecl *D) {
4295 ASTContext &Context = Self.Context;
4296 QualType ClassType = Context.getTypeDeclType(D);
4297 DeclarationName ConstructorName
4298 = Context.DeclarationNames.getCXXConstructorName(
4299 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4300
4301 DeclContext::lookup_const_iterator Con, ConEnd;
4302 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4303 Con != ConEnd; ++Con) {
4304 // FIXME: In C++0x, a constructor template can be a default constructor.
4305 if (isa<FunctionTemplateDecl>(*Con))
4306 continue;
4307
4308 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4309 if (Constructor->isDefaultConstructor())
4310 return Constructor;
4311 }
4312 return 0;
4313}
4314
Douglas Gregor0be31a22010-07-02 17:43:08 +00004315CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4316 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004317 // C++ [class.ctor]p5:
4318 // A default constructor for a class X is a constructor of class X
4319 // that can be called without an argument. If there is no
4320 // user-declared constructor for class X, a default constructor is
4321 // implicitly declared. An implicitly-declared default constructor
4322 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004323 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4324 "Should not build implicit default constructor!");
4325
Douglas Gregor6d880b12010-07-01 22:31:05 +00004326 // C++ [except.spec]p14:
4327 // An implicitly declared special member function (Clause 12) shall have an
4328 // exception-specification. [...]
4329 ImplicitExceptionSpecification ExceptSpec(Context);
4330
4331 // Direct base-class destructors.
4332 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4333 BEnd = ClassDecl->bases_end();
4334 B != BEnd; ++B) {
4335 if (B->isVirtual()) // Handled below.
4336 continue;
4337
Douglas Gregor9672f922010-07-03 00:47:00 +00004338 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4339 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4340 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4341 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004342 else if (CXXConstructorDecl *Constructor
4343 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004344 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004345 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004346 }
4347
4348 // Virtual base-class destructors.
4349 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4350 BEnd = ClassDecl->vbases_end();
4351 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004352 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4354 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4355 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4356 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004357 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004358 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004359 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004360 }
4361
4362 // Field destructors.
4363 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4364 FEnd = ClassDecl->field_end();
4365 F != FEnd; ++F) {
4366 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004367 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4368 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4369 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4370 ExceptSpec.CalledDecl(
4371 DeclareImplicitDefaultConstructor(FieldClassDecl));
4372 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004373 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004374 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004375 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004376 }
John McCalldb40c7f2010-12-14 08:05:40 +00004377
4378 FunctionProtoType::ExtProtoInfo EPI;
4379 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4380 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4381 EPI.NumExceptions = ExceptSpec.size();
4382 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004383
4384 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004385 CanQualType ClassType
4386 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4387 DeclarationName Name
4388 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004389 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004390 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004391 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004392 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004393 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004394 /*TInfo=*/0,
4395 /*isExplicit=*/false,
4396 /*isInline=*/true,
4397 /*isImplicitlyDeclared=*/true);
4398 DefaultCon->setAccess(AS_public);
4399 DefaultCon->setImplicit();
4400 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004401
4402 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004403 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4404
Douglas Gregor0be31a22010-07-02 17:43:08 +00004405 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004406 PushOnScopeChains(DefaultCon, S, false);
4407 ClassDecl->addDecl(DefaultCon);
4408
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004409 return DefaultCon;
4410}
4411
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004412void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4413 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004414 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004415 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004416 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004417
Anders Carlsson423f5d82010-04-23 16:04:08 +00004418 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004419 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004420
Douglas Gregora57478e2010-05-01 15:04:51 +00004421 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004422 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor54818f02010-05-12 16:39:35 +00004423 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4424 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004425 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004426 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004427 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004428 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004429 }
Douglas Gregor73193272010-09-20 16:48:21 +00004430
4431 SourceLocation Loc = Constructor->getLocation();
4432 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4433
4434 Constructor->setUsed();
4435 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004436}
4437
Douglas Gregor0be31a22010-07-02 17:43:08 +00004438CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004439 // C++ [class.dtor]p2:
4440 // If a class has no user-declared destructor, a destructor is
4441 // declared implicitly. An implicitly-declared destructor is an
4442 // inline public member of its class.
4443
4444 // C++ [except.spec]p14:
4445 // An implicitly declared special member function (Clause 12) shall have
4446 // an exception-specification.
4447 ImplicitExceptionSpecification ExceptSpec(Context);
4448
4449 // Direct base-class destructors.
4450 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4451 BEnd = ClassDecl->bases_end();
4452 B != BEnd; ++B) {
4453 if (B->isVirtual()) // Handled below.
4454 continue;
4455
4456 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4457 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004458 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004459 }
4460
4461 // Virtual base-class destructors.
4462 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4463 BEnd = ClassDecl->vbases_end();
4464 B != BEnd; ++B) {
4465 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4466 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004467 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004468 }
4469
4470 // Field destructors.
4471 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4472 FEnd = ClassDecl->field_end();
4473 F != FEnd; ++F) {
4474 if (const RecordType *RecordTy
4475 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4476 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004477 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004478 }
4479
Douglas Gregor7454c562010-07-02 20:37:36 +00004480 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004481 FunctionProtoType::ExtProtoInfo EPI;
4482 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4483 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4484 EPI.NumExceptions = ExceptSpec.size();
4485 EPI.Exceptions = ExceptSpec.data();
4486 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004487
4488 CanQualType ClassType
4489 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4490 DeclarationName Name
4491 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004492 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004493 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004494 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004495 /*isInline=*/true,
4496 /*isImplicitlyDeclared=*/true);
4497 Destructor->setAccess(AS_public);
4498 Destructor->setImplicit();
4499 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004500
4501 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004502 ++ASTContext::NumImplicitDestructorsDeclared;
4503
4504 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004505 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004506 PushOnScopeChains(Destructor, S, false);
4507 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004508
4509 // This could be uniqued if it ever proves significant.
4510 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4511
4512 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004513
Douglas Gregorf1203042010-07-01 19:09:28 +00004514 return Destructor;
4515}
4516
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004517void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004518 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004519 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004520 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004521 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004522 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004523
Douglas Gregor54818f02010-05-12 16:39:35 +00004524 if (Destructor->isInvalidDecl())
4525 return;
4526
Douglas Gregora57478e2010-05-01 15:04:51 +00004527 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004528
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004529 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004530 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4531 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004532
Douglas Gregor54818f02010-05-12 16:39:35 +00004533 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004534 Diag(CurrentLocation, diag::note_member_synthesized_at)
4535 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4536
4537 Destructor->setInvalidDecl();
4538 return;
4539 }
4540
Douglas Gregor73193272010-09-20 16:48:21 +00004541 SourceLocation Loc = Destructor->getLocation();
4542 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4543
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004544 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004545 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004546}
4547
Douglas Gregorb139cd52010-05-01 20:49:11 +00004548/// \brief Builds a statement that copies the given entity from \p From to
4549/// \c To.
4550///
4551/// This routine is used to copy the members of a class with an
4552/// implicitly-declared copy assignment operator. When the entities being
4553/// copied are arrays, this routine builds for loops to copy them.
4554///
4555/// \param S The Sema object used for type-checking.
4556///
4557/// \param Loc The location where the implicit copy is being generated.
4558///
4559/// \param T The type of the expressions being copied. Both expressions must
4560/// have this type.
4561///
4562/// \param To The expression we are copying to.
4563///
4564/// \param From The expression we are copying from.
4565///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004566/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4567/// Otherwise, it's a non-static member subobject.
4568///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004569/// \param Depth Internal parameter recording the depth of the recursion.
4570///
4571/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004572static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004573BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004574 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004575 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004576 // C++0x [class.copy]p30:
4577 // Each subobject is assigned in the manner appropriate to its type:
4578 //
4579 // - if the subobject is of class type, the copy assignment operator
4580 // for the class is used (as if by explicit qualification; that is,
4581 // ignoring any possible virtual overriding functions in more derived
4582 // classes);
4583 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4584 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4585
4586 // Look for operator=.
4587 DeclarationName Name
4588 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4589 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4590 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4591
4592 // Filter out any result that isn't a copy-assignment operator.
4593 LookupResult::Filter F = OpLookup.makeFilter();
4594 while (F.hasNext()) {
4595 NamedDecl *D = F.next();
4596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4597 if (Method->isCopyAssignmentOperator())
4598 continue;
4599
4600 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004601 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004602 F.done();
4603
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004604 // Suppress the protected check (C++ [class.protected]) for each of the
4605 // assignment operators we found. This strange dance is required when
4606 // we're assigning via a base classes's copy-assignment operator. To
4607 // ensure that we're getting the right base class subobject (without
4608 // ambiguities), we need to cast "this" to that subobject type; to
4609 // ensure that we don't go through the virtual call mechanism, we need
4610 // to qualify the operator= name with the base class (see below). However,
4611 // this means that if the base class has a protected copy assignment
4612 // operator, the protected member access check will fail. So, we
4613 // rewrite "protected" access to "public" access in this case, since we
4614 // know by construction that we're calling from a derived class.
4615 if (CopyingBaseSubobject) {
4616 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4617 L != LEnd; ++L) {
4618 if (L.getAccess() == AS_protected)
4619 L.setAccess(AS_public);
4620 }
4621 }
4622
Douglas Gregorb139cd52010-05-01 20:49:11 +00004623 // Create the nested-name-specifier that will be used to qualify the
4624 // reference to operator=; this is required to suppress the virtual
4625 // call mechanism.
4626 CXXScopeSpec SS;
4627 SS.setRange(Loc);
4628 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4629 T.getTypePtr()));
4630
4631 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004632 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004633 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004634 /*FirstQualifierInScope=*/0, OpLookup,
4635 /*TemplateArgs=*/0,
4636 /*SuppressQualifierCheck=*/true);
4637 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004638 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004639
4640 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004641
John McCalldadc5752010-08-24 06:29:42 +00004642 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004643 OpEqualRef.takeAs<Expr>(),
4644 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004645 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004646 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004647
4648 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004649 }
John McCallab8c2732010-03-16 06:11:48 +00004650
Douglas Gregorb139cd52010-05-01 20:49:11 +00004651 // - if the subobject is of scalar type, the built-in assignment
4652 // operator is used.
4653 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4654 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004655 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004656 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004657 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004658
4659 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004660 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004661
4662 // - if the subobject is an array, each element is assigned, in the
4663 // manner appropriate to the element type;
4664
4665 // Construct a loop over the array bounds, e.g.,
4666 //
4667 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4668 //
4669 // that will copy each of the array elements.
4670 QualType SizeType = S.Context.getSizeType();
4671
4672 // Create the iteration variable.
4673 IdentifierInfo *IterationVarName = 0;
4674 {
4675 llvm::SmallString<8> Str;
4676 llvm::raw_svector_ostream OS(Str);
4677 OS << "__i" << Depth;
4678 IterationVarName = &S.Context.Idents.get(OS.str());
4679 }
4680 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4681 IterationVarName, SizeType,
4682 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004683 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004684
4685 // Initialize the iteration variable to zero.
4686 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004687 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004688
4689 // Create a reference to the iteration variable; we'll use this several
4690 // times throughout.
4691 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004692 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004693 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4694
4695 // Create the DeclStmt that holds the iteration variable.
4696 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4697
4698 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004699 llvm::APInt Upper
4700 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004701 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004702 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004703 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4704 BO_NE, S.Context.BoolTy,
4705 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004706
4707 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004708 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004709 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4710 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004711
4712 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004713 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4714 IterationVarRef, Loc));
4715 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4716 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004717
4718 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004719 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4720 To, From, CopyingBaseSubobject,
4721 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004722 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004723 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004724
4725 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004726 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004727 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004728 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004729 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004730}
4731
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004732/// \brief Determine whether the given class has a copy assignment operator
4733/// that accepts a const-qualified argument.
4734static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4735 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4736
4737 if (!Class->hasDeclaredCopyAssignment())
4738 S.DeclareImplicitCopyAssignment(Class);
4739
4740 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4741 DeclarationName OpName
4742 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4743
4744 DeclContext::lookup_const_iterator Op, OpEnd;
4745 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4746 // C++ [class.copy]p9:
4747 // A user-declared copy assignment operator is a non-static non-template
4748 // member function of class X with exactly one parameter of type X, X&,
4749 // const X&, volatile X& or const volatile X&.
4750 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4751 if (!Method)
4752 continue;
4753
4754 if (Method->isStatic())
4755 continue;
4756 if (Method->getPrimaryTemplate())
4757 continue;
4758 const FunctionProtoType *FnType =
4759 Method->getType()->getAs<FunctionProtoType>();
4760 assert(FnType && "Overloaded operator has no prototype.");
4761 // Don't assert on this; an invalid decl might have been left in the AST.
4762 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4763 continue;
4764 bool AcceptsConst = true;
4765 QualType ArgType = FnType->getArgType(0);
4766 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4767 ArgType = Ref->getPointeeType();
4768 // Is it a non-const lvalue reference?
4769 if (!ArgType.isConstQualified())
4770 AcceptsConst = false;
4771 }
4772 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4773 continue;
4774
4775 // We have a single argument of type cv X or cv X&, i.e. we've found the
4776 // copy assignment operator. Return whether it accepts const arguments.
4777 return AcceptsConst;
4778 }
4779 assert(Class->isInvalidDecl() &&
4780 "No copy assignment operator declared in valid code.");
4781 return false;
4782}
4783
Douglas Gregor0be31a22010-07-02 17:43:08 +00004784CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004785 // Note: The following rules are largely analoguous to the copy
4786 // constructor rules. Note that virtual bases are not taken into account
4787 // for determining the argument type of the operator. Note also that
4788 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004789
4790
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004791 // C++ [class.copy]p10:
4792 // If the class definition does not explicitly declare a copy
4793 // assignment operator, one is declared implicitly.
4794 // The implicitly-defined copy assignment operator for a class X
4795 // will have the form
4796 //
4797 // X& X::operator=(const X&)
4798 //
4799 // if
4800 bool HasConstCopyAssignment = true;
4801
4802 // -- each direct base class B of X has a copy assignment operator
4803 // whose parameter is of type const B&, const volatile B& or B,
4804 // and
4805 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4806 BaseEnd = ClassDecl->bases_end();
4807 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4808 assert(!Base->getType()->isDependentType() &&
4809 "Cannot generate implicit members for class with dependent bases.");
4810 const CXXRecordDecl *BaseClassDecl
4811 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004812 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004813 }
4814
4815 // -- for all the nonstatic data members of X that are of a class
4816 // type M (or array thereof), each such class type has a copy
4817 // assignment operator whose parameter is of type const M&,
4818 // const volatile M& or M.
4819 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4820 FieldEnd = ClassDecl->field_end();
4821 HasConstCopyAssignment && Field != FieldEnd;
4822 ++Field) {
4823 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4824 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4825 const CXXRecordDecl *FieldClassDecl
4826 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004827 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004828 }
4829 }
4830
4831 // Otherwise, the implicitly declared copy assignment operator will
4832 // have the form
4833 //
4834 // X& X::operator=(X&)
4835 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4836 QualType RetType = Context.getLValueReferenceType(ArgType);
4837 if (HasConstCopyAssignment)
4838 ArgType = ArgType.withConst();
4839 ArgType = Context.getLValueReferenceType(ArgType);
4840
Douglas Gregor68e11362010-07-01 17:48:08 +00004841 // C++ [except.spec]p14:
4842 // An implicitly declared special member function (Clause 12) shall have an
4843 // exception-specification. [...]
4844 ImplicitExceptionSpecification ExceptSpec(Context);
4845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4846 BaseEnd = ClassDecl->bases_end();
4847 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004848 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004849 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004850
4851 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4852 DeclareImplicitCopyAssignment(BaseClassDecl);
4853
Douglas Gregor68e11362010-07-01 17:48:08 +00004854 if (CXXMethodDecl *CopyAssign
4855 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4856 ExceptSpec.CalledDecl(CopyAssign);
4857 }
4858 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4859 FieldEnd = ClassDecl->field_end();
4860 Field != FieldEnd;
4861 ++Field) {
4862 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4863 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004864 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004865 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004866
4867 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4868 DeclareImplicitCopyAssignment(FieldClassDecl);
4869
Douglas Gregor68e11362010-07-01 17:48:08 +00004870 if (CXXMethodDecl *CopyAssign
4871 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4872 ExceptSpec.CalledDecl(CopyAssign);
4873 }
4874 }
4875
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004876 // An implicitly-declared copy assignment operator is an inline public
4877 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004878 FunctionProtoType::ExtProtoInfo EPI;
4879 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4880 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4881 EPI.NumExceptions = ExceptSpec.size();
4882 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004883 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004884 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004885 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004886 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004887 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004888 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004889 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004890 /*isInline=*/true);
4891 CopyAssignment->setAccess(AS_public);
4892 CopyAssignment->setImplicit();
4893 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004894
4895 // Add the parameter to the operator.
4896 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4897 ClassDecl->getLocation(),
4898 /*Id=*/0,
4899 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004900 SC_None,
4901 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004902 CopyAssignment->setParams(&FromParam, 1);
4903
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004904 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004905 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4906
Douglas Gregor0be31a22010-07-02 17:43:08 +00004907 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004908 PushOnScopeChains(CopyAssignment, S, false);
4909 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004910
4911 AddOverriddenMethods(ClassDecl, CopyAssignment);
4912 return CopyAssignment;
4913}
4914
Douglas Gregorb139cd52010-05-01 20:49:11 +00004915void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4916 CXXMethodDecl *CopyAssignOperator) {
4917 assert((CopyAssignOperator->isImplicit() &&
4918 CopyAssignOperator->isOverloadedOperator() &&
4919 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004920 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004921 "DefineImplicitCopyAssignment called for wrong function");
4922
4923 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4924
4925 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4926 CopyAssignOperator->setInvalidDecl();
4927 return;
4928 }
4929
4930 CopyAssignOperator->setUsed();
4931
4932 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004933 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004934
4935 // C++0x [class.copy]p30:
4936 // The implicitly-defined or explicitly-defaulted copy assignment operator
4937 // for a non-union class X performs memberwise copy assignment of its
4938 // subobjects. The direct base classes of X are assigned first, in the
4939 // order of their declaration in the base-specifier-list, and then the
4940 // immediate non-static data members of X are assigned, in the order in
4941 // which they were declared in the class definition.
4942
4943 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004944 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004945
4946 // The parameter for the "other" object, which we are copying from.
4947 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4948 Qualifiers OtherQuals = Other->getType().getQualifiers();
4949 QualType OtherRefType = Other->getType();
4950 if (const LValueReferenceType *OtherRef
4951 = OtherRefType->getAs<LValueReferenceType>()) {
4952 OtherRefType = OtherRef->getPointeeType();
4953 OtherQuals = OtherRefType.getQualifiers();
4954 }
4955
4956 // Our location for everything implicitly-generated.
4957 SourceLocation Loc = CopyAssignOperator->getLocation();
4958
4959 // Construct a reference to the "other" object. We'll be using this
4960 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00004961 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004962 assert(OtherRef && "Reference to parameter cannot fail!");
4963
4964 // Construct the "this" pointer. We'll be using this throughout the generated
4965 // ASTs.
4966 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4967 assert(This && "Reference to this cannot fail!");
4968
4969 // Assign base classes.
4970 bool Invalid = false;
4971 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4972 E = ClassDecl->bases_end(); Base != E; ++Base) {
4973 // Form the assignment:
4974 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4975 QualType BaseType = Base->getType().getUnqualifiedType();
4976 CXXRecordDecl *BaseClassDecl = 0;
4977 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4978 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4979 else {
4980 Invalid = true;
4981 continue;
4982 }
4983
John McCallcf142162010-08-07 06:22:56 +00004984 CXXCastPath BasePath;
4985 BasePath.push_back(Base);
4986
Douglas Gregorb139cd52010-05-01 20:49:11 +00004987 // Construct the "from" expression, which is an implicit cast to the
4988 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00004989 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004990 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004991 CK_UncheckedDerivedToBase,
4992 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004993
4994 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004995 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004996
4997 // Implicitly cast "this" to the appropriately-qualified base type.
4998 Expr *ToE = To.takeAs<Expr>();
4999 ImpCastExprToType(ToE,
5000 Context.getCVRQualifiedType(BaseType,
5001 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005002 CK_UncheckedDerivedToBase,
5003 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005004 To = Owned(ToE);
5005
5006 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005007 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005008 To.get(), From,
5009 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005010 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005011 Diag(CurrentLocation, diag::note_member_synthesized_at)
5012 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5013 CopyAssignOperator->setInvalidDecl();
5014 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005015 }
5016
5017 // Success! Record the copy.
5018 Statements.push_back(Copy.takeAs<Expr>());
5019 }
5020
5021 // \brief Reference to the __builtin_memcpy function.
5022 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005023 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005024 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005025
5026 // Assign non-static members.
5027 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5028 FieldEnd = ClassDecl->field_end();
5029 Field != FieldEnd; ++Field) {
5030 // Check for members of reference type; we can't copy those.
5031 if (Field->getType()->isReferenceType()) {
5032 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5033 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5034 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005035 Diag(CurrentLocation, diag::note_member_synthesized_at)
5036 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005037 Invalid = true;
5038 continue;
5039 }
5040
5041 // Check for members of const-qualified, non-class type.
5042 QualType BaseType = Context.getBaseElementType(Field->getType());
5043 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5044 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5045 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5046 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005047 Diag(CurrentLocation, diag::note_member_synthesized_at)
5048 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005049 Invalid = true;
5050 continue;
5051 }
5052
5053 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005054 if (FieldType->isIncompleteArrayType()) {
5055 assert(ClassDecl->hasFlexibleArrayMember() &&
5056 "Incomplete array type is not valid");
5057 continue;
5058 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005059
5060 // Build references to the field in the object we're copying from and to.
5061 CXXScopeSpec SS; // Intentionally empty
5062 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5063 LookupMemberName);
5064 MemberLookup.addDecl(*Field);
5065 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005066 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005067 Loc, /*IsArrow=*/false,
5068 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005069 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005070 Loc, /*IsArrow=*/true,
5071 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005072 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5073 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5074
5075 // If the field should be copied with __builtin_memcpy rather than via
5076 // explicit assignments, do so. This optimization only applies for arrays
5077 // of scalars and arrays of class type with trivial copy-assignment
5078 // operators.
5079 if (FieldType->isArrayType() &&
5080 (!BaseType->isRecordType() ||
5081 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5082 ->hasTrivialCopyAssignment())) {
5083 // Compute the size of the memory buffer to be copied.
5084 QualType SizeType = Context.getSizeType();
5085 llvm::APInt Size(Context.getTypeSize(SizeType),
5086 Context.getTypeSizeInChars(BaseType).getQuantity());
5087 for (const ConstantArrayType *Array
5088 = Context.getAsConstantArrayType(FieldType);
5089 Array;
5090 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005091 llvm::APInt ArraySize
5092 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005093 Size *= ArraySize;
5094 }
5095
5096 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005097 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5098 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005099
5100 bool NeedsCollectableMemCpy =
5101 (BaseType->isRecordType() &&
5102 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5103
5104 if (NeedsCollectableMemCpy) {
5105 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005106 // Create a reference to the __builtin_objc_memmove_collectable function.
5107 LookupResult R(*this,
5108 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005109 Loc, LookupOrdinaryName);
5110 LookupName(R, TUScope, true);
5111
5112 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5113 if (!CollectableMemCpy) {
5114 // Something went horribly wrong earlier, and we will have
5115 // complained about it.
5116 Invalid = true;
5117 continue;
5118 }
5119
5120 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5121 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005122 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005123 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5124 }
5125 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005126 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005127 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005128 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5129 LookupOrdinaryName);
5130 LookupName(R, TUScope, true);
5131
5132 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5133 if (!BuiltinMemCpy) {
5134 // Something went horribly wrong earlier, and we will have complained
5135 // about it.
5136 Invalid = true;
5137 continue;
5138 }
5139
5140 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5141 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005142 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005143 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5144 }
5145
John McCall37ad5512010-08-23 06:44:23 +00005146 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005147 CallArgs.push_back(To.takeAs<Expr>());
5148 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005149 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005150 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005151 if (NeedsCollectableMemCpy)
5152 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005153 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005154 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005155 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005156 else
5157 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005158 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005159 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005160 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005161
Douglas Gregorb139cd52010-05-01 20:49:11 +00005162 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5163 Statements.push_back(Call.takeAs<Expr>());
5164 continue;
5165 }
5166
5167 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005168 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005169 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005170 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005171 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005172 Diag(CurrentLocation, diag::note_member_synthesized_at)
5173 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5174 CopyAssignOperator->setInvalidDecl();
5175 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005176 }
5177
5178 // Success! Record the copy.
5179 Statements.push_back(Copy.takeAs<Stmt>());
5180 }
5181
5182 if (!Invalid) {
5183 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005184 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005185
John McCalldadc5752010-08-24 06:29:42 +00005186 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005187 if (Return.isInvalid())
5188 Invalid = true;
5189 else {
5190 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005191
5192 if (Trap.hasErrorOccurred()) {
5193 Diag(CurrentLocation, diag::note_member_synthesized_at)
5194 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5195 Invalid = true;
5196 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005197 }
5198 }
5199
5200 if (Invalid) {
5201 CopyAssignOperator->setInvalidDecl();
5202 return;
5203 }
5204
John McCalldadc5752010-08-24 06:29:42 +00005205 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005206 /*isStmtExpr=*/false);
5207 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5208 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005209}
5210
Douglas Gregor0be31a22010-07-02 17:43:08 +00005211CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5212 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005213 // C++ [class.copy]p4:
5214 // If the class definition does not explicitly declare a copy
5215 // constructor, one is declared implicitly.
5216
Douglas Gregor54be3392010-07-01 17:57:27 +00005217 // C++ [class.copy]p5:
5218 // The implicitly-declared copy constructor for a class X will
5219 // have the form
5220 //
5221 // X::X(const X&)
5222 //
5223 // if
5224 bool HasConstCopyConstructor = true;
5225
5226 // -- each direct or virtual base class B of X has a copy
5227 // constructor whose first parameter is of type const B& or
5228 // const volatile B&, and
5229 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5230 BaseEnd = ClassDecl->bases_end();
5231 HasConstCopyConstructor && Base != BaseEnd;
5232 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005233 // Virtual bases are handled below.
5234 if (Base->isVirtual())
5235 continue;
5236
Douglas Gregora6d69502010-07-02 23:41:54 +00005237 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005238 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005239 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5240 DeclareImplicitCopyConstructor(BaseClassDecl);
5241
Douglas Gregorcfe68222010-07-01 18:27:03 +00005242 HasConstCopyConstructor
5243 = BaseClassDecl->hasConstCopyConstructor(Context);
5244 }
5245
5246 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5247 BaseEnd = ClassDecl->vbases_end();
5248 HasConstCopyConstructor && Base != BaseEnd;
5249 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005250 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005251 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005252 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5253 DeclareImplicitCopyConstructor(BaseClassDecl);
5254
Douglas Gregor54be3392010-07-01 17:57:27 +00005255 HasConstCopyConstructor
5256 = BaseClassDecl->hasConstCopyConstructor(Context);
5257 }
5258
5259 // -- for all the nonstatic data members of X that are of a
5260 // class type M (or array thereof), each such class type
5261 // has a copy constructor whose first parameter is of type
5262 // const M& or const volatile M&.
5263 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5264 FieldEnd = ClassDecl->field_end();
5265 HasConstCopyConstructor && Field != FieldEnd;
5266 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005267 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005268 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005269 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005270 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005271 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5272 DeclareImplicitCopyConstructor(FieldClassDecl);
5273
Douglas Gregor54be3392010-07-01 17:57:27 +00005274 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005275 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005276 }
5277 }
5278
5279 // Otherwise, the implicitly declared copy constructor will have
5280 // the form
5281 //
5282 // X::X(X&)
5283 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5284 QualType ArgType = ClassType;
5285 if (HasConstCopyConstructor)
5286 ArgType = ArgType.withConst();
5287 ArgType = Context.getLValueReferenceType(ArgType);
5288
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005289 // C++ [except.spec]p14:
5290 // An implicitly declared special member function (Clause 12) shall have an
5291 // exception-specification. [...]
5292 ImplicitExceptionSpecification ExceptSpec(Context);
5293 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5294 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5295 BaseEnd = ClassDecl->bases_end();
5296 Base != BaseEnd;
5297 ++Base) {
5298 // Virtual bases are handled below.
5299 if (Base->isVirtual())
5300 continue;
5301
Douglas Gregora6d69502010-07-02 23:41:54 +00005302 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005303 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005304 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5305 DeclareImplicitCopyConstructor(BaseClassDecl);
5306
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005307 if (CXXConstructorDecl *CopyConstructor
5308 = BaseClassDecl->getCopyConstructor(Context, Quals))
5309 ExceptSpec.CalledDecl(CopyConstructor);
5310 }
5311 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5312 BaseEnd = ClassDecl->vbases_end();
5313 Base != BaseEnd;
5314 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005315 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005316 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005317 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5318 DeclareImplicitCopyConstructor(BaseClassDecl);
5319
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005320 if (CXXConstructorDecl *CopyConstructor
5321 = BaseClassDecl->getCopyConstructor(Context, Quals))
5322 ExceptSpec.CalledDecl(CopyConstructor);
5323 }
5324 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5325 FieldEnd = ClassDecl->field_end();
5326 Field != FieldEnd;
5327 ++Field) {
5328 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5329 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005330 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005331 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005332 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5333 DeclareImplicitCopyConstructor(FieldClassDecl);
5334
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005335 if (CXXConstructorDecl *CopyConstructor
5336 = FieldClassDecl->getCopyConstructor(Context, Quals))
5337 ExceptSpec.CalledDecl(CopyConstructor);
5338 }
5339 }
5340
Douglas Gregor54be3392010-07-01 17:57:27 +00005341 // An implicitly-declared copy constructor is an inline public
5342 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005343 FunctionProtoType::ExtProtoInfo EPI;
5344 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5345 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5346 EPI.NumExceptions = ExceptSpec.size();
5347 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005348 DeclarationName Name
5349 = Context.DeclarationNames.getCXXConstructorName(
5350 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005351 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005352 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005353 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005354 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005355 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005356 /*TInfo=*/0,
5357 /*isExplicit=*/false,
5358 /*isInline=*/true,
5359 /*isImplicitlyDeclared=*/true);
5360 CopyConstructor->setAccess(AS_public);
5361 CopyConstructor->setImplicit();
5362 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5363
Douglas Gregora6d69502010-07-02 23:41:54 +00005364 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005365 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5366
Douglas Gregor54be3392010-07-01 17:57:27 +00005367 // Add the parameter to the constructor.
5368 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5369 ClassDecl->getLocation(),
5370 /*IdentifierInfo=*/0,
5371 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005372 SC_None,
5373 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005374 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005375 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005376 PushOnScopeChains(CopyConstructor, S, false);
5377 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005378
5379 return CopyConstructor;
5380}
5381
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005382void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5383 CXXConstructorDecl *CopyConstructor,
5384 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005385 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005386 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005387 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005388 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005389
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005390 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005391 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005392
Douglas Gregora57478e2010-05-01 15:04:51 +00005393 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005394 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005395
Douglas Gregor54818f02010-05-12 16:39:35 +00005396 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5397 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005398 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005399 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005400 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005401 } else {
5402 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5403 CopyConstructor->getLocation(),
5404 MultiStmtArg(*this, 0, 0),
5405 /*isStmtExpr=*/false)
5406 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005407 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005408
5409 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005410}
5411
John McCalldadc5752010-08-24 06:29:42 +00005412ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005413Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005414 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005415 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005416 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005417 unsigned ConstructKind,
5418 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005419 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005420
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005421 // C++0x [class.copy]p34:
5422 // When certain criteria are met, an implementation is allowed to
5423 // omit the copy/move construction of a class object, even if the
5424 // copy/move constructor and/or destructor for the object have
5425 // side effects. [...]
5426 // - when a temporary class object that has not been bound to a
5427 // reference (12.2) would be copied/moved to a class object
5428 // with the same cv-unqualified type, the copy/move operation
5429 // can be omitted by constructing the temporary object
5430 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005431 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5432 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005433 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005434 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005435 }
Mike Stump11289f42009-09-09 15:08:12 +00005436
5437 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005438 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005439 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005440}
5441
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005442/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5443/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005444ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005445Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5446 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005447 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005448 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005449 unsigned ConstructKind,
5450 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005451 unsigned NumExprs = ExprArgs.size();
5452 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005453
Douglas Gregor27381f32009-11-23 12:27:39 +00005454 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005455 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005456 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005457 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005458 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5459 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005460}
5461
Mike Stump11289f42009-09-09 15:08:12 +00005462bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005463 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005464 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005465 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005466 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005467 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005468 move(Exprs), false, CXXConstructExpr::CK_Complete,
5469 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005470 if (TempResult.isInvalid())
5471 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005472
Anders Carlsson6eb55572009-08-25 05:12:04 +00005473 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005474 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005475 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005476 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005477 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005478
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005479 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005480}
5481
John McCall03c48482010-02-02 09:10:11 +00005482void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5483 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005484 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005485 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005486 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005487 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005488 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005489 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005490 << VD->getDeclName()
5491 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005492
John McCall386dfc72010-09-18 05:25:11 +00005493 // TODO: this should be re-enabled for static locals by !CXAAtExit
5494 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005495 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005496 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005497}
5498
Mike Stump11289f42009-09-09 15:08:12 +00005499/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005500/// ActOnDeclarator, when a C++ direct initializer is present.
5501/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005502void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005503 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005504 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005505 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005506 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005507
5508 // If there is no declaration, there was an error parsing it. Just ignore
5509 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005510 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005511 return;
Mike Stump11289f42009-09-09 15:08:12 +00005512
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005513 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5514 if (!VDecl) {
5515 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5516 RealDecl->setInvalidDecl();
5517 return;
5518 }
5519
Douglas Gregor402250f2009-08-26 21:14:46 +00005520 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005521 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005522 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5523 //
5524 // Clients that want to distinguish between the two forms, can check for
5525 // direct initializer using VarDecl::hasCXXDirectInitializer().
5526 // A major benefit is that clients that don't particularly care about which
5527 // exactly form was it (like the CodeGen) can handle both cases without
5528 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005529
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005530 // C++ 8.5p11:
5531 // The form of initialization (using parentheses or '=') is generally
5532 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005533 // class type.
5534
Douglas Gregor50dc2192010-02-11 22:55:30 +00005535 if (!VDecl->getType()->isDependentType() &&
5536 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005537 diag::err_typecheck_decl_incomplete_type)) {
5538 VDecl->setInvalidDecl();
5539 return;
5540 }
5541
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005542 // The variable can not have an abstract class type.
5543 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5544 diag::err_abstract_type_in_decl,
5545 AbstractVariableType))
5546 VDecl->setInvalidDecl();
5547
Sebastian Redl5ca79842010-02-01 20:16:42 +00005548 const VarDecl *Def;
5549 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005550 Diag(VDecl->getLocation(), diag::err_redefinition)
5551 << VDecl->getDeclName();
5552 Diag(Def->getLocation(), diag::note_previous_definition);
5553 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005554 return;
5555 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005556
Douglas Gregorf0f83692010-08-24 05:27:49 +00005557 // C++ [class.static.data]p4
5558 // If a static data member is of const integral or const
5559 // enumeration type, its declaration in the class definition can
5560 // specify a constant-initializer which shall be an integral
5561 // constant expression (5.19). In that case, the member can appear
5562 // in integral constant expressions. The member shall still be
5563 // defined in a namespace scope if it is used in the program and the
5564 // namespace scope definition shall not contain an initializer.
5565 //
5566 // We already performed a redefinition check above, but for static
5567 // data members we also need to check whether there was an in-class
5568 // declaration with an initializer.
5569 const VarDecl* PrevInit = 0;
5570 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5571 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5572 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5573 return;
5574 }
5575
Douglas Gregor71f39c92010-12-16 01:31:22 +00005576 bool IsDependent = false;
5577 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5578 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5579 VDecl->setInvalidDecl();
5580 return;
5581 }
5582
5583 if (Exprs.get()[I]->isTypeDependent())
5584 IsDependent = true;
5585 }
5586
Douglas Gregor50dc2192010-02-11 22:55:30 +00005587 // If either the declaration has a dependent type or if any of the
5588 // expressions is type-dependent, we represent the initialization
5589 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005590 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005591 // Let clients know that initialization was done with a direct initializer.
5592 VDecl->setCXXDirectInitializer(true);
5593
5594 // Store the initialization expressions as a ParenListExpr.
5595 unsigned NumExprs = Exprs.size();
5596 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5597 (Expr **)Exprs.release(),
5598 NumExprs, RParenLoc));
5599 return;
5600 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005601
5602 // Capture the variable that is being initialized and the style of
5603 // initialization.
5604 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5605
5606 // FIXME: Poor source location information.
5607 InitializationKind Kind
5608 = InitializationKind::CreateDirect(VDecl->getLocation(),
5609 LParenLoc, RParenLoc);
5610
5611 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005612 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005613 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005614 if (Result.isInvalid()) {
5615 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005616 return;
5617 }
John McCallacf0ee52010-10-08 02:01:28 +00005618
5619 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005620
Douglas Gregora40433a2010-12-07 00:41:46 +00005621 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005622 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005623 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005624
John McCall8b0f4ff2010-08-02 21:13:48 +00005625 if (!VDecl->isInvalidDecl() &&
5626 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005627 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005628 !VDecl->getInit()->isConstantInitializer(Context,
5629 VDecl->getType()->isReferenceType()))
5630 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5631 << VDecl->getInit()->getSourceRange();
5632
John McCall03c48482010-02-02 09:10:11 +00005633 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5634 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005635}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005636
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005637/// \brief Given a constructor and the set of arguments provided for the
5638/// constructor, convert the arguments and add any required default arguments
5639/// to form a proper call to this constructor.
5640///
5641/// \returns true if an error occurred, false otherwise.
5642bool
5643Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5644 MultiExprArg ArgsPtr,
5645 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005646 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005647 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5648 unsigned NumArgs = ArgsPtr.size();
5649 Expr **Args = (Expr **)ArgsPtr.get();
5650
5651 const FunctionProtoType *Proto
5652 = Constructor->getType()->getAs<FunctionProtoType>();
5653 assert(Proto && "Constructor without a prototype?");
5654 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005655
5656 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005657 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005658 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005659 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005660 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005661
5662 VariadicCallType CallType =
5663 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5664 llvm::SmallVector<Expr *, 8> AllArgs;
5665 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5666 Proto, 0, Args, NumArgs, AllArgs,
5667 CallType);
5668 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5669 ConvertedArgs.push_back(AllArgs[i]);
5670 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005671}
5672
Anders Carlssone363c8e2009-12-12 00:32:00 +00005673static inline bool
5674CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5675 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005676 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005677 if (isa<NamespaceDecl>(DC)) {
5678 return SemaRef.Diag(FnDecl->getLocation(),
5679 diag::err_operator_new_delete_declared_in_namespace)
5680 << FnDecl->getDeclName();
5681 }
5682
5683 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005684 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005685 return SemaRef.Diag(FnDecl->getLocation(),
5686 diag::err_operator_new_delete_declared_static)
5687 << FnDecl->getDeclName();
5688 }
5689
Anders Carlsson60659a82009-12-12 02:43:16 +00005690 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005691}
5692
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005693static inline bool
5694CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5695 CanQualType ExpectedResultType,
5696 CanQualType ExpectedFirstParamType,
5697 unsigned DependentParamTypeDiag,
5698 unsigned InvalidParamTypeDiag) {
5699 QualType ResultType =
5700 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5701
5702 // Check that the result type is not dependent.
5703 if (ResultType->isDependentType())
5704 return SemaRef.Diag(FnDecl->getLocation(),
5705 diag::err_operator_new_delete_dependent_result_type)
5706 << FnDecl->getDeclName() << ExpectedResultType;
5707
5708 // Check that the result type is what we expect.
5709 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5710 return SemaRef.Diag(FnDecl->getLocation(),
5711 diag::err_operator_new_delete_invalid_result_type)
5712 << FnDecl->getDeclName() << ExpectedResultType;
5713
5714 // A function template must have at least 2 parameters.
5715 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5716 return SemaRef.Diag(FnDecl->getLocation(),
5717 diag::err_operator_new_delete_template_too_few_parameters)
5718 << FnDecl->getDeclName();
5719
5720 // The function decl must have at least 1 parameter.
5721 if (FnDecl->getNumParams() == 0)
5722 return SemaRef.Diag(FnDecl->getLocation(),
5723 diag::err_operator_new_delete_too_few_parameters)
5724 << FnDecl->getDeclName();
5725
5726 // Check the the first parameter type is not dependent.
5727 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5728 if (FirstParamType->isDependentType())
5729 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5730 << FnDecl->getDeclName() << ExpectedFirstParamType;
5731
5732 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005733 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005734 ExpectedFirstParamType)
5735 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5736 << FnDecl->getDeclName() << ExpectedFirstParamType;
5737
5738 return false;
5739}
5740
Anders Carlsson12308f42009-12-11 23:23:22 +00005741static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005742CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005743 // C++ [basic.stc.dynamic.allocation]p1:
5744 // A program is ill-formed if an allocation function is declared in a
5745 // namespace scope other than global scope or declared static in global
5746 // scope.
5747 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5748 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005749
5750 CanQualType SizeTy =
5751 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5752
5753 // C++ [basic.stc.dynamic.allocation]p1:
5754 // The return type shall be void*. The first parameter shall have type
5755 // std::size_t.
5756 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5757 SizeTy,
5758 diag::err_operator_new_dependent_param_type,
5759 diag::err_operator_new_param_type))
5760 return true;
5761
5762 // C++ [basic.stc.dynamic.allocation]p1:
5763 // The first parameter shall not have an associated default argument.
5764 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005765 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005766 diag::err_operator_new_default_arg)
5767 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5768
5769 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005770}
5771
5772static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005773CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5774 // C++ [basic.stc.dynamic.deallocation]p1:
5775 // A program is ill-formed if deallocation functions are declared in a
5776 // namespace scope other than global scope or declared static in global
5777 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005778 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5779 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005780
5781 // C++ [basic.stc.dynamic.deallocation]p2:
5782 // Each deallocation function shall return void and its first parameter
5783 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005784 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5785 SemaRef.Context.VoidPtrTy,
5786 diag::err_operator_delete_dependent_param_type,
5787 diag::err_operator_delete_param_type))
5788 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005789
Anders Carlsson12308f42009-12-11 23:23:22 +00005790 return false;
5791}
5792
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005793/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5794/// of this overloaded operator is well-formed. If so, returns false;
5795/// otherwise, emits appropriate diagnostics and returns true.
5796bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005797 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005798 "Expected an overloaded operator declaration");
5799
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005800 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5801
Mike Stump11289f42009-09-09 15:08:12 +00005802 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005803 // The allocation and deallocation functions, operator new,
5804 // operator new[], operator delete and operator delete[], are
5805 // described completely in 3.7.3. The attributes and restrictions
5806 // found in the rest of this subclause do not apply to them unless
5807 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005808 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005809 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005810
Anders Carlsson22f443f2009-12-12 00:26:23 +00005811 if (Op == OO_New || Op == OO_Array_New)
5812 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005813
5814 // C++ [over.oper]p6:
5815 // An operator function shall either be a non-static member
5816 // function or be a non-member function and have at least one
5817 // parameter whose type is a class, a reference to a class, an
5818 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005819 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5820 if (MethodDecl->isStatic())
5821 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005822 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005823 } else {
5824 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005825 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5826 ParamEnd = FnDecl->param_end();
5827 Param != ParamEnd; ++Param) {
5828 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005829 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5830 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005831 ClassOrEnumParam = true;
5832 break;
5833 }
5834 }
5835
Douglas Gregord69246b2008-11-17 16:14:12 +00005836 if (!ClassOrEnumParam)
5837 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005838 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005839 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005840 }
5841
5842 // C++ [over.oper]p8:
5843 // An operator function cannot have default arguments (8.3.6),
5844 // except where explicitly stated below.
5845 //
Mike Stump11289f42009-09-09 15:08:12 +00005846 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005847 // (C++ [over.call]p1).
5848 if (Op != OO_Call) {
5849 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5850 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005851 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005852 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005853 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005854 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005855 }
5856 }
5857
Douglas Gregor6cf08062008-11-10 13:38:07 +00005858 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5859 { false, false, false }
5860#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5861 , { Unary, Binary, MemberOnly }
5862#include "clang/Basic/OperatorKinds.def"
5863 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005864
Douglas Gregor6cf08062008-11-10 13:38:07 +00005865 bool CanBeUnaryOperator = OperatorUses[Op][0];
5866 bool CanBeBinaryOperator = OperatorUses[Op][1];
5867 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005868
5869 // C++ [over.oper]p8:
5870 // [...] Operator functions cannot have more or fewer parameters
5871 // than the number required for the corresponding operator, as
5872 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005873 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005874 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005875 if (Op != OO_Call &&
5876 ((NumParams == 1 && !CanBeUnaryOperator) ||
5877 (NumParams == 2 && !CanBeBinaryOperator) ||
5878 (NumParams < 1) || (NumParams > 2))) {
5879 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005880 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005881 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005882 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005883 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005884 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005885 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005886 assert(CanBeBinaryOperator &&
5887 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005888 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005889 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005890
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005891 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005892 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005893 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005894
Douglas Gregord69246b2008-11-17 16:14:12 +00005895 // Overloaded operators other than operator() cannot be variadic.
5896 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005897 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005898 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005899 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005900 }
5901
5902 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005903 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5904 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005905 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005906 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005907 }
5908
5909 // C++ [over.inc]p1:
5910 // The user-defined function called operator++ implements the
5911 // prefix and postfix ++ operator. If this function is a member
5912 // function with no parameters, or a non-member function with one
5913 // parameter of class or enumeration type, it defines the prefix
5914 // increment operator ++ for objects of that type. If the function
5915 // is a member function with one parameter (which shall be of type
5916 // int) or a non-member function with two parameters (the second
5917 // of which shall be of type int), it defines the postfix
5918 // increment operator ++ for objects of that type.
5919 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5920 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5921 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005922 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005923 ParamIsInt = BT->getKind() == BuiltinType::Int;
5924
Chris Lattner2b786902008-11-21 07:50:02 +00005925 if (!ParamIsInt)
5926 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005927 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005928 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005929 }
5930
Douglas Gregord69246b2008-11-17 16:14:12 +00005931 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005932}
Chris Lattner3b024a32008-12-17 07:09:26 +00005933
Alexis Huntc88db062010-01-13 09:01:02 +00005934/// CheckLiteralOperatorDeclaration - Check whether the declaration
5935/// of this literal operator function is well-formed. If so, returns
5936/// false; otherwise, emits appropriate diagnostics and returns true.
5937bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5938 DeclContext *DC = FnDecl->getDeclContext();
5939 Decl::Kind Kind = DC->getDeclKind();
5940 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5941 Kind != Decl::LinkageSpec) {
5942 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5943 << FnDecl->getDeclName();
5944 return true;
5945 }
5946
5947 bool Valid = false;
5948
Alexis Hunt7dd26172010-04-07 23:11:06 +00005949 // template <char...> type operator "" name() is the only valid template
5950 // signature, and the only valid signature with no parameters.
5951 if (FnDecl->param_size() == 0) {
5952 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5953 // Must have only one template parameter
5954 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5955 if (Params->size() == 1) {
5956 NonTypeTemplateParmDecl *PmDecl =
5957 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005958
Alexis Hunt7dd26172010-04-07 23:11:06 +00005959 // The template parameter must be a char parameter pack.
5960 // FIXME: This test will always fail because non-type parameter packs
5961 // have not been implemented.
5962 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5963 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5964 Valid = true;
5965 }
5966 }
5967 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005968 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005969 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5970
Alexis Huntc88db062010-01-13 09:01:02 +00005971 QualType T = (*Param)->getType();
5972
Alexis Hunt079a6f72010-04-07 22:57:35 +00005973 // unsigned long long int, long double, and any character type are allowed
5974 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005975 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5976 Context.hasSameType(T, Context.LongDoubleTy) ||
5977 Context.hasSameType(T, Context.CharTy) ||
5978 Context.hasSameType(T, Context.WCharTy) ||
5979 Context.hasSameType(T, Context.Char16Ty) ||
5980 Context.hasSameType(T, Context.Char32Ty)) {
5981 if (++Param == FnDecl->param_end())
5982 Valid = true;
5983 goto FinishedParams;
5984 }
5985
Alexis Hunt079a6f72010-04-07 22:57:35 +00005986 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005987 const PointerType *PT = T->getAs<PointerType>();
5988 if (!PT)
5989 goto FinishedParams;
5990 T = PT->getPointeeType();
5991 if (!T.isConstQualified())
5992 goto FinishedParams;
5993 T = T.getUnqualifiedType();
5994
5995 // Move on to the second parameter;
5996 ++Param;
5997
5998 // If there is no second parameter, the first must be a const char *
5999 if (Param == FnDecl->param_end()) {
6000 if (Context.hasSameType(T, Context.CharTy))
6001 Valid = true;
6002 goto FinishedParams;
6003 }
6004
6005 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6006 // are allowed as the first parameter to a two-parameter function
6007 if (!(Context.hasSameType(T, Context.CharTy) ||
6008 Context.hasSameType(T, Context.WCharTy) ||
6009 Context.hasSameType(T, Context.Char16Ty) ||
6010 Context.hasSameType(T, Context.Char32Ty)))
6011 goto FinishedParams;
6012
6013 // The second and final parameter must be an std::size_t
6014 T = (*Param)->getType().getUnqualifiedType();
6015 if (Context.hasSameType(T, Context.getSizeType()) &&
6016 ++Param == FnDecl->param_end())
6017 Valid = true;
6018 }
6019
6020 // FIXME: This diagnostic is absolutely terrible.
6021FinishedParams:
6022 if (!Valid) {
6023 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6024 << FnDecl->getDeclName();
6025 return true;
6026 }
6027
6028 return false;
6029}
6030
Douglas Gregor07665a62009-01-05 19:45:36 +00006031/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6032/// linkage specification, including the language and (if present)
6033/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6034/// the location of the language string literal, which is provided
6035/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6036/// the '{' brace. Otherwise, this linkage specification does not
6037/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006038Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6039 SourceLocation LangLoc,
6040 llvm::StringRef Lang,
6041 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006042 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006043 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006044 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006045 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006046 Language = LinkageSpecDecl::lang_cxx;
6047 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006048 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006049 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006050 }
Mike Stump11289f42009-09-09 15:08:12 +00006051
Chris Lattner438e5012008-12-17 07:13:27 +00006052 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006053
Douglas Gregor07665a62009-01-05 19:45:36 +00006054 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006055 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006056 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006057 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006058 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006059 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006060}
6061
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006062/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006063/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6064/// valid, it's the position of the closing '}' brace in a linkage
6065/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006066Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6067 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006068 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006069 if (LinkageSpec)
6070 PopDeclContext();
6071 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006072}
6073
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006074/// \brief Perform semantic analysis for the variable declaration that
6075/// occurs within a C++ catch clause, returning the newly-created
6076/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006077VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006078 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006079 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006080 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006081 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006082 QualType ExDeclType = TInfo->getType();
6083
Sebastian Redl54c04d42008-12-22 19:15:10 +00006084 // Arrays and functions decay.
6085 if (ExDeclType->isArrayType())
6086 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6087 else if (ExDeclType->isFunctionType())
6088 ExDeclType = Context.getPointerType(ExDeclType);
6089
6090 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6091 // The exception-declaration shall not denote a pointer or reference to an
6092 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006093 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006094 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006095 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006096 Invalid = true;
6097 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006098
Douglas Gregor104ee002010-03-08 01:47:36 +00006099 // GCC allows catching pointers and references to incomplete types
6100 // as an extension; so do we, but we warn by default.
6101
Sebastian Redl54c04d42008-12-22 19:15:10 +00006102 QualType BaseType = ExDeclType;
6103 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006104 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006105 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006106 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006107 BaseType = Ptr->getPointeeType();
6108 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006109 DK = diag::ext_catch_incomplete_ptr;
6110 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006111 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006112 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006113 BaseType = Ref->getPointeeType();
6114 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006115 DK = diag::ext_catch_incomplete_ref;
6116 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006117 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006118 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006119 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6120 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006121 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006122
Mike Stump11289f42009-09-09 15:08:12 +00006123 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006124 RequireNonAbstractType(Loc, ExDeclType,
6125 diag::err_abstract_type_in_decl,
6126 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006127 Invalid = true;
6128
John McCall2ca705e2010-07-24 00:37:23 +00006129 // Only the non-fragile NeXT runtime currently supports C++ catches
6130 // of ObjC types, and no runtime supports catching ObjC types by value.
6131 if (!Invalid && getLangOptions().ObjC1) {
6132 QualType T = ExDeclType;
6133 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6134 T = RT->getPointeeType();
6135
6136 if (T->isObjCObjectType()) {
6137 Diag(Loc, diag::err_objc_object_catch);
6138 Invalid = true;
6139 } else if (T->isObjCObjectPointerType()) {
6140 if (!getLangOptions().NeXTRuntime) {
6141 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6142 Invalid = true;
6143 } else if (!getLangOptions().ObjCNonFragileABI) {
6144 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6145 Invalid = true;
6146 }
6147 }
6148 }
6149
Mike Stump11289f42009-09-09 15:08:12 +00006150 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006151 Name, ExDeclType, TInfo, SC_None,
6152 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006153 ExDecl->setExceptionVariable(true);
6154
Douglas Gregor6de584c2010-03-05 23:38:39 +00006155 if (!Invalid) {
6156 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6157 // C++ [except.handle]p16:
6158 // The object declared in an exception-declaration or, if the
6159 // exception-declaration does not specify a name, a temporary (12.2) is
6160 // copy-initialized (8.5) from the exception object. [...]
6161 // The object is destroyed when the handler exits, after the destruction
6162 // of any automatic objects initialized within the handler.
6163 //
6164 // We just pretend to initialize the object with itself, then make sure
6165 // it can be destroyed later.
6166 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6167 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006168 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006169 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6170 SourceLocation());
6171 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006172 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006173 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006174 if (Result.isInvalid())
6175 Invalid = true;
6176 else
6177 FinalizeVarWithDestructor(ExDecl, RecordTy);
6178 }
6179 }
6180
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006181 if (Invalid)
6182 ExDecl->setInvalidDecl();
6183
6184 return ExDecl;
6185}
6186
6187/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6188/// handler.
John McCall48871652010-08-21 09:40:31 +00006189Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006190 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006191 bool Invalid = D.isInvalidType();
6192
6193 // Check for unexpanded parameter packs.
6194 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6195 UPPC_ExceptionType)) {
6196 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6197 D.getIdentifierLoc());
6198 Invalid = true;
6199 }
6200
John McCall8cb7bdf2010-06-04 23:28:52 +00006201 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006202
Sebastian Redl54c04d42008-12-22 19:15:10 +00006203 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006204 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006205 LookupOrdinaryName,
6206 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006207 // The scope should be freshly made just for us. There is just no way
6208 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006209 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006210 if (PrevDecl->isTemplateParameter()) {
6211 // Maybe we will complain about the shadowed template parameter.
6212 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006213 }
6214 }
6215
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006216 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006217 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6218 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006219 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006220 }
6221
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006222 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006223 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006224 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006225
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006226 if (Invalid)
6227 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006228
Sebastian Redl54c04d42008-12-22 19:15:10 +00006229 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006230 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006231 PushOnScopeChains(ExDecl, S);
6232 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006233 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006234
Douglas Gregor758a8692009-06-17 21:51:59 +00006235 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006236 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006237}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006238
John McCall48871652010-08-21 09:40:31 +00006239Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006240 Expr *AssertExpr,
6241 Expr *AssertMessageExpr_) {
6242 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006243
Anders Carlsson54b26982009-03-14 00:33:21 +00006244 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6245 llvm::APSInt Value(32);
6246 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6247 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6248 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006249 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006250 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006251
Anders Carlsson54b26982009-03-14 00:33:21 +00006252 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006253 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006254 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006255 }
6256 }
Mike Stump11289f42009-09-09 15:08:12 +00006257
Douglas Gregoref68fee2010-12-15 23:55:21 +00006258 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6259 return 0;
6260
Mike Stump11289f42009-09-09 15:08:12 +00006261 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006262 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006263
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006264 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006265 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006266}
Sebastian Redlf769df52009-03-24 22:27:57 +00006267
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006268/// \brief Perform semantic analysis of the given friend type declaration.
6269///
6270/// \returns A friend declaration that.
6271FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6272 TypeSourceInfo *TSInfo) {
6273 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6274
6275 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006276 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006277
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006278 if (!getLangOptions().CPlusPlus0x) {
6279 // C++03 [class.friend]p2:
6280 // An elaborated-type-specifier shall be used in a friend declaration
6281 // for a class.*
6282 //
6283 // * The class-key of the elaborated-type-specifier is required.
6284 if (!ActiveTemplateInstantiations.empty()) {
6285 // Do not complain about the form of friend template types during
6286 // template instantiation; we will already have complained when the
6287 // template was declared.
6288 } else if (!T->isElaboratedTypeSpecifier()) {
6289 // If we evaluated the type to a record type, suggest putting
6290 // a tag in front.
6291 if (const RecordType *RT = T->getAs<RecordType>()) {
6292 RecordDecl *RD = RT->getDecl();
6293
6294 std::string InsertionText = std::string(" ") + RD->getKindName();
6295
6296 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6297 << (unsigned) RD->getTagKind()
6298 << T
6299 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6300 InsertionText);
6301 } else {
6302 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6303 << T
6304 << SourceRange(FriendLoc, TypeRange.getEnd());
6305 }
6306 } else if (T->getAs<EnumType>()) {
6307 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006308 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006309 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006310 }
6311 }
6312
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006313 // C++0x [class.friend]p3:
6314 // If the type specifier in a friend declaration designates a (possibly
6315 // cv-qualified) class type, that class is declared as a friend; otherwise,
6316 // the friend declaration is ignored.
6317
6318 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6319 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006320
6321 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6322}
6323
John McCallace48cd2010-10-19 01:40:49 +00006324/// Handle a friend tag declaration where the scope specifier was
6325/// templated.
6326Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6327 unsigned TagSpec, SourceLocation TagLoc,
6328 CXXScopeSpec &SS,
6329 IdentifierInfo *Name, SourceLocation NameLoc,
6330 AttributeList *Attr,
6331 MultiTemplateParamsArg TempParamLists) {
6332 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6333
6334 bool isExplicitSpecialization = false;
6335 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6336 bool Invalid = false;
6337
6338 if (TemplateParameterList *TemplateParams
6339 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6340 TempParamLists.get(),
6341 TempParamLists.size(),
6342 /*friend*/ true,
6343 isExplicitSpecialization,
6344 Invalid)) {
6345 --NumMatchedTemplateParamLists;
6346
6347 if (TemplateParams->size() > 0) {
6348 // This is a declaration of a class template.
6349 if (Invalid)
6350 return 0;
6351
6352 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6353 SS, Name, NameLoc, Attr,
6354 TemplateParams, AS_public).take();
6355 } else {
6356 // The "template<>" header is extraneous.
6357 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6358 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6359 isExplicitSpecialization = true;
6360 }
6361 }
6362
6363 if (Invalid) return 0;
6364
6365 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6366
6367 bool isAllExplicitSpecializations = true;
6368 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6369 if (TempParamLists.get()[I]->size()) {
6370 isAllExplicitSpecializations = false;
6371 break;
6372 }
6373 }
6374
6375 // FIXME: don't ignore attributes.
6376
6377 // If it's explicit specializations all the way down, just forget
6378 // about the template header and build an appropriate non-templated
6379 // friend. TODO: for source fidelity, remember the headers.
6380 if (isAllExplicitSpecializations) {
6381 ElaboratedTypeKeyword Keyword
6382 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6383 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6384 TagLoc, SS.getRange(), NameLoc);
6385 if (T.isNull())
6386 return 0;
6387
6388 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6389 if (isa<DependentNameType>(T)) {
6390 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6391 TL.setKeywordLoc(TagLoc);
6392 TL.setQualifierRange(SS.getRange());
6393 TL.setNameLoc(NameLoc);
6394 } else {
6395 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6396 TL.setKeywordLoc(TagLoc);
6397 TL.setQualifierRange(SS.getRange());
6398 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6399 }
6400
6401 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6402 TSI, FriendLoc);
6403 Friend->setAccess(AS_public);
6404 CurContext->addDecl(Friend);
6405 return Friend;
6406 }
6407
6408 // Handle the case of a templated-scope friend class. e.g.
6409 // template <class T> class A<T>::B;
6410 // FIXME: we don't support these right now.
6411 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6412 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6413 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6414 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6415 TL.setKeywordLoc(TagLoc);
6416 TL.setQualifierRange(SS.getRange());
6417 TL.setNameLoc(NameLoc);
6418
6419 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6420 TSI, FriendLoc);
6421 Friend->setAccess(AS_public);
6422 Friend->setUnsupportedFriend(true);
6423 CurContext->addDecl(Friend);
6424 return Friend;
6425}
6426
6427
John McCall11083da2009-09-16 22:47:08 +00006428/// Handle a friend type declaration. This works in tandem with
6429/// ActOnTag.
6430///
6431/// Notes on friend class templates:
6432///
6433/// We generally treat friend class declarations as if they were
6434/// declaring a class. So, for example, the elaborated type specifier
6435/// in a friend declaration is required to obey the restrictions of a
6436/// class-head (i.e. no typedefs in the scope chain), template
6437/// parameters are required to match up with simple template-ids, &c.
6438/// However, unlike when declaring a template specialization, it's
6439/// okay to refer to a template specialization without an empty
6440/// template parameter declaration, e.g.
6441/// friend class A<T>::B<unsigned>;
6442/// We permit this as a special case; if there are any template
6443/// parameters present at all, require proper matching, i.e.
6444/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006445Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006446 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006447 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006448
6449 assert(DS.isFriendSpecified());
6450 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6451
John McCall11083da2009-09-16 22:47:08 +00006452 // Try to convert the decl specifier to a type. This works for
6453 // friend templates because ActOnTag never produces a ClassTemplateDecl
6454 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006455 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006456 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6457 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006458 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006459 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006460
Douglas Gregor6c110f32010-12-16 01:14:37 +00006461 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6462 return 0;
6463
John McCall11083da2009-09-16 22:47:08 +00006464 // This is definitely an error in C++98. It's probably meant to
6465 // be forbidden in C++0x, too, but the specification is just
6466 // poorly written.
6467 //
6468 // The problem is with declarations like the following:
6469 // template <T> friend A<T>::foo;
6470 // where deciding whether a class C is a friend or not now hinges
6471 // on whether there exists an instantiation of A that causes
6472 // 'foo' to equal C. There are restrictions on class-heads
6473 // (which we declare (by fiat) elaborated friend declarations to
6474 // be) that makes this tractable.
6475 //
6476 // FIXME: handle "template <> friend class A<T>;", which
6477 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006478 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006479 Diag(Loc, diag::err_tagless_friend_type_template)
6480 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006481 return 0;
John McCall11083da2009-09-16 22:47:08 +00006482 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006483
John McCallaa74a0c2009-08-28 07:59:38 +00006484 // C++98 [class.friend]p1: A friend of a class is a function
6485 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006486 // This is fixed in DR77, which just barely didn't make the C++03
6487 // deadline. It's also a very silly restriction that seriously
6488 // affects inner classes and which nobody else seems to implement;
6489 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006490 //
6491 // But note that we could warn about it: it's always useless to
6492 // friend one of your own members (it's not, however, worthless to
6493 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006494
John McCall11083da2009-09-16 22:47:08 +00006495 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006496 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006497 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006498 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006499 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006500 TSI,
John McCall11083da2009-09-16 22:47:08 +00006501 DS.getFriendSpecLoc());
6502 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006503 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6504
6505 if (!D)
John McCall48871652010-08-21 09:40:31 +00006506 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006507
John McCall11083da2009-09-16 22:47:08 +00006508 D->setAccess(AS_public);
6509 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006510
John McCall48871652010-08-21 09:40:31 +00006511 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006512}
6513
John McCallde3fd222010-10-12 23:13:28 +00006514Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6515 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006516 const DeclSpec &DS = D.getDeclSpec();
6517
6518 assert(DS.isFriendSpecified());
6519 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6520
6521 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006522 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6523 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006524
6525 // C++ [class.friend]p1
6526 // A friend of a class is a function or class....
6527 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006528 // It *doesn't* see through dependent types, which is correct
6529 // according to [temp.arg.type]p3:
6530 // If a declaration acquires a function type through a
6531 // type dependent on a template-parameter and this causes
6532 // a declaration that does not use the syntactic form of a
6533 // function declarator to have a function type, the program
6534 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006535 if (!T->isFunctionType()) {
6536 Diag(Loc, diag::err_unexpected_friend);
6537
6538 // It might be worthwhile to try to recover by creating an
6539 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006540 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006541 }
6542
6543 // C++ [namespace.memdef]p3
6544 // - If a friend declaration in a non-local class first declares a
6545 // class or function, the friend class or function is a member
6546 // of the innermost enclosing namespace.
6547 // - The name of the friend is not found by simple name lookup
6548 // until a matching declaration is provided in that namespace
6549 // scope (either before or after the class declaration granting
6550 // friendship).
6551 // - If a friend function is called, its name may be found by the
6552 // name lookup that considers functions from namespaces and
6553 // classes associated with the types of the function arguments.
6554 // - When looking for a prior declaration of a class or a function
6555 // declared as a friend, scopes outside the innermost enclosing
6556 // namespace scope are not considered.
6557
John McCallde3fd222010-10-12 23:13:28 +00006558 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006559 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6560 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006561 assert(Name);
6562
Douglas Gregor6c110f32010-12-16 01:14:37 +00006563 // Check for unexpanded parameter packs.
6564 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6565 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6566 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6567 return 0;
6568
John McCall07e91c02009-08-06 02:15:43 +00006569 // The context we found the declaration in, or in which we should
6570 // create the declaration.
6571 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006572 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006573 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006574 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006575
John McCallde3fd222010-10-12 23:13:28 +00006576 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006577
John McCallde3fd222010-10-12 23:13:28 +00006578 // There are four cases here.
6579 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006580 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006581 // there as appropriate.
6582 // Recover from invalid scope qualifiers as if they just weren't there.
6583 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006584 // C++0x [namespace.memdef]p3:
6585 // If the name in a friend declaration is neither qualified nor
6586 // a template-id and the declaration is a function or an
6587 // elaborated-type-specifier, the lookup to determine whether
6588 // the entity has been previously declared shall not consider
6589 // any scopes outside the innermost enclosing namespace.
6590 // C++0x [class.friend]p11:
6591 // If a friend declaration appears in a local class and the name
6592 // specified is an unqualified name, a prior declaration is
6593 // looked up without considering scopes that are outside the
6594 // innermost enclosing non-class scope. For a friend function
6595 // declaration, if there is no prior declaration, the program is
6596 // ill-formed.
6597 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006598 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006599
John McCallf7cfb222010-10-13 05:45:15 +00006600 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006601 DC = CurContext;
6602 while (true) {
6603 // Skip class contexts. If someone can cite chapter and verse
6604 // for this behavior, that would be nice --- it's what GCC and
6605 // EDG do, and it seems like a reasonable intent, but the spec
6606 // really only says that checks for unqualified existing
6607 // declarations should stop at the nearest enclosing namespace,
6608 // not that they should only consider the nearest enclosing
6609 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006610 while (DC->isRecord())
6611 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006612
John McCall1f82f242009-11-18 22:49:29 +00006613 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006614
6615 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006616 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006617 break;
John McCallf7cfb222010-10-13 05:45:15 +00006618
John McCallf4776592010-10-14 22:22:28 +00006619 if (isTemplateId) {
6620 if (isa<TranslationUnitDecl>(DC)) break;
6621 } else {
6622 if (DC->isFileContext()) break;
6623 }
John McCall07e91c02009-08-06 02:15:43 +00006624 DC = DC->getParent();
6625 }
6626
6627 // C++ [class.friend]p1: A friend of a class is a function or
6628 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006629 // C++0x changes this for both friend types and functions.
6630 // Most C++ 98 compilers do seem to give an error here, so
6631 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006632 if (!Previous.empty() && DC->Equals(CurContext)
6633 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006634 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006635
John McCallccbc0322010-10-13 06:22:15 +00006636 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006637
John McCallde3fd222010-10-12 23:13:28 +00006638 // - There's a non-dependent scope specifier, in which case we
6639 // compute it and do a previous lookup there for a function
6640 // or function template.
6641 } else if (!SS.getScopeRep()->isDependent()) {
6642 DC = computeDeclContext(SS);
6643 if (!DC) return 0;
6644
6645 if (RequireCompleteDeclContext(SS, DC)) return 0;
6646
6647 LookupQualifiedName(Previous, DC);
6648
6649 // Ignore things found implicitly in the wrong scope.
6650 // TODO: better diagnostics for this case. Suggesting the right
6651 // qualified scope would be nice...
6652 LookupResult::Filter F = Previous.makeFilter();
6653 while (F.hasNext()) {
6654 NamedDecl *D = F.next();
6655 if (!DC->InEnclosingNamespaceSetOf(
6656 D->getDeclContext()->getRedeclContext()))
6657 F.erase();
6658 }
6659 F.done();
6660
6661 if (Previous.empty()) {
6662 D.setInvalidType();
6663 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6664 return 0;
6665 }
6666
6667 // C++ [class.friend]p1: A friend of a class is a function or
6668 // class that is not a member of the class . . .
6669 if (DC->Equals(CurContext))
6670 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6671
6672 // - There's a scope specifier that does not match any template
6673 // parameter lists, in which case we use some arbitrary context,
6674 // create a method or method template, and wait for instantiation.
6675 // - There's a scope specifier that does match some template
6676 // parameter lists, which we don't handle right now.
6677 } else {
6678 DC = CurContext;
6679 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006680 }
6681
John McCallf7cfb222010-10-13 05:45:15 +00006682 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006683 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006684 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6685 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6686 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006687 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006688 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6689 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006690 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006691 }
John McCall07e91c02009-08-06 02:15:43 +00006692 }
6693
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006694 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006695 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006696 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006697 IsDefinition,
6698 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006699 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006700
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006701 assert(ND->getDeclContext() == DC);
6702 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006703
John McCall759e32b2009-08-31 22:39:49 +00006704 // Add the function declaration to the appropriate lookup tables,
6705 // adjusting the redeclarations list as necessary. We don't
6706 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006707 //
John McCall759e32b2009-08-31 22:39:49 +00006708 // Also update the scope-based lookup if the target context's
6709 // lookup context is in lexical scope.
6710 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006711 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006712 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006713 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006714 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006715 }
John McCallaa74a0c2009-08-28 07:59:38 +00006716
6717 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006718 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006719 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006720 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006721 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006722
John McCallde3fd222010-10-12 23:13:28 +00006723 if (ND->isInvalidDecl())
6724 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006725 else {
6726 FunctionDecl *FD;
6727 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6728 FD = FTD->getTemplatedDecl();
6729 else
6730 FD = cast<FunctionDecl>(ND);
6731
6732 // Mark templated-scope function declarations as unsupported.
6733 if (FD->getNumTemplateParameterLists())
6734 FrD->setUnsupportedFriend(true);
6735 }
John McCallde3fd222010-10-12 23:13:28 +00006736
John McCall48871652010-08-21 09:40:31 +00006737 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006738}
6739
John McCall48871652010-08-21 09:40:31 +00006740void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6741 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006742
Sebastian Redlf769df52009-03-24 22:27:57 +00006743 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6744 if (!Fn) {
6745 Diag(DelLoc, diag::err_deleted_non_function);
6746 return;
6747 }
6748 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6749 Diag(DelLoc, diag::err_deleted_decl_not_first);
6750 Diag(Prev->getLocation(), diag::note_previous_declaration);
6751 // If the declaration wasn't the first, we delete the function anyway for
6752 // recovery.
6753 }
6754 Fn->setDeleted();
6755}
Sebastian Redl4c018662009-04-27 21:33:24 +00006756
6757static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6758 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6759 ++CI) {
6760 Stmt *SubStmt = *CI;
6761 if (!SubStmt)
6762 continue;
6763 if (isa<ReturnStmt>(SubStmt))
6764 Self.Diag(SubStmt->getSourceRange().getBegin(),
6765 diag::err_return_in_constructor_handler);
6766 if (!isa<Expr>(SubStmt))
6767 SearchForReturnInStmt(Self, SubStmt);
6768 }
6769}
6770
6771void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6772 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6773 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6774 SearchForReturnInStmt(*this, Handler);
6775 }
6776}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006777
Mike Stump11289f42009-09-09 15:08:12 +00006778bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006779 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006780 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6781 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006782
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006783 if (Context.hasSameType(NewTy, OldTy) ||
6784 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006785 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006786
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006787 // Check if the return types are covariant
6788 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006789
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006790 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006791 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6792 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006793 NewClassTy = NewPT->getPointeeType();
6794 OldClassTy = OldPT->getPointeeType();
6795 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006796 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6797 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6798 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6799 NewClassTy = NewRT->getPointeeType();
6800 OldClassTy = OldRT->getPointeeType();
6801 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006802 }
6803 }
Mike Stump11289f42009-09-09 15:08:12 +00006804
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006805 // The return types aren't either both pointers or references to a class type.
6806 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006807 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006808 diag::err_different_return_type_for_overriding_virtual_function)
6809 << New->getDeclName() << NewTy << OldTy;
6810 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006811
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006812 return true;
6813 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006814
Anders Carlssone60365b2009-12-31 18:34:24 +00006815 // C++ [class.virtual]p6:
6816 // If the return type of D::f differs from the return type of B::f, the
6817 // class type in the return type of D::f shall be complete at the point of
6818 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006819 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6820 if (!RT->isBeingDefined() &&
6821 RequireCompleteType(New->getLocation(), NewClassTy,
6822 PDiag(diag::err_covariant_return_incomplete)
6823 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006824 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006825 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006826
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006827 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006828 // Check if the new class derives from the old class.
6829 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6830 Diag(New->getLocation(),
6831 diag::err_covariant_return_not_derived)
6832 << New->getDeclName() << NewTy << OldTy;
6833 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6834 return true;
6835 }
Mike Stump11289f42009-09-09 15:08:12 +00006836
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006837 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006838 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006839 diag::err_covariant_return_inaccessible_base,
6840 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6841 // FIXME: Should this point to the return type?
6842 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006843 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6844 return true;
6845 }
6846 }
Mike Stump11289f42009-09-09 15:08:12 +00006847
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006848 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006849 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006850 Diag(New->getLocation(),
6851 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006852 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006853 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6854 return true;
6855 };
Mike Stump11289f42009-09-09 15:08:12 +00006856
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006857
6858 // The new class type must have the same or less qualifiers as the old type.
6859 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6860 Diag(New->getLocation(),
6861 diag::err_covariant_return_type_class_type_more_qualified)
6862 << New->getDeclName() << NewTy << OldTy;
6863 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6864 return true;
6865 };
Mike Stump11289f42009-09-09 15:08:12 +00006866
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006867 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006868}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006869
Alexis Hunt96d5c762009-11-21 08:43:09 +00006870bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6871 const CXXMethodDecl *Old)
6872{
6873 if (Old->hasAttr<FinalAttr>()) {
6874 Diag(New->getLocation(), diag::err_final_function_overridden)
6875 << New->getDeclName();
6876 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6877 return true;
6878 }
6879
6880 return false;
6881}
6882
Douglas Gregor21920e372009-12-01 17:24:26 +00006883/// \brief Mark the given method pure.
6884///
6885/// \param Method the method to be marked pure.
6886///
6887/// \param InitRange the source range that covers the "0" initializer.
6888bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6889 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6890 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006891 return false;
6892 }
6893
6894 if (!Method->isInvalidDecl())
6895 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6896 << Method->getDeclName() << InitRange;
6897 return true;
6898}
6899
John McCall1f4ee7b2009-12-19 09:28:58 +00006900/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6901/// an initializer for the out-of-line declaration 'Dcl'. The scope
6902/// is a fresh scope pushed for just this purpose.
6903///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006904/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6905/// static data member of class X, names should be looked up in the scope of
6906/// class X.
John McCall48871652010-08-21 09:40:31 +00006907void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006908 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006909 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006910
John McCall1f4ee7b2009-12-19 09:28:58 +00006911 // We should only get called for declarations with scope specifiers, like:
6912 // int foo::bar;
6913 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006914 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006915}
6916
6917/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006918/// initializer for the out-of-line declaration 'D'.
6919void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006920 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006921 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006922
John McCall1f4ee7b2009-12-19 09:28:58 +00006923 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006924 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006925}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006926
6927/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6928/// C++ if/switch/while/for statement.
6929/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006930DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006931 // C++ 6.4p2:
6932 // The declarator shall not specify a function or an array.
6933 // The type-specifier-seq shall not contain typedef and shall not declare a
6934 // new class or enumeration.
6935 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6936 "Parser allowed 'typedef' as storage class of condition decl.");
6937
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006938 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006939 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6940 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006941
6942 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6943 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6944 // would be created and CXXConditionDeclExpr wants a VarDecl.
6945 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6946 << D.getSourceRange();
6947 return DeclResult();
6948 } else if (OwnedTag && OwnedTag->isDefinition()) {
6949 // The type-specifier-seq shall not declare a new class or enumeration.
6950 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6951 }
6952
John McCall48871652010-08-21 09:40:31 +00006953 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006954 if (!Dcl)
6955 return DeclResult();
6956
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006957 return Dcl;
6958}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006959
Douglas Gregor88d292c2010-05-13 16:44:06 +00006960void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6961 bool DefinitionRequired) {
6962 // Ignore any vtable uses in unevaluated operands or for classes that do
6963 // not have a vtable.
6964 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6965 CurContext->isDependentContext() ||
6966 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006967 return;
6968
Douglas Gregor88d292c2010-05-13 16:44:06 +00006969 // Try to insert this class into the map.
6970 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6971 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6972 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6973 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006974 // If we already had an entry, check to see if we are promoting this vtable
6975 // to required a definition. If so, we need to reappend to the VTableUses
6976 // list, since we may have already processed the first entry.
6977 if (DefinitionRequired && !Pos.first->second) {
6978 Pos.first->second = true;
6979 } else {
6980 // Otherwise, we can early exit.
6981 return;
6982 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006983 }
6984
6985 // Local classes need to have their virtual members marked
6986 // immediately. For all other classes, we mark their virtual members
6987 // at the end of the translation unit.
6988 if (Class->isLocalClass())
6989 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006990 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006991 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006992}
6993
Douglas Gregor88d292c2010-05-13 16:44:06 +00006994bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006995 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006996 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00006997
Douglas Gregor88d292c2010-05-13 16:44:06 +00006998 // Note: The VTableUses vector could grow as a result of marking
6999 // the members of a class as "used", so we check the size each
7000 // time through the loop and prefer indices (with are stable) to
7001 // iterators (which are not).
7002 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007003 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007004 if (!Class)
7005 continue;
7006
7007 SourceLocation Loc = VTableUses[I].second;
7008
7009 // If this class has a key function, but that key function is
7010 // defined in another translation unit, we don't need to emit the
7011 // vtable even though we're using it.
7012 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007013 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007014 switch (KeyFunction->getTemplateSpecializationKind()) {
7015 case TSK_Undeclared:
7016 case TSK_ExplicitSpecialization:
7017 case TSK_ExplicitInstantiationDeclaration:
7018 // The key function is in another translation unit.
7019 continue;
7020
7021 case TSK_ExplicitInstantiationDefinition:
7022 case TSK_ImplicitInstantiation:
7023 // We will be instantiating the key function.
7024 break;
7025 }
7026 } else if (!KeyFunction) {
7027 // If we have a class with no key function that is the subject
7028 // of an explicit instantiation declaration, suppress the
7029 // vtable; it will live with the explicit instantiation
7030 // definition.
7031 bool IsExplicitInstantiationDeclaration
7032 = Class->getTemplateSpecializationKind()
7033 == TSK_ExplicitInstantiationDeclaration;
7034 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7035 REnd = Class->redecls_end();
7036 R != REnd; ++R) {
7037 TemplateSpecializationKind TSK
7038 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7039 if (TSK == TSK_ExplicitInstantiationDeclaration)
7040 IsExplicitInstantiationDeclaration = true;
7041 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7042 IsExplicitInstantiationDeclaration = false;
7043 break;
7044 }
7045 }
7046
7047 if (IsExplicitInstantiationDeclaration)
7048 continue;
7049 }
7050
7051 // Mark all of the virtual members of this class as referenced, so
7052 // that we can build a vtable. Then, tell the AST consumer that a
7053 // vtable for this class is required.
7054 MarkVirtualMembersReferenced(Loc, Class);
7055 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7056 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7057
7058 // Optionally warn if we're emitting a weak vtable.
7059 if (Class->getLinkage() == ExternalLinkage &&
7060 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007061 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007062 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7063 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007064 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007065 VTableUses.clear();
7066
Anders Carlsson82fccd02009-12-07 08:24:59 +00007067 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007068}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007069
Rafael Espindola5b334082010-03-26 00:36:59 +00007070void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7071 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007072 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7073 e = RD->method_end(); i != e; ++i) {
7074 CXXMethodDecl *MD = *i;
7075
7076 // C++ [basic.def.odr]p2:
7077 // [...] A virtual member function is used if it is not pure. [...]
7078 if (MD->isVirtual() && !MD->isPure())
7079 MarkDeclarationReferenced(Loc, MD);
7080 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007081
7082 // Only classes that have virtual bases need a VTT.
7083 if (RD->getNumVBases() == 0)
7084 return;
7085
7086 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7087 e = RD->bases_end(); i != e; ++i) {
7088 const CXXRecordDecl *Base =
7089 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007090 if (Base->getNumVBases() == 0)
7091 continue;
7092 MarkVirtualMembersReferenced(Loc, Base);
7093 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007094}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007095
7096/// SetIvarInitializers - This routine builds initialization ASTs for the
7097/// Objective-C implementation whose ivars need be initialized.
7098void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7099 if (!getLangOptions().CPlusPlus)
7100 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007101 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007102 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7103 CollectIvarsToConstructOrDestruct(OID, ivars);
7104 if (ivars.empty())
7105 return;
7106 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
7107 for (unsigned i = 0; i < ivars.size(); i++) {
7108 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007109 if (Field->isInvalidDecl())
7110 continue;
7111
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007112 CXXBaseOrMemberInitializer *Member;
7113 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7114 InitializationKind InitKind =
7115 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7116
7117 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007118 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007119 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007120 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007121 // Note, MemberInit could actually come back empty if no initialization
7122 // is required (e.g., because it would call a trivial default constructor)
7123 if (!MemberInit.get() || MemberInit.isInvalid())
7124 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007125
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007126 Member =
7127 new (Context) CXXBaseOrMemberInitializer(Context,
7128 Field, SourceLocation(),
7129 SourceLocation(),
7130 MemberInit.takeAs<Expr>(),
7131 SourceLocation());
7132 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007133
7134 // Be sure that the destructor is accessible and is marked as referenced.
7135 if (const RecordType *RecordTy
7136 = Context.getBaseElementType(Field->getType())
7137 ->getAs<RecordType>()) {
7138 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007139 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007140 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7141 CheckDestructorAccess(Field->getLocation(), Destructor,
7142 PDiag(diag::err_access_dtor_ivar)
7143 << Context.getBaseElementType(Field->getType()));
7144 }
7145 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007146 }
7147 ObjCImplementation->setIvarInitializers(Context,
7148 AllToInit.data(), AllToInit.size());
7149 }
7150}