blob: bf5addc34d56bc19ba5c003f4892efea54b909c7 [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
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000524 // C++ [class.derived]p2:
525 // If a class is marked with the class-virt-specifier final and it appears
526 // as a base-type-specifier in a base-clause (10 class.derived), the program
527 // is ill-formed.
528 if (CXXBaseDecl->isMarkedFinal()) {
529 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
530 << CXXBaseDecl->getDeclName();
531 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
532 << CXXBaseDecl->getDeclName();
533 return 0;
534 }
535
536 // FIXME: Get rid of this.
Alexis Hunt96d5c762009-11-21 08:43:09 +0000537 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
538 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
539 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000540 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
541 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000542 return 0;
543 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000544
John McCall3696dcb2010-08-17 07:23:57 +0000545 if (BaseDecl->isInvalidDecl())
546 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000547
548 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000549 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000550 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000551 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000552}
553
Douglas Gregor556877c2008-04-13 21:30:24 +0000554/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
555/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000556/// example:
557/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000558/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000559BaseResult
John McCall48871652010-08-21 09:40:31 +0000560Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000561 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 ParsedType basetype, SourceLocation BaseLoc,
563 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000564 if (!classdecl)
565 return true;
566
Douglas Gregorc40290e2009-03-09 23:48:35 +0000567 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000568 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000569 if (!Class)
570 return true;
571
Nick Lewycky19b9f952010-07-26 16:56:01 +0000572 TypeSourceInfo *TInfo = 0;
573 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000574
Douglas Gregor752a5952011-01-03 22:36:02 +0000575 if (EllipsisLoc.isInvalid() &&
576 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000577 UPPC_BaseType))
578 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000579
Douglas Gregor463421d2009-03-03 04:44:36 +0000580 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000581 Virtual, Access, TInfo,
582 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000583 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000584
Douglas Gregor463421d2009-03-03 04:44:36 +0000585 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000586}
Douglas Gregor556877c2008-04-13 21:30:24 +0000587
Douglas Gregor463421d2009-03-03 04:44:36 +0000588/// \brief Performs the actual work of attaching the given base class
589/// specifiers to a C++ class.
590bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
591 unsigned NumBases) {
592 if (NumBases == 0)
593 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000594
595 // Used to keep track of which base types we have already seen, so
596 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000597 // that the key is always the unqualified canonical type of the base
598 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000599 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
600
601 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000602 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000604 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000605 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000607 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000608 if (!Class->hasObjectMember()) {
609 if (const RecordType *FDTTy =
610 NewBaseType.getTypePtr()->getAs<RecordType>())
611 if (FDTTy->getDecl()->hasObjectMember())
612 Class->setHasObjectMember(true);
613 }
614
Douglas Gregor29a92472008-10-22 17:49:05 +0000615 if (KnownBaseTypes[NewBaseType]) {
616 // C++ [class.mi]p3:
617 // A class shall not be specified as a direct base class of a
618 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000619 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000620 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000621 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000623
624 // Delete the duplicate base class specifier; we're going to
625 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000626 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000627
628 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000629 } else {
630 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 KnownBaseTypes[NewBaseType] = Bases[idx];
632 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000633 }
634 }
635
636 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000637 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000638
639 // Delete the remaining (good) base class specifiers, since their
640 // data has been copied into the CXXRecordDecl.
641 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000642 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000643
644 return Invalid;
645}
646
647/// ActOnBaseSpecifiers - Attach the given base specifiers to the
648/// class, after checking whether there are any duplicate base
649/// classes.
John McCall48871652010-08-21 09:40:31 +0000650void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000651 unsigned NumBases) {
652 if (!ClassDecl || !Bases || !NumBases)
653 return;
654
655 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000656 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000658}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000659
John McCalle78aac42010-03-10 03:28:59 +0000660static CXXRecordDecl *GetClassForType(QualType T) {
661 if (const RecordType *RT = T->getAs<RecordType>())
662 return cast<CXXRecordDecl>(RT->getDecl());
663 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
664 return ICT->getDecl();
665 else
666 return 0;
667}
668
Douglas Gregor36d1b142009-10-06 17:59:45 +0000669/// \brief Determine whether the type \p Derived is a C++ class that is
670/// derived from the type \p Base.
671bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
672 if (!getLangOptions().CPlusPlus)
673 return false;
John McCalle78aac42010-03-10 03:28:59 +0000674
675 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
676 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000677 return false;
678
John McCalle78aac42010-03-10 03:28:59 +0000679 CXXRecordDecl *BaseRD = GetClassForType(Base);
680 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000681 return false;
682
John McCall67da35c2010-02-04 22:26:26 +0000683 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
684 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000685}
686
687/// \brief Determine whether the type \p Derived is a C++ class that is
688/// derived from the type \p Base.
689bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
690 if (!getLangOptions().CPlusPlus)
691 return false;
692
John McCalle78aac42010-03-10 03:28:59 +0000693 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
694 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000695 return false;
696
John McCalle78aac42010-03-10 03:28:59 +0000697 CXXRecordDecl *BaseRD = GetClassForType(Base);
698 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000699 return false;
700
Douglas Gregor36d1b142009-10-06 17:59:45 +0000701 return DerivedRD->isDerivedFrom(BaseRD, Paths);
702}
703
Anders Carlssona70cff62010-04-24 19:06:50 +0000704void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000705 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000706 assert(BasePathArray.empty() && "Base path array must be empty!");
707 assert(Paths.isRecordingPaths() && "Must record paths!");
708
709 const CXXBasePath &Path = Paths.front();
710
711 // We first go backward and check if we have a virtual base.
712 // FIXME: It would be better if CXXBasePath had the base specifier for
713 // the nearest virtual base.
714 unsigned Start = 0;
715 for (unsigned I = Path.size(); I != 0; --I) {
716 if (Path[I - 1].Base->isVirtual()) {
717 Start = I - 1;
718 break;
719 }
720 }
721
722 // Now add all bases.
723 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000724 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000725}
726
Douglas Gregor88d292c2010-05-13 16:44:06 +0000727/// \brief Determine whether the given base path includes a virtual
728/// base class.
John McCallcf142162010-08-07 06:22:56 +0000729bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
730 for (CXXCastPath::const_iterator B = BasePath.begin(),
731 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000732 B != BEnd; ++B)
733 if ((*B)->isVirtual())
734 return true;
735
736 return false;
737}
738
Douglas Gregor36d1b142009-10-06 17:59:45 +0000739/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
740/// conversion (where Derived and Base are class types) is
741/// well-formed, meaning that the conversion is unambiguous (and
742/// that all of the base classes are accessible). Returns true
743/// and emits a diagnostic if the code is ill-formed, returns false
744/// otherwise. Loc is the location where this routine should point to
745/// if there is an error, and Range is the source range to highlight
746/// if there is an error.
747bool
748Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000749 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000750 unsigned AmbigiousBaseConvID,
751 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000752 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000753 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000754 // First, determine whether the path from Derived to Base is
755 // ambiguous. This is slightly more expensive than checking whether
756 // the Derived to Base conversion exists, because here we need to
757 // explore multiple paths to determine if there is an ambiguity.
758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
759 /*DetectVirtual=*/false);
760 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
761 assert(DerivationOkay &&
762 "Can only be used with a derived-to-base conversion");
763 (void)DerivationOkay;
764
765 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000766 if (InaccessibleBaseID) {
767 // Check that the base class can be accessed.
768 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
769 InaccessibleBaseID)) {
770 case AR_inaccessible:
771 return true;
772 case AR_accessible:
773 case AR_dependent:
774 case AR_delayed:
775 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000776 }
John McCall5b0829a2010-02-10 09:31:12 +0000777 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000778
779 // Build a base path if necessary.
780 if (BasePath)
781 BuildBasePathArray(Paths, *BasePath);
782 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000783 }
784
785 // We know that the derived-to-base conversion is ambiguous, and
786 // we're going to produce a diagnostic. Perform the derived-to-base
787 // search just one more time to compute all of the possible paths so
788 // that we can print them out. This is more expensive than any of
789 // the previous derived-to-base checks we've done, but at this point
790 // performance isn't as much of an issue.
791 Paths.clear();
792 Paths.setRecordingPaths(true);
793 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
794 assert(StillOkay && "Can only be used with a derived-to-base conversion");
795 (void)StillOkay;
796
797 // Build up a textual representation of the ambiguous paths, e.g.,
798 // D -> B -> A, that will be used to illustrate the ambiguous
799 // conversions in the diagnostic. We only print one of the paths
800 // to each base class subobject.
801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
802
803 Diag(Loc, AmbigiousBaseConvID)
804 << Derived << Base << PathDisplayStr << Range << Name;
805 return true;
806}
807
808bool
809Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000810 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000811 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000812 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000813 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000814 IgnoreAccess ? 0
815 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000816 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000817 Loc, Range, DeclarationName(),
818 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000819}
820
821
822/// @brief Builds a string representing ambiguous paths from a
823/// specific derived class to different subobjects of the same base
824/// class.
825///
826/// This function builds a string that can be used in error messages
827/// to show the different paths that one can take through the
828/// inheritance hierarchy to go from the derived class to different
829/// subobjects of a base class. The result looks something like this:
830/// @code
831/// struct D -> struct B -> struct A
832/// struct D -> struct C -> struct A
833/// @endcode
834std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
835 std::string PathDisplayStr;
836 std::set<unsigned> DisplayedPaths;
837 for (CXXBasePaths::paths_iterator Path = Paths.begin();
838 Path != Paths.end(); ++Path) {
839 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
840 // We haven't displayed a path to this particular base
841 // class subobject yet.
842 PathDisplayStr += "\n ";
843 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
844 for (CXXBasePath::const_iterator Element = Path->begin();
845 Element != Path->end(); ++Element)
846 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
847 }
848 }
849
850 return PathDisplayStr;
851}
852
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853//===----------------------------------------------------------------------===//
854// C++ class member Handling
855//===----------------------------------------------------------------------===//
856
Abramo Bagnarad7340582010-06-05 05:09:32 +0000857/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000858Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
859 SourceLocation ASLoc,
860 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000861 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000862 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000863 ASLoc, ColonLoc);
864 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000865 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000866}
867
Anders Carlssonfd835532011-01-20 05:57:14 +0000868/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000869void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000870 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
871 if (!MD || !MD->isVirtual())
872 return;
873
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000874 if (MD->isDependentContext())
875 return;
876
Anders Carlssonfd835532011-01-20 05:57:14 +0000877 // C++0x [class.virtual]p3:
878 // If a virtual function is marked with the virt-specifier override and does
879 // not override a member function of a base class,
880 // the program is ill-formed.
881 bool HasOverriddenMethods =
882 MD->begin_overridden_methods() != MD->end_overridden_methods();
883 if (MD->isMarkedOverride() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000884 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000885 diag::err_function_marked_override_not_overriding)
886 << MD->getDeclName();
887 return;
888 }
889}
890
Anders Carlsson3f610c72011-01-20 16:25:36 +0000891/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
892/// function overrides a virtual member function marked 'final', according to
893/// C++0x [class.virtual]p3.
894bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
895 const CXXMethodDecl *Old) {
896 // FIXME: Get rid of FinalAttr here.
897 if (Old->hasAttr<FinalAttr>() || Old->isMarkedFinal()) {
898 Diag(New->getLocation(), diag::err_final_function_overridden)
899 << New->getDeclName();
900 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
901 return true;
902 }
903
904 return false;
905}
906
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000907/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
908/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
909/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000910/// any.
John McCall48871652010-08-21 09:40:31 +0000911Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000912Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000913 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000914 ExprTy *BW, const VirtSpecifiers &VS,
915 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000916 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000917 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000918 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
919 DeclarationName Name = NameInfo.getName();
920 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000921
922 // For anonymous bitfields, the location should point to the type.
923 if (Loc.isInvalid())
924 Loc = D.getSourceRange().getBegin();
925
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000926 Expr *BitWidth = static_cast<Expr*>(BW);
927 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000928
John McCallb1cd7da2010-06-04 08:34:12 +0000929 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000930 assert(!DS.isFriendSpecified());
931
John McCallb1cd7da2010-06-04 08:34:12 +0000932 bool isFunc = false;
933 if (D.isFunctionDeclarator())
934 isFunc = true;
935 else if (D.getNumTypeObjects() == 0 &&
936 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000937 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000938 isFunc = TDType->isFunctionType();
939 }
940
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000941 // C++ 9.2p6: A member shall not be declared to have automatic storage
942 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000943 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
944 // data members and cannot be applied to names declared const or static,
945 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946 switch (DS.getStorageClassSpec()) {
947 case DeclSpec::SCS_unspecified:
948 case DeclSpec::SCS_typedef:
949 case DeclSpec::SCS_static:
950 // FALL THROUGH.
951 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000952 case DeclSpec::SCS_mutable:
953 if (isFunc) {
954 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000955 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000956 else
Chris Lattner3b054132008-11-19 05:08:23 +0000957 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000958
Sebastian Redl8071edb2008-11-17 23:24:37 +0000959 // FIXME: It would be nicer if the keyword was ignored only for this
960 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000961 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000962 }
963 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000964 default:
965 if (DS.getStorageClassSpecLoc().isValid())
966 Diag(DS.getStorageClassSpecLoc(),
967 diag::err_storageclass_invalid_for_member);
968 else
969 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
970 D.getMutableDeclSpec().ClearStorageClassSpecs();
971 }
972
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000973 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
974 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000975 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000976
977 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000978 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000979 CXXScopeSpec &SS = D.getCXXScopeSpec();
980
981
982 if (SS.isSet() && !SS.isInvalid()) {
983 // The user provided a superfluous scope specifier inside a class
984 // definition:
985 //
986 // class X {
987 // int X::member;
988 // };
989 DeclContext *DC = 0;
990 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
991 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
992 << Name << FixItHint::CreateRemoval(SS.getRange());
993 else
994 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
995 << Name << SS.getRange();
996
997 SS.clear();
998 }
999
Douglas Gregor3447e762009-08-20 22:52:58 +00001000 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001001 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001002 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1003 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001004 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001005 } else {
John McCall48871652010-08-21 09:40:31 +00001006 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001007 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001008 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001009 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001010
1011 // Non-instance-fields can't have a bitfield.
1012 if (BitWidth) {
1013 if (Member->isInvalidDecl()) {
1014 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001015 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001016 // C++ 9.6p3: A bit-field shall not be a static member.
1017 // "static member 'A' cannot be a bit-field"
1018 Diag(Loc, diag::err_static_not_bitfield)
1019 << Name << BitWidth->getSourceRange();
1020 } else if (isa<TypedefDecl>(Member)) {
1021 // "typedef member 'x' cannot be a bit-field"
1022 Diag(Loc, diag::err_typedef_not_bitfield)
1023 << Name << BitWidth->getSourceRange();
1024 } else {
1025 // A function typedef ("typedef int f(); f a;").
1026 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1027 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001028 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001029 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattnerd26760a2009-03-05 23:01:03 +00001032 BitWidth = 0;
1033 Member->setInvalidDecl();
1034 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001035
1036 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001037
Douglas Gregor3447e762009-08-20 22:52:58 +00001038 // If we have declared a member function template, set the access of the
1039 // templated declaration as well.
1040 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1041 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001042 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001043
Anders Carlsson13a69102011-01-20 04:34:22 +00001044 if (VS.isOverrideSpecified()) {
1045 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1046 if (!MD || !MD->isVirtual()) {
1047 Diag(Member->getLocStart(),
1048 diag::override_keyword_only_allowed_on_virtual_member_functions)
1049 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001050 } else
1051 MD->setIsMarkedOverride(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001052 }
1053 if (VS.isFinalSpecified()) {
1054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1055 if (!MD || !MD->isVirtual()) {
1056 Diag(Member->getLocStart(),
1057 diag::override_keyword_only_allowed_on_virtual_member_functions)
1058 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001059 } else
1060 MD->setIsMarkedFinal(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001061 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001062
Anders Carlssonc87f8612011-01-20 06:29:02 +00001063 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001064
Douglas Gregor92751d42008-11-17 22:58:34 +00001065 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001066
Douglas Gregor0c880302009-03-11 23:00:04 +00001067 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001068 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001069 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001070 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001071
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001072 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001073 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001074 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001075 }
John McCall48871652010-08-21 09:40:31 +00001076 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001077}
1078
Douglas Gregor15e77a22009-12-31 09:10:24 +00001079/// \brief Find the direct and/or virtual base specifiers that
1080/// correspond to the given base type, for use in base initialization
1081/// within a constructor.
1082static bool FindBaseInitializer(Sema &SemaRef,
1083 CXXRecordDecl *ClassDecl,
1084 QualType BaseType,
1085 const CXXBaseSpecifier *&DirectBaseSpec,
1086 const CXXBaseSpecifier *&VirtualBaseSpec) {
1087 // First, check for a direct base class.
1088 DirectBaseSpec = 0;
1089 for (CXXRecordDecl::base_class_const_iterator Base
1090 = ClassDecl->bases_begin();
1091 Base != ClassDecl->bases_end(); ++Base) {
1092 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1093 // We found a direct base of this type. That's what we're
1094 // initializing.
1095 DirectBaseSpec = &*Base;
1096 break;
1097 }
1098 }
1099
1100 // Check for a virtual base class.
1101 // FIXME: We might be able to short-circuit this if we know in advance that
1102 // there are no virtual bases.
1103 VirtualBaseSpec = 0;
1104 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1105 // We haven't found a base yet; search the class hierarchy for a
1106 // virtual base class.
1107 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1108 /*DetectVirtual=*/false);
1109 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1110 BaseType, Paths)) {
1111 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1112 Path != Paths.end(); ++Path) {
1113 if (Path->back().Base->isVirtual()) {
1114 VirtualBaseSpec = Path->back().Base;
1115 break;
1116 }
1117 }
1118 }
1119 }
1120
1121 return DirectBaseSpec || VirtualBaseSpec;
1122}
1123
Douglas Gregore8381c02008-11-05 04:29:56 +00001124/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001125MemInitResult
John McCall48871652010-08-21 09:40:31 +00001126Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001127 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001128 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001129 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001130 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001131 SourceLocation IdLoc,
1132 SourceLocation LParenLoc,
1133 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001134 SourceLocation RParenLoc,
1135 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001136 if (!ConstructorD)
1137 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001138
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001139 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001140
1141 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001142 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001143 if (!Constructor) {
1144 // The user wrote a constructor initializer on a function that is
1145 // not a C++ constructor. Ignore the error for now, because we may
1146 // have more member initializers coming; we'll diagnose it just
1147 // once in ActOnMemInitializers.
1148 return true;
1149 }
1150
1151 CXXRecordDecl *ClassDecl = Constructor->getParent();
1152
1153 // C++ [class.base.init]p2:
1154 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001155 // constructor's class and, if not found in that scope, are looked
1156 // up in the scope containing the constructor's definition.
1157 // [Note: if the constructor's class contains a member with the
1158 // same name as a direct or virtual base class of the class, a
1159 // mem-initializer-id naming the member or base class and composed
1160 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001161 // mem-initializer-id for the hidden base class may be specified
1162 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001163 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001164 // Look for a member, first.
1165 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001166 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001167 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001168 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001169 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001170
Douglas Gregor44e7df62011-01-04 00:32:56 +00001171 if (Member) {
1172 if (EllipsisLoc.isValid())
1173 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1174 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1175
Francois Pichetd583da02010-12-04 09:14:42 +00001176 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001177 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001178 }
1179
Francois Pichetd583da02010-12-04 09:14:42 +00001180 // Handle anonymous union case.
1181 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001182 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1183 if (EllipsisLoc.isValid())
1184 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1185 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1186
Francois Pichetd583da02010-12-04 09:14:42 +00001187 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1188 NumArgs, IdLoc,
1189 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001190 }
Francois Pichetd583da02010-12-04 09:14:42 +00001191 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001192 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001193 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001194 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001195 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001196
1197 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001198 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001199 } else {
1200 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1201 LookupParsedName(R, S, &SS);
1202
1203 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1204 if (!TyD) {
1205 if (R.isAmbiguous()) return true;
1206
John McCallda6841b2010-04-09 19:01:14 +00001207 // We don't want access-control diagnostics here.
1208 R.suppressDiagnostics();
1209
Douglas Gregora3b624a2010-01-19 06:46:48 +00001210 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1211 bool NotUnknownSpecialization = false;
1212 DeclContext *DC = computeDeclContext(SS, false);
1213 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1214 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1215
1216 if (!NotUnknownSpecialization) {
1217 // When the scope specifier can refer to a member of an unknown
1218 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001219 BaseType = CheckTypenameType(ETK_None,
1220 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001221 *MemberOrBase, SourceLocation(),
1222 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001223 if (BaseType.isNull())
1224 return true;
1225
Douglas Gregora3b624a2010-01-19 06:46:48 +00001226 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001227 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001228 }
1229 }
1230
Douglas Gregor15e77a22009-12-31 09:10:24 +00001231 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001232 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001233 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1234 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001235 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001236 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001237 // We have found a non-static data member with a similar
1238 // name to what was typed; complain and initialize that
1239 // member.
1240 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1241 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001242 << FixItHint::CreateReplacement(R.getNameLoc(),
1243 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001244 Diag(Member->getLocation(), diag::note_previous_decl)
1245 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001246
1247 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1248 LParenLoc, RParenLoc);
1249 }
1250 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1251 const CXXBaseSpecifier *DirectBaseSpec;
1252 const CXXBaseSpecifier *VirtualBaseSpec;
1253 if (FindBaseInitializer(*this, ClassDecl,
1254 Context.getTypeDeclType(Type),
1255 DirectBaseSpec, VirtualBaseSpec)) {
1256 // We have found a direct or virtual base class with a
1257 // similar name to what was typed; complain and initialize
1258 // that base class.
1259 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1260 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001261 << FixItHint::CreateReplacement(R.getNameLoc(),
1262 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001263
1264 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1265 : VirtualBaseSpec;
1266 Diag(BaseSpec->getSourceRange().getBegin(),
1267 diag::note_base_class_specified_here)
1268 << BaseSpec->getType()
1269 << BaseSpec->getSourceRange();
1270
Douglas Gregor15e77a22009-12-31 09:10:24 +00001271 TyD = Type;
1272 }
1273 }
1274 }
1275
Douglas Gregora3b624a2010-01-19 06:46:48 +00001276 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001277 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1278 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1279 return true;
1280 }
John McCallb5a0d312009-12-21 10:41:20 +00001281 }
1282
Douglas Gregora3b624a2010-01-19 06:46:48 +00001283 if (BaseType.isNull()) {
1284 BaseType = Context.getTypeDeclType(TyD);
1285 if (SS.isSet()) {
1286 NestedNameSpecifier *Qualifier =
1287 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001288
Douglas Gregora3b624a2010-01-19 06:46:48 +00001289 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001290 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001291 }
John McCallb5a0d312009-12-21 10:41:20 +00001292 }
1293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
John McCallbcd03502009-12-07 02:54:59 +00001295 if (!TInfo)
1296 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001297
John McCallbcd03502009-12-07 02:54:59 +00001298 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001299 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001300}
1301
John McCalle22a04a2009-11-04 23:02:40 +00001302/// Checks an initializer expression for use of uninitialized fields, such as
1303/// containing the field that is being initialized. Returns true if there is an
1304/// uninitialized field was used an updates the SourceLocation parameter; false
1305/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001306static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001307 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001308 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001309 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1310
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001311 if (isa<CallExpr>(S)) {
1312 // Do not descend into function calls or constructors, as the use
1313 // of an uninitialized field may be valid. One would have to inspect
1314 // the contents of the function/ctor to determine if it is safe or not.
1315 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1316 // may be safe, depending on what the function/ctor does.
1317 return false;
1318 }
1319 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1320 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001321
1322 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1323 // The member expression points to a static data member.
1324 assert(VD->isStaticDataMember() &&
1325 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001326 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001327 return false;
1328 }
1329
1330 if (isa<EnumConstantDecl>(RhsField)) {
1331 // The member expression points to an enum.
1332 return false;
1333 }
1334
John McCalle22a04a2009-11-04 23:02:40 +00001335 if (RhsField == LhsField) {
1336 // Initializing a field with itself. Throw a warning.
1337 // But wait; there are exceptions!
1338 // Exception #1: The field may not belong to this record.
1339 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001340 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001341 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1342 // Even though the field matches, it does not belong to this record.
1343 return false;
1344 }
1345 // None of the exceptions triggered; return true to indicate an
1346 // uninitialized field was used.
1347 *L = ME->getMemberLoc();
1348 return true;
1349 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001350 } else if (isa<SizeOfAlignOfExpr>(S)) {
1351 // sizeof/alignof doesn't reference contents, do not warn.
1352 return false;
1353 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1354 // address-of doesn't reference contents (the pointer may be dereferenced
1355 // in the same expression but it would be rare; and weird).
1356 if (UOE->getOpcode() == UO_AddrOf)
1357 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001358 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001359 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1360 it != e; ++it) {
1361 if (!*it) {
1362 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001363 continue;
1364 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001365 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1366 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001367 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001368 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001369}
1370
John McCallfaf5fb42010-08-26 23:41:50 +00001371MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001372Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001373 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001374 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001375 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001376 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1377 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1378 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001379 "Member must be a FieldDecl or IndirectFieldDecl");
1380
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001381 if (Member->isInvalidDecl())
1382 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001383
John McCalle22a04a2009-11-04 23:02:40 +00001384 // Diagnose value-uses of fields to initialize themselves, e.g.
1385 // foo(foo)
1386 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001387 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001388 for (unsigned i = 0; i < NumArgs; ++i) {
1389 SourceLocation L;
1390 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1391 // FIXME: Return true in the case when other fields are used before being
1392 // uninitialized. For example, let this field be the i'th field. When
1393 // initializing the i'th field, throw a warning if any of the >= i'th
1394 // fields are used, as they are not yet initialized.
1395 // Right now we are only handling the case where the i'th field uses
1396 // itself in its initializer.
1397 Diag(L, diag::warn_field_is_uninit);
1398 }
1399 }
1400
Eli Friedman8e1433b2009-07-29 19:44:27 +00001401 bool HasDependentArg = false;
1402 for (unsigned i = 0; i < NumArgs; i++)
1403 HasDependentArg |= Args[i]->isTypeDependent();
1404
Chandler Carruthd44c3102010-12-06 09:23:57 +00001405 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001406 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001407 // Can't check initialization for a member of dependent type or when
1408 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001409 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1410 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001411
1412 // Erase any temporaries within this evaluation context; we're not
1413 // going to track them in the AST, since we'll be rebuilding the
1414 // ASTs during template instantiation.
1415 ExprTemporaries.erase(
1416 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1417 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001418 } else {
1419 // Initialize the member.
1420 InitializedEntity MemberEntity =
1421 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1422 : InitializedEntity::InitializeMember(IndirectMember, 0);
1423 InitializationKind Kind =
1424 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001425
Chandler Carruthd44c3102010-12-06 09:23:57 +00001426 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1427
1428 ExprResult MemberInit =
1429 InitSeq.Perform(*this, MemberEntity, Kind,
1430 MultiExprArg(*this, Args, NumArgs), 0);
1431 if (MemberInit.isInvalid())
1432 return true;
1433
1434 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1435
1436 // C++0x [class.base.init]p7:
1437 // The initialization of each base and member constitutes a
1438 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001439 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001440 if (MemberInit.isInvalid())
1441 return true;
1442
1443 // If we are in a dependent context, template instantiation will
1444 // perform this type-checking again. Just save the arguments that we
1445 // received in a ParenListExpr.
1446 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1447 // of the information that we have about the member
1448 // initializer. However, deconstructing the ASTs is a dicey process,
1449 // and this approach is far more likely to get the corner cases right.
1450 if (CurContext->isDependentContext())
1451 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1452 RParenLoc);
1453 else
1454 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001455 }
1456
Chandler Carruthd44c3102010-12-06 09:23:57 +00001457 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001458 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001459 IdLoc, LParenLoc, Init,
1460 RParenLoc);
1461 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001462 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001463 IdLoc, LParenLoc, Init,
1464 RParenLoc);
1465 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001466}
1467
John McCallfaf5fb42010-08-26 23:41:50 +00001468MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001469Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1470 Expr **Args, unsigned NumArgs,
1471 SourceLocation LParenLoc,
1472 SourceLocation RParenLoc,
1473 CXXRecordDecl *ClassDecl,
1474 SourceLocation EllipsisLoc) {
1475 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1476 if (!LangOpts.CPlusPlus0x)
1477 return Diag(Loc, diag::err_delegation_0x_only)
1478 << TInfo->getTypeLoc().getLocalSourceRange();
1479
1480 return Diag(Loc, diag::err_delegation_unimplemented)
1481 << TInfo->getTypeLoc().getLocalSourceRange();
1482}
1483
1484MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001485Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001486 Expr **Args, unsigned NumArgs,
1487 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001488 CXXRecordDecl *ClassDecl,
1489 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001490 bool HasDependentArg = false;
1491 for (unsigned i = 0; i < NumArgs; i++)
1492 HasDependentArg |= Args[i]->isTypeDependent();
1493
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001494 SourceLocation BaseLoc
1495 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1496
1497 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1498 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1499 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1500
1501 // C++ [class.base.init]p2:
1502 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001503 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001504 // of that class, the mem-initializer is ill-formed. A
1505 // mem-initializer-list can initialize a base class using any
1506 // name that denotes that base class type.
1507 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1508
Douglas Gregor44e7df62011-01-04 00:32:56 +00001509 if (EllipsisLoc.isValid()) {
1510 // This is a pack expansion.
1511 if (!BaseType->containsUnexpandedParameterPack()) {
1512 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1513 << SourceRange(BaseLoc, RParenLoc);
1514
1515 EllipsisLoc = SourceLocation();
1516 }
1517 } else {
1518 // Check for any unexpanded parameter packs.
1519 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1520 return true;
1521
1522 for (unsigned I = 0; I != NumArgs; ++I)
1523 if (DiagnoseUnexpandedParameterPack(Args[I]))
1524 return true;
1525 }
1526
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001527 // Check for direct and virtual base classes.
1528 const CXXBaseSpecifier *DirectBaseSpec = 0;
1529 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1530 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001531 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1532 BaseType))
1533 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1534 LParenLoc, RParenLoc, ClassDecl,
1535 EllipsisLoc);
1536
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001537 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1538 VirtualBaseSpec);
1539
1540 // C++ [base.class.init]p2:
1541 // Unless the mem-initializer-id names a nonstatic data member of the
1542 // constructor's class or a direct or virtual base of that class, the
1543 // mem-initializer is ill-formed.
1544 if (!DirectBaseSpec && !VirtualBaseSpec) {
1545 // If the class has any dependent bases, then it's possible that
1546 // one of those types will resolve to the same type as
1547 // BaseType. Therefore, just treat this as a dependent base
1548 // class initialization. FIXME: Should we try to check the
1549 // initialization anyway? It seems odd.
1550 if (ClassDecl->hasAnyDependentBases())
1551 Dependent = true;
1552 else
1553 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1554 << BaseType << Context.getTypeDeclType(ClassDecl)
1555 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1556 }
1557 }
1558
1559 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001560 // Can't check initialization for a base of dependent type or when
1561 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001562 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001563 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1564 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001565
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001566 // Erase any temporaries within this evaluation context; we're not
1567 // going to track them in the AST, since we'll be rebuilding the
1568 // ASTs during template instantiation.
1569 ExprTemporaries.erase(
1570 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1571 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001572
Alexis Hunt1d792652011-01-08 20:30:50 +00001573 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001574 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001575 LParenLoc,
1576 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001577 RParenLoc,
1578 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001579 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001580
1581 // C++ [base.class.init]p2:
1582 // If a mem-initializer-id is ambiguous because it designates both
1583 // a direct non-virtual base class and an inherited virtual base
1584 // class, the mem-initializer is ill-formed.
1585 if (DirectBaseSpec && VirtualBaseSpec)
1586 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001587 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001588
1589 CXXBaseSpecifier *BaseSpec
1590 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1591 if (!BaseSpec)
1592 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1593
1594 // Initialize the base.
1595 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001596 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001597 InitializationKind Kind =
1598 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1599
1600 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1601
John McCalldadc5752010-08-24 06:29:42 +00001602 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001603 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001604 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001605 if (BaseInit.isInvalid())
1606 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001607
1608 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001609
1610 // C++0x [class.base.init]p7:
1611 // The initialization of each base and member constitutes a
1612 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001613 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001614 if (BaseInit.isInvalid())
1615 return true;
1616
1617 // If we are in a dependent context, template instantiation will
1618 // perform this type-checking again. Just save the arguments that we
1619 // received in a ParenListExpr.
1620 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1621 // of the information that we have about the base
1622 // initializer. However, deconstructing the ASTs is a dicey process,
1623 // and this approach is far more likely to get the corner cases right.
1624 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001625 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001626 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1627 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001628 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001629 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001630 LParenLoc,
1631 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001632 RParenLoc,
1633 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001634 }
1635
Alexis Hunt1d792652011-01-08 20:30:50 +00001636 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001637 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001638 LParenLoc,
1639 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001640 RParenLoc,
1641 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001642}
1643
Anders Carlsson1b00e242010-04-23 03:10:23 +00001644/// ImplicitInitializerKind - How an implicit base or member initializer should
1645/// initialize its base or member.
1646enum ImplicitInitializerKind {
1647 IIK_Default,
1648 IIK_Copy,
1649 IIK_Move
1650};
1651
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001652static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001653BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001654 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001655 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001656 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001657 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001658 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001659 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1660 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001661
John McCalldadc5752010-08-24 06:29:42 +00001662 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001663
1664 switch (ImplicitInitKind) {
1665 case IIK_Default: {
1666 InitializationKind InitKind
1667 = InitializationKind::CreateDefault(Constructor->getLocation());
1668 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1669 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001670 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001671 break;
1672 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001673
Anders Carlsson1b00e242010-04-23 03:10:23 +00001674 case IIK_Copy: {
1675 ParmVarDecl *Param = Constructor->getParamDecl(0);
1676 QualType ParamType = Param->getType().getNonReferenceType();
1677
1678 Expr *CopyCtorArg =
1679 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001680 Constructor->getLocation(), ParamType,
1681 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001682
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001683 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001684 QualType ArgTy =
1685 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1686 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001687
1688 CXXCastPath BasePath;
1689 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001690 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001691 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001692 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001693
Anders Carlsson1b00e242010-04-23 03:10:23 +00001694 InitializationKind InitKind
1695 = InitializationKind::CreateDirect(Constructor->getLocation(),
1696 SourceLocation(), SourceLocation());
1697 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1698 &CopyCtorArg, 1);
1699 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001700 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001701 break;
1702 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001703
Anders Carlsson1b00e242010-04-23 03:10:23 +00001704 case IIK_Move:
1705 assert(false && "Unhandled initializer kind!");
1706 }
John McCallb268a282010-08-23 23:25:46 +00001707
Douglas Gregora40433a2010-12-07 00:41:46 +00001708 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001709 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001710 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001711
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001712 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001713 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001714 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1715 SourceLocation()),
1716 BaseSpec->isVirtual(),
1717 SourceLocation(),
1718 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001719 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001720 SourceLocation());
1721
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001722 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001723}
1724
Anders Carlsson3c1db572010-04-23 02:15:47 +00001725static bool
1726BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001727 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001728 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001729 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001730 if (Field->isInvalidDecl())
1731 return true;
1732
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001733 SourceLocation Loc = Constructor->getLocation();
1734
Anders Carlsson423f5d82010-04-23 16:04:08 +00001735 if (ImplicitInitKind == IIK_Copy) {
1736 ParmVarDecl *Param = Constructor->getParamDecl(0);
1737 QualType ParamType = Param->getType().getNonReferenceType();
1738
1739 Expr *MemberExprBase =
1740 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001741 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001742
1743 // Build a reference to this field within the parameter.
1744 CXXScopeSpec SS;
1745 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1746 Sema::LookupMemberName);
1747 MemberLookup.addDecl(Field, AS_public);
1748 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001749 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001750 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001751 ParamType, Loc,
1752 /*IsArrow=*/false,
1753 SS,
1754 /*FirstQualifierInScope=*/0,
1755 MemberLookup,
1756 /*TemplateArgs=*/0);
1757 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001758 return true;
1759
Douglas Gregor94f9a482010-05-05 05:51:00 +00001760 // When the field we are copying is an array, create index variables for
1761 // each dimension of the array. We use these index variables to subscript
1762 // the source array, and other clients (e.g., CodeGen) will perform the
1763 // necessary iteration with these index variables.
1764 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1765 QualType BaseType = Field->getType();
1766 QualType SizeType = SemaRef.Context.getSizeType();
1767 while (const ConstantArrayType *Array
1768 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1769 // Create the iteration variable for this array index.
1770 IdentifierInfo *IterationVarName = 0;
1771 {
1772 llvm::SmallString<8> Str;
1773 llvm::raw_svector_ostream OS(Str);
1774 OS << "__i" << IndexVariables.size();
1775 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1776 }
1777 VarDecl *IterationVar
1778 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1779 IterationVarName, SizeType,
1780 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001781 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001782 IndexVariables.push_back(IterationVar);
1783
1784 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001785 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001786 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001787 assert(!IterationVarRef.isInvalid() &&
1788 "Reference to invented variable cannot fail!");
1789
1790 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001791 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001792 Loc,
John McCallb268a282010-08-23 23:25:46 +00001793 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001794 Loc);
1795 if (CopyCtorArg.isInvalid())
1796 return true;
1797
1798 BaseType = Array->getElementType();
1799 }
1800
1801 // Construct the entity that we will be initializing. For an array, this
1802 // will be first element in the array, which may require several levels
1803 // of array-subscript entities.
1804 llvm::SmallVector<InitializedEntity, 4> Entities;
1805 Entities.reserve(1 + IndexVariables.size());
1806 Entities.push_back(InitializedEntity::InitializeMember(Field));
1807 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1808 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1809 0,
1810 Entities.back()));
1811
1812 // Direct-initialize to use the copy constructor.
1813 InitializationKind InitKind =
1814 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1815
1816 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1817 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1818 &CopyCtorArgE, 1);
1819
John McCalldadc5752010-08-24 06:29:42 +00001820 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001821 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001822 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001823 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001824 if (MemberInit.isInvalid())
1825 return true;
1826
1827 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001828 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001829 MemberInit.takeAs<Expr>(), Loc,
1830 IndexVariables.data(),
1831 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001832 return false;
1833 }
1834
Anders Carlsson423f5d82010-04-23 16:04:08 +00001835 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1836
Anders Carlsson3c1db572010-04-23 02:15:47 +00001837 QualType FieldBaseElementType =
1838 SemaRef.Context.getBaseElementType(Field->getType());
1839
Anders Carlsson3c1db572010-04-23 02:15:47 +00001840 if (FieldBaseElementType->isRecordType()) {
1841 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001842 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001843 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001844
1845 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001846 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001847 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001848
Douglas Gregora40433a2010-12-07 00:41:46 +00001849 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001850 if (MemberInit.isInvalid())
1851 return true;
1852
1853 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001854 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001855 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001856 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001857 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001858 return false;
1859 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001860
1861 if (FieldBaseElementType->isReferenceType()) {
1862 SemaRef.Diag(Constructor->getLocation(),
1863 diag::err_uninitialized_member_in_ctor)
1864 << (int)Constructor->isImplicit()
1865 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1866 << 0 << Field->getDeclName();
1867 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1868 return true;
1869 }
1870
1871 if (FieldBaseElementType.isConstQualified()) {
1872 SemaRef.Diag(Constructor->getLocation(),
1873 diag::err_uninitialized_member_in_ctor)
1874 << (int)Constructor->isImplicit()
1875 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1876 << 1 << Field->getDeclName();
1877 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1878 return true;
1879 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001880
1881 // Nothing to initialize.
1882 CXXMemberInit = 0;
1883 return false;
1884}
John McCallbc83b3f2010-05-20 23:23:51 +00001885
1886namespace {
1887struct BaseAndFieldInfo {
1888 Sema &S;
1889 CXXConstructorDecl *Ctor;
1890 bool AnyErrorsInInits;
1891 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001892 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1893 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001894
1895 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1896 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1897 // FIXME: Handle implicit move constructors.
1898 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1899 IIK = IIK_Copy;
1900 else
1901 IIK = IIK_Default;
1902 }
1903};
1904}
1905
1906static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1907 FieldDecl *Top, FieldDecl *Field) {
1908
Chandler Carruth139e9622010-06-30 02:59:29 +00001909 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001910 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001911 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001912 return false;
1913 }
1914
1915 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1916 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1917 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001918 CXXRecordDecl *FieldClassDecl
1919 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001920
1921 // Even though union members never have non-trivial default
1922 // constructions in C++03, we still build member initializers for aggregate
1923 // record types which can be union members, and C++0x allows non-trivial
1924 // default constructors for union members, so we ensure that only one
1925 // member is initialized for these.
1926 if (FieldClassDecl->isUnion()) {
1927 // First check for an explicit initializer for one field.
1928 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1929 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001930 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001931 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001932
1933 // Once we've initialized a field of an anonymous union, the union
1934 // field in the class is also initialized, so exit immediately.
1935 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001936 } else if ((*FA)->isAnonymousStructOrUnion()) {
1937 if (CollectFieldInitializer(Info, Top, *FA))
1938 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001939 }
1940 }
1941
1942 // Fallthrough and construct a default initializer for the union as
1943 // a whole, which can call its default constructor if such a thing exists
1944 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1945 // behavior going forward with C++0x, when anonymous unions there are
1946 // finalized, we should revisit this.
1947 } else {
1948 // For structs, we simply descend through to initialize all members where
1949 // necessary.
1950 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1951 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1952 if (CollectFieldInitializer(Info, Top, *FA))
1953 return true;
1954 }
1955 }
John McCallbc83b3f2010-05-20 23:23:51 +00001956 }
1957
1958 // Don't try to build an implicit initializer if there were semantic
1959 // errors in any of the initializers (and therefore we might be
1960 // missing some that the user actually wrote).
1961 if (Info.AnyErrorsInInits)
1962 return false;
1963
Alexis Hunt1d792652011-01-08 20:30:50 +00001964 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001965 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1966 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001967
Francois Pichetd583da02010-12-04 09:14:42 +00001968 if (Init)
1969 Info.AllToInit.push_back(Init);
1970
John McCallbc83b3f2010-05-20 23:23:51 +00001971 return false;
1972}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001973
Eli Friedman9cf6b592009-11-09 19:20:36 +00001974bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001975Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1976 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001977 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001978 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001979 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001980 // Just store the initializers as written, they will be checked during
1981 // instantiation.
1982 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001983 Constructor->setNumCtorInitializers(NumInitializers);
1984 CXXCtorInitializer **baseOrMemberInitializers =
1985 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001986 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001987 NumInitializers * sizeof(CXXCtorInitializer*));
1988 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001989 }
1990
1991 return false;
1992 }
1993
John McCallbc83b3f2010-05-20 23:23:51 +00001994 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001995
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001996 // We need to build the initializer AST according to order of construction
1997 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001998 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001999 if (!ClassDecl)
2000 return true;
2001
Eli Friedman9cf6b592009-11-09 19:20:36 +00002002 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002003
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002004 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002005 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002006
2007 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002008 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002009 else
Francois Pichetd583da02010-12-04 09:14:42 +00002010 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002011 }
2012
Anders Carlsson43c64af2010-04-21 19:52:01 +00002013 // Keep track of the direct virtual bases.
2014 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2015 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2016 E = ClassDecl->bases_end(); I != E; ++I) {
2017 if (I->isVirtual())
2018 DirectVBases.insert(I);
2019 }
2020
Anders Carlssondb0a9652010-04-02 06:26:44 +00002021 // Push virtual bases before others.
2022 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2023 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2024
Alexis Hunt1d792652011-01-08 20:30:50 +00002025 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002026 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2027 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002028 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002029 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002030 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002031 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002032 VBase, IsInheritedVirtualBase,
2033 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002034 HadError = true;
2035 continue;
2036 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002037
John McCallbc83b3f2010-05-20 23:23:51 +00002038 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002039 }
2040 }
Mike Stump11289f42009-09-09 15:08:12 +00002041
John McCallbc83b3f2010-05-20 23:23:51 +00002042 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002043 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2044 E = ClassDecl->bases_end(); Base != E; ++Base) {
2045 // Virtuals are in the virtual base list and already constructed.
2046 if (Base->isVirtual())
2047 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002048
Alexis Hunt1d792652011-01-08 20:30:50 +00002049 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002050 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2051 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002052 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002053 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002054 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002055 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002056 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002057 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002058 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002059 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002060
John McCallbc83b3f2010-05-20 23:23:51 +00002061 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002062 }
2063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
John McCallbc83b3f2010-05-20 23:23:51 +00002065 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002066 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002067 E = ClassDecl->field_end(); Field != E; ++Field) {
2068 if ((*Field)->getType()->isIncompleteArrayType()) {
2069 assert(ClassDecl->hasFlexibleArrayMember() &&
2070 "Incomplete array type is not valid");
2071 continue;
2072 }
John McCallbc83b3f2010-05-20 23:23:51 +00002073 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002074 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002075 }
Mike Stump11289f42009-09-09 15:08:12 +00002076
John McCallbc83b3f2010-05-20 23:23:51 +00002077 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002078 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002079 Constructor->setNumCtorInitializers(NumInitializers);
2080 CXXCtorInitializer **baseOrMemberInitializers =
2081 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002082 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002083 NumInitializers * sizeof(CXXCtorInitializer*));
2084 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002085
John McCalla6309952010-03-16 21:39:52 +00002086 // Constructors implicitly reference the base and member
2087 // destructors.
2088 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2089 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002090 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002091
2092 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002093}
2094
Eli Friedman952c15d2009-07-21 19:28:10 +00002095static void *GetKeyForTopLevelField(FieldDecl *Field) {
2096 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002097 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002098 if (RT->getDecl()->isAnonymousStructOrUnion())
2099 return static_cast<void *>(RT->getDecl());
2100 }
2101 return static_cast<void *>(Field);
2102}
2103
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002104static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002105 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002106}
2107
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002108static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002109 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002110 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002111 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002112
Eli Friedman952c15d2009-07-21 19:28:10 +00002113 // For fields injected into the class via declaration of an anonymous union,
2114 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002115 FieldDecl *Field = Member->getAnyMember();
2116
John McCall23eebd92010-04-10 09:28:51 +00002117 // If the field is a member of an anonymous struct or union, our key
2118 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002119 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002120 if (RD->isAnonymousStructOrUnion()) {
2121 while (true) {
2122 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2123 if (Parent->isAnonymousStructOrUnion())
2124 RD = Parent;
2125 else
2126 break;
2127 }
2128
Anders Carlsson83ac3122010-03-30 16:19:37 +00002129 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Anders Carlssona942dcd2010-03-30 15:39:27 +00002132 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002133}
2134
Anders Carlssone857b292010-04-02 03:37:03 +00002135static void
2136DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002137 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002138 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002139 unsigned NumInits) {
2140 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002141 return;
Mike Stump11289f42009-09-09 15:08:12 +00002142
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002143 // Don't check initializers order unless the warning is enabled at the
2144 // location of at least one initializer.
2145 bool ShouldCheckOrder = false;
2146 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002147 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002148 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2149 Init->getSourceLocation())
2150 != Diagnostic::Ignored) {
2151 ShouldCheckOrder = true;
2152 break;
2153 }
2154 }
2155 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002156 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002157
John McCallbb7b6582010-04-10 07:37:23 +00002158 // Build the list of bases and members in the order that they'll
2159 // actually be initialized. The explicit initializers should be in
2160 // this same order but may be missing things.
2161 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002163 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2164
John McCallbb7b6582010-04-10 07:37:23 +00002165 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002166 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002167 ClassDecl->vbases_begin(),
2168 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002169 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002170
John McCallbb7b6582010-04-10 07:37:23 +00002171 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002172 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002173 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002174 if (Base->isVirtual())
2175 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002176 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
John McCallbb7b6582010-04-10 07:37:23 +00002179 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002180 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2181 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002182 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002183
John McCallbb7b6582010-04-10 07:37:23 +00002184 unsigned NumIdealInits = IdealInitKeys.size();
2185 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002186
Alexis Hunt1d792652011-01-08 20:30:50 +00002187 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002188 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002189 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002190 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002191
2192 // Scan forward to try to find this initializer in the idealized
2193 // initializers list.
2194 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2195 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002196 break;
John McCallbb7b6582010-04-10 07:37:23 +00002197
2198 // If we didn't find this initializer, it must be because we
2199 // scanned past it on a previous iteration. That can only
2200 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002201 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002202 Sema::SemaDiagnosticBuilder D =
2203 SemaRef.Diag(PrevInit->getSourceLocation(),
2204 diag::warn_initializer_out_of_order);
2205
Francois Pichetd583da02010-12-04 09:14:42 +00002206 if (PrevInit->isAnyMemberInitializer())
2207 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002208 else
2209 D << 1 << PrevInit->getBaseClassInfo()->getType();
2210
Francois Pichetd583da02010-12-04 09:14:42 +00002211 if (Init->isAnyMemberInitializer())
2212 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002213 else
2214 D << 1 << Init->getBaseClassInfo()->getType();
2215
2216 // Move back to the initializer's location in the ideal list.
2217 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2218 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002219 break;
John McCallbb7b6582010-04-10 07:37:23 +00002220
2221 assert(IdealIndex != NumIdealInits &&
2222 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002223 }
John McCallbb7b6582010-04-10 07:37:23 +00002224
2225 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002226 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002227}
2228
John McCall23eebd92010-04-10 09:28:51 +00002229namespace {
2230bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002231 CXXCtorInitializer *Init,
2232 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002233 if (!PrevInit) {
2234 PrevInit = Init;
2235 return false;
2236 }
2237
2238 if (FieldDecl *Field = Init->getMember())
2239 S.Diag(Init->getSourceLocation(),
2240 diag::err_multiple_mem_initialization)
2241 << Field->getDeclName()
2242 << Init->getSourceRange();
2243 else {
John McCall424cec92011-01-19 06:33:43 +00002244 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002245 assert(BaseClass && "neither field nor base");
2246 S.Diag(Init->getSourceLocation(),
2247 diag::err_multiple_base_initialization)
2248 << QualType(BaseClass, 0)
2249 << Init->getSourceRange();
2250 }
2251 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2252 << 0 << PrevInit->getSourceRange();
2253
2254 return true;
2255}
2256
Alexis Hunt1d792652011-01-08 20:30:50 +00002257typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002258typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2259
2260bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002261 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002262 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002263 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002264 RecordDecl *Parent = Field->getParent();
2265 if (!Parent->isAnonymousStructOrUnion())
2266 return false;
2267
2268 NamedDecl *Child = Field;
2269 do {
2270 if (Parent->isUnion()) {
2271 UnionEntry &En = Unions[Parent];
2272 if (En.first && En.first != Child) {
2273 S.Diag(Init->getSourceLocation(),
2274 diag::err_multiple_mem_union_initialization)
2275 << Field->getDeclName()
2276 << Init->getSourceRange();
2277 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2278 << 0 << En.second->getSourceRange();
2279 return true;
2280 } else if (!En.first) {
2281 En.first = Child;
2282 En.second = Init;
2283 }
2284 }
2285
2286 Child = Parent;
2287 Parent = cast<RecordDecl>(Parent->getDeclContext());
2288 } while (Parent->isAnonymousStructOrUnion());
2289
2290 return false;
2291}
2292}
2293
Anders Carlssone857b292010-04-02 03:37:03 +00002294/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002295void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002296 SourceLocation ColonLoc,
2297 MemInitTy **meminits, unsigned NumMemInits,
2298 bool AnyErrors) {
2299 if (!ConstructorDecl)
2300 return;
2301
2302 AdjustDeclIfTemplate(ConstructorDecl);
2303
2304 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002305 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002306
2307 if (!Constructor) {
2308 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2309 return;
2310 }
2311
Alexis Hunt1d792652011-01-08 20:30:50 +00002312 CXXCtorInitializer **MemInits =
2313 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002314
2315 // Mapping for the duplicate initializers check.
2316 // For member initializers, this is keyed with a FieldDecl*.
2317 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002318 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002319
2320 // Mapping for the inconsistent anonymous-union initializers check.
2321 RedundantUnionMap MemberUnions;
2322
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002323 bool HadError = false;
2324 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002325 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002326
Abramo Bagnara341d7832010-05-26 18:09:23 +00002327 // Set the source order index.
2328 Init->setSourceOrder(i);
2329
Francois Pichetd583da02010-12-04 09:14:42 +00002330 if (Init->isAnyMemberInitializer()) {
2331 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002332 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2333 CheckRedundantUnionInit(*this, Init, MemberUnions))
2334 HadError = true;
2335 } else {
2336 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2337 if (CheckRedundantInit(*this, Init, Members[Key]))
2338 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002339 }
Anders Carlssone857b292010-04-02 03:37:03 +00002340 }
2341
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002342 if (HadError)
2343 return;
2344
Anders Carlssone857b292010-04-02 03:37:03 +00002345 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002346
Alexis Hunt1d792652011-01-08 20:30:50 +00002347 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002348}
2349
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002350void
John McCalla6309952010-03-16 21:39:52 +00002351Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2352 CXXRecordDecl *ClassDecl) {
2353 // Ignore dependent contexts.
2354 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002355 return;
John McCall1064d7e2010-03-16 05:22:47 +00002356
2357 // FIXME: all the access-control diagnostics are positioned on the
2358 // field/base declaration. That's probably good; that said, the
2359 // user might reasonably want to know why the destructor is being
2360 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002361
Anders Carlssondee9a302009-11-17 04:44:12 +00002362 // Non-static data members.
2363 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2364 E = ClassDecl->field_end(); I != E; ++I) {
2365 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002366 if (Field->isInvalidDecl())
2367 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002368 QualType FieldType = Context.getBaseElementType(Field->getType());
2369
2370 const RecordType* RT = FieldType->getAs<RecordType>();
2371 if (!RT)
2372 continue;
2373
2374 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2375 if (FieldClassDecl->hasTrivialDestructor())
2376 continue;
2377
Douglas Gregore71edda2010-07-01 22:47:18 +00002378 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002379 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002380 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002381 << Field->getDeclName()
2382 << FieldType);
2383
John McCalla6309952010-03-16 21:39:52 +00002384 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002385 }
2386
John McCall1064d7e2010-03-16 05:22:47 +00002387 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2388
Anders Carlssondee9a302009-11-17 04:44:12 +00002389 // Bases.
2390 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2391 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002392 // Bases are always records in a well-formed non-dependent class.
2393 const RecordType *RT = Base->getType()->getAs<RecordType>();
2394
2395 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002396 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002397 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002398
2399 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002400 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002401 if (BaseClassDecl->hasTrivialDestructor())
2402 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002403
Douglas Gregore71edda2010-07-01 22:47:18 +00002404 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002405
2406 // FIXME: caret should be on the start of the class name
2407 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002408 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002409 << Base->getType()
2410 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002411
John McCalla6309952010-03-16 21:39:52 +00002412 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002413 }
2414
2415 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002416 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2417 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002418
2419 // Bases are always records in a well-formed non-dependent class.
2420 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2421
2422 // Ignore direct virtual bases.
2423 if (DirectVirtualBases.count(RT))
2424 continue;
2425
Anders Carlssondee9a302009-11-17 04:44:12 +00002426 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002427 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002428 if (BaseClassDecl->hasTrivialDestructor())
2429 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002430
Douglas Gregore71edda2010-07-01 22:47:18 +00002431 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002432 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002433 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002434 << VBase->getType());
2435
John McCalla6309952010-03-16 21:39:52 +00002436 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002437 }
2438}
2439
John McCall48871652010-08-21 09:40:31 +00002440void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002441 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002442 return;
Mike Stump11289f42009-09-09 15:08:12 +00002443
Mike Stump11289f42009-09-09 15:08:12 +00002444 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002445 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002446 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002447}
2448
Mike Stump11289f42009-09-09 15:08:12 +00002449bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002450 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002451 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002452 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002453 else
John McCall02db245d2010-08-18 09:41:07 +00002454 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002455}
2456
Anders Carlssoneabf7702009-08-27 00:13:57 +00002457bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002458 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002459 if (!getLangOptions().CPlusPlus)
2460 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002461
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002462 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002463 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002465 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002466 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002467 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002468 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002469
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002470 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002471 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002472 }
Mike Stump11289f42009-09-09 15:08:12 +00002473
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002474 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002475 if (!RT)
2476 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002477
John McCall67da35c2010-02-04 22:26:26 +00002478 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002479
John McCall02db245d2010-08-18 09:41:07 +00002480 // We can't answer whether something is abstract until it has a
2481 // definition. If it's currently being defined, we'll walk back
2482 // over all the declarations when we have a full definition.
2483 const CXXRecordDecl *Def = RD->getDefinition();
2484 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002485 return false;
2486
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002487 if (!RD->isAbstract())
2488 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002489
Anders Carlssoneabf7702009-08-27 00:13:57 +00002490 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002491 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002492
John McCall02db245d2010-08-18 09:41:07 +00002493 return true;
2494}
2495
2496void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2497 // Check if we've already emitted the list of pure virtual functions
2498 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002499 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002500 return;
Mike Stump11289f42009-09-09 15:08:12 +00002501
Douglas Gregor4165bd62010-03-23 23:47:56 +00002502 CXXFinalOverriderMap FinalOverriders;
2503 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002504
Anders Carlssona2f74f32010-06-03 01:00:02 +00002505 // Keep a set of seen pure methods so we won't diagnose the same method
2506 // more than once.
2507 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2508
Douglas Gregor4165bd62010-03-23 23:47:56 +00002509 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2510 MEnd = FinalOverriders.end();
2511 M != MEnd;
2512 ++M) {
2513 for (OverridingMethods::iterator SO = M->second.begin(),
2514 SOEnd = M->second.end();
2515 SO != SOEnd; ++SO) {
2516 // C++ [class.abstract]p4:
2517 // A class is abstract if it contains or inherits at least one
2518 // pure virtual function for which the final overrider is pure
2519 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002520
Douglas Gregor4165bd62010-03-23 23:47:56 +00002521 //
2522 if (SO->second.size() != 1)
2523 continue;
2524
2525 if (!SO->second.front().Method->isPure())
2526 continue;
2527
Anders Carlssona2f74f32010-06-03 01:00:02 +00002528 if (!SeenPureMethods.insert(SO->second.front().Method))
2529 continue;
2530
Douglas Gregor4165bd62010-03-23 23:47:56 +00002531 Diag(SO->second.front().Method->getLocation(),
2532 diag::note_pure_virtual_function)
2533 << SO->second.front().Method->getDeclName();
2534 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002535 }
2536
2537 if (!PureVirtualClassDiagSet)
2538 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2539 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002540}
2541
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002542namespace {
John McCall02db245d2010-08-18 09:41:07 +00002543struct AbstractUsageInfo {
2544 Sema &S;
2545 CXXRecordDecl *Record;
2546 CanQualType AbstractType;
2547 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002548
John McCall02db245d2010-08-18 09:41:07 +00002549 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2550 : S(S), Record(Record),
2551 AbstractType(S.Context.getCanonicalType(
2552 S.Context.getTypeDeclType(Record))),
2553 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002554
John McCall02db245d2010-08-18 09:41:07 +00002555 void DiagnoseAbstractType() {
2556 if (Invalid) return;
2557 S.DiagnoseAbstractType(Record);
2558 Invalid = true;
2559 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002560
John McCall02db245d2010-08-18 09:41:07 +00002561 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2562};
2563
2564struct CheckAbstractUsage {
2565 AbstractUsageInfo &Info;
2566 const NamedDecl *Ctx;
2567
2568 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2569 : Info(Info), Ctx(Ctx) {}
2570
2571 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2572 switch (TL.getTypeLocClass()) {
2573#define ABSTRACT_TYPELOC(CLASS, PARENT)
2574#define TYPELOC(CLASS, PARENT) \
2575 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2576#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002577 }
John McCall02db245d2010-08-18 09:41:07 +00002578 }
Mike Stump11289f42009-09-09 15:08:12 +00002579
John McCall02db245d2010-08-18 09:41:07 +00002580 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2581 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2582 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2583 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2584 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002585 }
John McCall02db245d2010-08-18 09:41:07 +00002586 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002587
John McCall02db245d2010-08-18 09:41:07 +00002588 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2589 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
John McCall02db245d2010-08-18 09:41:07 +00002592 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2593 // Visit the type parameters from a permissive context.
2594 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2595 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2596 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2597 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2598 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2599 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002600 }
John McCall02db245d2010-08-18 09:41:07 +00002601 }
Mike Stump11289f42009-09-09 15:08:12 +00002602
John McCall02db245d2010-08-18 09:41:07 +00002603 // Visit pointee types from a permissive context.
2604#define CheckPolymorphic(Type) \
2605 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2606 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2607 }
2608 CheckPolymorphic(PointerTypeLoc)
2609 CheckPolymorphic(ReferenceTypeLoc)
2610 CheckPolymorphic(MemberPointerTypeLoc)
2611 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002612
John McCall02db245d2010-08-18 09:41:07 +00002613 /// Handle all the types we haven't given a more specific
2614 /// implementation for above.
2615 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2616 // Every other kind of type that we haven't called out already
2617 // that has an inner type is either (1) sugar or (2) contains that
2618 // inner type in some way as a subobject.
2619 if (TypeLoc Next = TL.getNextTypeLoc())
2620 return Visit(Next, Sel);
2621
2622 // If there's no inner type and we're in a permissive context,
2623 // don't diagnose.
2624 if (Sel == Sema::AbstractNone) return;
2625
2626 // Check whether the type matches the abstract type.
2627 QualType T = TL.getType();
2628 if (T->isArrayType()) {
2629 Sel = Sema::AbstractArrayType;
2630 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002631 }
John McCall02db245d2010-08-18 09:41:07 +00002632 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2633 if (CT != Info.AbstractType) return;
2634
2635 // It matched; do some magic.
2636 if (Sel == Sema::AbstractArrayType) {
2637 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2638 << T << TL.getSourceRange();
2639 } else {
2640 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2641 << Sel << T << TL.getSourceRange();
2642 }
2643 Info.DiagnoseAbstractType();
2644 }
2645};
2646
2647void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2648 Sema::AbstractDiagSelID Sel) {
2649 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2650}
2651
2652}
2653
2654/// Check for invalid uses of an abstract type in a method declaration.
2655static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2656 CXXMethodDecl *MD) {
2657 // No need to do the check on definitions, which require that
2658 // the return/param types be complete.
2659 if (MD->isThisDeclarationADefinition())
2660 return;
2661
2662 // For safety's sake, just ignore it if we don't have type source
2663 // information. This should never happen for non-implicit methods,
2664 // but...
2665 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2666 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2667}
2668
2669/// Check for invalid uses of an abstract type within a class definition.
2670static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2671 CXXRecordDecl *RD) {
2672 for (CXXRecordDecl::decl_iterator
2673 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2674 Decl *D = *I;
2675 if (D->isImplicit()) continue;
2676
2677 // Methods and method templates.
2678 if (isa<CXXMethodDecl>(D)) {
2679 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2680 } else if (isa<FunctionTemplateDecl>(D)) {
2681 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2682 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2683
2684 // Fields and static variables.
2685 } else if (isa<FieldDecl>(D)) {
2686 FieldDecl *FD = cast<FieldDecl>(D);
2687 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2688 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2689 } else if (isa<VarDecl>(D)) {
2690 VarDecl *VD = cast<VarDecl>(D);
2691 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2692 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2693
2694 // Nested classes and class templates.
2695 } else if (isa<CXXRecordDecl>(D)) {
2696 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2697 } else if (isa<ClassTemplateDecl>(D)) {
2698 CheckAbstractClassUsage(Info,
2699 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2700 }
2701 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002702}
2703
Douglas Gregorc99f1552009-12-03 18:33:45 +00002704/// \brief Perform semantic checks on a class definition that has been
2705/// completing, introducing implicitly-declared members, checking for
2706/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002707void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002708 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002709 return;
2710
John McCall02db245d2010-08-18 09:41:07 +00002711 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2712 AbstractUsageInfo Info(*this, Record);
2713 CheckAbstractClassUsage(Info, Record);
2714 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002715
2716 // If this is not an aggregate type and has no user-declared constructor,
2717 // complain about any non-static data members of reference or const scalar
2718 // type, since they will never get initializers.
2719 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2720 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2721 bool Complained = false;
2722 for (RecordDecl::field_iterator F = Record->field_begin(),
2723 FEnd = Record->field_end();
2724 F != FEnd; ++F) {
2725 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002726 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002727 if (!Complained) {
2728 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2729 << Record->getTagKind() << Record;
2730 Complained = true;
2731 }
2732
2733 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2734 << F->getType()->isReferenceType()
2735 << F->getDeclName();
2736 }
2737 }
2738 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002739
2740 if (Record->isDynamicClass())
2741 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002742
2743 if (Record->getIdentifier()) {
2744 // C++ [class.mem]p13:
2745 // If T is the name of a class, then each of the following shall have a
2746 // name different from T:
2747 // - every member of every anonymous union that is a member of class T.
2748 //
2749 // C++ [class.mem]p14:
2750 // In addition, if class T has a user-declared constructor (12.1), every
2751 // non-static data member of class T shall have a name different from T.
2752 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002753 R.first != R.second; ++R.first) {
2754 NamedDecl *D = *R.first;
2755 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2756 isa<IndirectFieldDecl>(D)) {
2757 Diag(D->getLocation(), diag::err_member_name_of_class)
2758 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002759 break;
2760 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002761 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002762 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002763}
2764
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002765void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002766 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002767 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002768 SourceLocation RBrac,
2769 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002770 if (!TagDecl)
2771 return;
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002773 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002774
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002775 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002776 // strict aliasing violation!
2777 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002778 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002779
Douglas Gregor0be31a22010-07-02 17:43:08 +00002780 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002781 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002782}
2783
Douglas Gregor95755162010-07-01 05:10:53 +00002784namespace {
2785 /// \brief Helper class that collects exception specifications for
2786 /// implicitly-declared special member functions.
2787 class ImplicitExceptionSpecification {
2788 ASTContext &Context;
2789 bool AllowsAllExceptions;
2790 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2791 llvm::SmallVector<QualType, 4> Exceptions;
2792
2793 public:
2794 explicit ImplicitExceptionSpecification(ASTContext &Context)
2795 : Context(Context), AllowsAllExceptions(false) { }
2796
2797 /// \brief Whether the special member function should have any
2798 /// exception specification at all.
2799 bool hasExceptionSpecification() const {
2800 return !AllowsAllExceptions;
2801 }
2802
2803 /// \brief Whether the special member function should have a
2804 /// throw(...) exception specification (a Microsoft extension).
2805 bool hasAnyExceptionSpecification() const {
2806 return false;
2807 }
2808
2809 /// \brief The number of exceptions in the exception specification.
2810 unsigned size() const { return Exceptions.size(); }
2811
2812 /// \brief The set of exceptions in the exception specification.
2813 const QualType *data() const { return Exceptions.data(); }
2814
2815 /// \brief Note that
2816 void CalledDecl(CXXMethodDecl *Method) {
2817 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002818 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002819 return;
2820
2821 const FunctionProtoType *Proto
2822 = Method->getType()->getAs<FunctionProtoType>();
2823
2824 // If this function can throw any exceptions, make a note of that.
2825 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2826 AllowsAllExceptions = true;
2827 ExceptionsSeen.clear();
2828 Exceptions.clear();
2829 return;
2830 }
2831
2832 // Record the exceptions in this function's exception specification.
2833 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2834 EEnd = Proto->exception_end();
2835 E != EEnd; ++E)
2836 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2837 Exceptions.push_back(*E);
2838 }
2839 };
2840}
2841
2842
Douglas Gregor05379422008-11-03 17:51:48 +00002843/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2844/// special functions, such as the default constructor, copy
2845/// constructor, or destructor, to the given C++ class (C++
2846/// [special]p1). This routine can only be executed just before the
2847/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002848void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002849 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002850 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002851
Douglas Gregor54be3392010-07-01 17:57:27 +00002852 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002853 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002854
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002855 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2856 ++ASTContext::NumImplicitCopyAssignmentOperators;
2857
2858 // If we have a dynamic class, then the copy assignment operator may be
2859 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2860 // it shows up in the right place in the vtable and that we diagnose
2861 // problems with the implicit exception specification.
2862 if (ClassDecl->isDynamicClass())
2863 DeclareImplicitCopyAssignment(ClassDecl);
2864 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002865
Douglas Gregor7454c562010-07-02 20:37:36 +00002866 if (!ClassDecl->hasUserDeclaredDestructor()) {
2867 ++ASTContext::NumImplicitDestructors;
2868
2869 // If we have a dynamic class, then the destructor may be virtual, so we
2870 // have to declare the destructor immediately. This ensures that, e.g., it
2871 // shows up in the right place in the vtable and that we diagnose problems
2872 // with the implicit exception specification.
2873 if (ClassDecl->isDynamicClass())
2874 DeclareImplicitDestructor(ClassDecl);
2875 }
Douglas Gregor05379422008-11-03 17:51:48 +00002876}
2877
John McCall48871652010-08-21 09:40:31 +00002878void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002879 if (!D)
2880 return;
2881
2882 TemplateParameterList *Params = 0;
2883 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2884 Params = Template->getTemplateParameters();
2885 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2886 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2887 Params = PartialSpec->getTemplateParameters();
2888 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002889 return;
2890
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002891 for (TemplateParameterList::iterator Param = Params->begin(),
2892 ParamEnd = Params->end();
2893 Param != ParamEnd; ++Param) {
2894 NamedDecl *Named = cast<NamedDecl>(*Param);
2895 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002896 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002897 IdResolver.AddDecl(Named);
2898 }
2899 }
2900}
2901
John McCall48871652010-08-21 09:40:31 +00002902void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002903 if (!RecordD) return;
2904 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002905 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002906 PushDeclContext(S, Record);
2907}
2908
John McCall48871652010-08-21 09:40:31 +00002909void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002910 if (!RecordD) return;
2911 PopDeclContext();
2912}
2913
Douglas Gregor4d87df52008-12-16 21:30:33 +00002914/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2915/// parsing a top-level (non-nested) C++ class, and we are now
2916/// parsing those parts of the given Method declaration that could
2917/// not be parsed earlier (C++ [class.mem]p2), such as default
2918/// arguments. This action should enter the scope of the given
2919/// Method declaration as if we had just parsed the qualified method
2920/// name. However, it should not bring the parameters into scope;
2921/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002922void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002923}
2924
2925/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2926/// C++ method declaration. We're (re-)introducing the given
2927/// function parameter into scope for use in parsing later parts of
2928/// the method declaration. For example, we could see an
2929/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002930void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002931 if (!ParamD)
2932 return;
Mike Stump11289f42009-09-09 15:08:12 +00002933
John McCall48871652010-08-21 09:40:31 +00002934 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002935
2936 // If this parameter has an unparsed default argument, clear it out
2937 // to make way for the parsed default argument.
2938 if (Param->hasUnparsedDefaultArg())
2939 Param->setDefaultArg(0);
2940
John McCall48871652010-08-21 09:40:31 +00002941 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002942 if (Param->getDeclName())
2943 IdResolver.AddDecl(Param);
2944}
2945
2946/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2947/// processing the delayed method declaration for Method. The method
2948/// declaration is now considered finished. There may be a separate
2949/// ActOnStartOfFunctionDef action later (not necessarily
2950/// immediately!) for this method, if it was also defined inside the
2951/// class body.
John McCall48871652010-08-21 09:40:31 +00002952void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002953 if (!MethodD)
2954 return;
Mike Stump11289f42009-09-09 15:08:12 +00002955
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002956 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002957
John McCall48871652010-08-21 09:40:31 +00002958 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002959
2960 // Now that we have our default arguments, check the constructor
2961 // again. It could produce additional diagnostics or affect whether
2962 // the class has implicitly-declared destructors, among other
2963 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002964 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2965 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002966
2967 // Check the default arguments, which we may have added.
2968 if (!Method->isInvalidDecl())
2969 CheckCXXDefaultArguments(Method);
2970}
2971
Douglas Gregor831c93f2008-11-05 20:51:48 +00002972/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002973/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002974/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002975/// emit diagnostics and set the invalid bit to true. In any case, the type
2976/// will be updated to reflect a well-formed type for the constructor and
2977/// returned.
2978QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002979 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002980 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002981
2982 // C++ [class.ctor]p3:
2983 // A constructor shall not be virtual (10.3) or static (9.4). A
2984 // constructor can be invoked for a const, volatile or const
2985 // volatile object. A constructor shall not be declared const,
2986 // volatile, or const volatile (9.3.2).
2987 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002988 if (!D.isInvalidType())
2989 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2990 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2991 << SourceRange(D.getIdentifierLoc());
2992 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002993 }
John McCall8e7d6562010-08-26 03:08:43 +00002994 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002995 if (!D.isInvalidType())
2996 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2997 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2998 << SourceRange(D.getIdentifierLoc());
2999 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003000 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003001 }
Mike Stump11289f42009-09-09 15:08:12 +00003002
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003003 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003004 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003005 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003006 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3007 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003008 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003009 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3010 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003011 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003012 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3013 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003014 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003015 }
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregor831c93f2008-11-05 20:51:48 +00003017 // Rebuild the function type "R" without any type qualifiers (in
3018 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003019 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003020 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003021 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3022 return R;
3023
3024 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3025 EPI.TypeQuals = 0;
3026
Chris Lattner38378bf2009-04-25 08:28:21 +00003027 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003028 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003029}
3030
Douglas Gregor4d87df52008-12-16 21:30:33 +00003031/// CheckConstructor - Checks a fully-formed constructor for
3032/// well-formedness, issuing any diagnostics required. Returns true if
3033/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003034void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003035 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003036 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3037 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003038 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003039
3040 // C++ [class.copy]p3:
3041 // A declaration of a constructor for a class X is ill-formed if
3042 // its first parameter is of type (optionally cv-qualified) X and
3043 // either there are no other parameters or else all other
3044 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003045 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003046 ((Constructor->getNumParams() == 1) ||
3047 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003048 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3049 Constructor->getTemplateSpecializationKind()
3050 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003051 QualType ParamType = Constructor->getParamDecl(0)->getType();
3052 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3053 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003054 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003055 const char *ConstRef
3056 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3057 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003058 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003059 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003060
3061 // FIXME: Rather that making the constructor invalid, we should endeavor
3062 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003063 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003064 }
3065 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003066}
3067
John McCalldeb646e2010-08-04 01:04:25 +00003068/// CheckDestructor - Checks a fully-formed destructor definition for
3069/// well-formedness, issuing any diagnostics required. Returns true
3070/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003071bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003072 CXXRecordDecl *RD = Destructor->getParent();
3073
3074 if (Destructor->isVirtual()) {
3075 SourceLocation Loc;
3076
3077 if (!Destructor->isImplicit())
3078 Loc = Destructor->getLocation();
3079 else
3080 Loc = RD->getLocation();
3081
3082 // If we have a virtual destructor, look up the deallocation function
3083 FunctionDecl *OperatorDelete = 0;
3084 DeclarationName Name =
3085 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003086 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003087 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003088
3089 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003090
3091 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003092 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003093
3094 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003095}
3096
Mike Stump11289f42009-09-09 15:08:12 +00003097static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003098FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3099 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3100 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003101 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003102}
3103
Douglas Gregor831c93f2008-11-05 20:51:48 +00003104/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3105/// the well-formednes of the destructor declarator @p D with type @p
3106/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003107/// emit diagnostics and set the declarator to invalid. Even if this happens,
3108/// will be updated to reflect a well-formed type for the destructor and
3109/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003110QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003111 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003112 // C++ [class.dtor]p1:
3113 // [...] A typedef-name that names a class is a class-name
3114 // (7.1.3); however, a typedef-name that names a class shall not
3115 // be used as the identifier in the declarator for a destructor
3116 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003117 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003118 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003119 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003120 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003121
3122 // C++ [class.dtor]p2:
3123 // A destructor is used to destroy objects of its class type. A
3124 // destructor takes no parameters, and no return type can be
3125 // specified for it (not even void). The address of a destructor
3126 // shall not be taken. A destructor shall not be static. A
3127 // destructor can be invoked for a const, volatile or const
3128 // volatile object. A destructor shall not be declared const,
3129 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003130 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003131 if (!D.isInvalidType())
3132 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3133 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003134 << SourceRange(D.getIdentifierLoc())
3135 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3136
John McCall8e7d6562010-08-26 03:08:43 +00003137 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003138 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003139 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003140 // Destructors don't have return types, but the parser will
3141 // happily parse something like:
3142 //
3143 // class X {
3144 // float ~X();
3145 // };
3146 //
3147 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003148 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3149 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3150 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003151 }
Mike Stump11289f42009-09-09 15:08:12 +00003152
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003153 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003154 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003155 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003156 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3157 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003158 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003159 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3160 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003161 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003162 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3163 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003164 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003165 }
3166
3167 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003168 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003169 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3170
3171 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003172 FTI.freeArgs();
3173 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003174 }
3175
Mike Stump11289f42009-09-09 15:08:12 +00003176 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003177 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003178 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003179 D.setInvalidType();
3180 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003181
3182 // Rebuild the function type "R" without any type qualifiers or
3183 // parameters (in case any of the errors above fired) and with
3184 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003185 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003186 if (!D.isInvalidType())
3187 return R;
3188
Douglas Gregor95755162010-07-01 05:10:53 +00003189 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003190 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3191 EPI.Variadic = false;
3192 EPI.TypeQuals = 0;
3193 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003194}
3195
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003196/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3197/// well-formednes of the conversion function declarator @p D with
3198/// type @p R. If there are any errors in the declarator, this routine
3199/// will emit diagnostics and return true. Otherwise, it will return
3200/// false. Either way, the type @p R will be updated to reflect a
3201/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003202void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003203 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003204 // C++ [class.conv.fct]p1:
3205 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003206 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003207 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003208 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003209 if (!D.isInvalidType())
3210 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3211 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3212 << SourceRange(D.getIdentifierLoc());
3213 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003214 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003215 }
John McCall212fa2e2010-04-13 00:04:31 +00003216
3217 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3218
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003219 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003220 // Conversion functions don't have return types, but the parser will
3221 // happily parse something like:
3222 //
3223 // class X {
3224 // float operator bool();
3225 // };
3226 //
3227 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003228 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3229 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3230 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003231 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003232 }
3233
John McCall212fa2e2010-04-13 00:04:31 +00003234 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3235
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003236 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003237 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003238 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3239
3240 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003241 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003242 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003243 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003244 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003245 D.setInvalidType();
3246 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003247
John McCall212fa2e2010-04-13 00:04:31 +00003248 // Diagnose "&operator bool()" and other such nonsense. This
3249 // is actually a gcc extension which we don't support.
3250 if (Proto->getResultType() != ConvType) {
3251 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3252 << Proto->getResultType();
3253 D.setInvalidType();
3254 ConvType = Proto->getResultType();
3255 }
3256
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003257 // C++ [class.conv.fct]p4:
3258 // The conversion-type-id shall not represent a function type nor
3259 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003260 if (ConvType->isArrayType()) {
3261 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3262 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003263 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003264 } else if (ConvType->isFunctionType()) {
3265 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3266 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003267 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003268 }
3269
3270 // Rebuild the function type "R" without any parameters (in case any
3271 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003272 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003273 if (D.isInvalidType())
3274 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003275
Douglas Gregor5fb53972009-01-14 15:45:31 +00003276 // C++0x explicit conversion operators.
3277 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003278 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003279 diag::warn_explicit_conversion_functions)
3280 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003281}
3282
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003283/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3284/// the declaration of the given C++ conversion function. This routine
3285/// is responsible for recording the conversion function in the C++
3286/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003287Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003288 assert(Conversion && "Expected to receive a conversion function declaration");
3289
Douglas Gregor4287b372008-12-12 08:25:50 +00003290 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003291
3292 // Make sure we aren't redeclaring the conversion function.
3293 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003294
3295 // C++ [class.conv.fct]p1:
3296 // [...] A conversion function is never used to convert a
3297 // (possibly cv-qualified) object to the (possibly cv-qualified)
3298 // same object type (or a reference to it), to a (possibly
3299 // cv-qualified) base class of that type (or a reference to it),
3300 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003301 // FIXME: Suppress this warning if the conversion function ends up being a
3302 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003303 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003304 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003305 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003306 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003307 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3308 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003309 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003310 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003311 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3312 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003313 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003314 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003315 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003316 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003317 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003318 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003319 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003320 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003321 }
3322
Douglas Gregor457104e2010-09-29 04:25:11 +00003323 if (FunctionTemplateDecl *ConversionTemplate
3324 = Conversion->getDescribedFunctionTemplate())
3325 return ConversionTemplate;
3326
John McCall48871652010-08-21 09:40:31 +00003327 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003328}
3329
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003330//===----------------------------------------------------------------------===//
3331// Namespace Handling
3332//===----------------------------------------------------------------------===//
3333
John McCallb1be5232010-08-26 09:15:37 +00003334
3335
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003336/// ActOnStartNamespaceDef - This is called at the start of a namespace
3337/// definition.
John McCall48871652010-08-21 09:40:31 +00003338Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003339 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003340 SourceLocation IdentLoc,
3341 IdentifierInfo *II,
3342 SourceLocation LBrace,
3343 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003344 // anonymous namespace starts at its left brace
3345 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3346 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003347 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003348 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003349
3350 Scope *DeclRegionScope = NamespcScope->getParent();
3351
Anders Carlssona7bcade2010-02-07 01:09:23 +00003352 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3353
John McCall2faf32c2010-12-10 02:59:44 +00003354 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3355 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003356
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003357 if (II) {
3358 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003359 // The identifier in an original-namespace-definition shall not
3360 // have been previously defined in the declarative region in
3361 // which the original-namespace-definition appears. The
3362 // identifier in an original-namespace-definition is the name of
3363 // the namespace. Subsequently in that declarative region, it is
3364 // treated as an original-namespace-name.
3365 //
3366 // Since namespace names are unique in their scope, and we don't
3367 // look through using directives, just
3368 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3369 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003370
Douglas Gregor91f84212008-12-11 16:49:14 +00003371 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3372 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003373 if (Namespc->isInline() != OrigNS->isInline()) {
3374 // inline-ness must match
3375 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3376 << Namespc->isInline();
3377 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3378 Namespc->setInvalidDecl();
3379 // Recover by ignoring the new namespace's inline status.
3380 Namespc->setInline(OrigNS->isInline());
3381 }
3382
Douglas Gregor91f84212008-12-11 16:49:14 +00003383 // Attach this namespace decl to the chain of extended namespace
3384 // definitions.
3385 OrigNS->setNextNamespace(Namespc);
3386 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003387
Mike Stump11289f42009-09-09 15:08:12 +00003388 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003389 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003390 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003391 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003392 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003393 } else if (PrevDecl) {
3394 // This is an invalid name redefinition.
3395 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3396 << Namespc->getDeclName();
3397 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3398 Namespc->setInvalidDecl();
3399 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003400 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003401 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003402 // This is the first "real" definition of the namespace "std", so update
3403 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003404 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003405 // We had already defined a dummy namespace "std". Link this new
3406 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003407 StdNS->setNextNamespace(Namespc);
3408 StdNS->setLocation(IdentLoc);
3409 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003410 }
3411
3412 // Make our StdNamespace cache point at the first real definition of the
3413 // "std" namespace.
3414 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003415 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003416
3417 PushOnScopeChains(Namespc, DeclRegionScope);
3418 } else {
John McCall4fa53422009-10-01 00:25:31 +00003419 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003420 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003421
3422 // Link the anonymous namespace into its parent.
3423 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003424 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003425 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3426 PrevDecl = TU->getAnonymousNamespace();
3427 TU->setAnonymousNamespace(Namespc);
3428 } else {
3429 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3430 PrevDecl = ND->getAnonymousNamespace();
3431 ND->setAnonymousNamespace(Namespc);
3432 }
3433
3434 // Link the anonymous namespace with its previous declaration.
3435 if (PrevDecl) {
3436 assert(PrevDecl->isAnonymousNamespace());
3437 assert(!PrevDecl->getNextNamespace());
3438 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3439 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003440
3441 if (Namespc->isInline() != PrevDecl->isInline()) {
3442 // inline-ness must match
3443 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3444 << Namespc->isInline();
3445 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3446 Namespc->setInvalidDecl();
3447 // Recover by ignoring the new namespace's inline status.
3448 Namespc->setInline(PrevDecl->isInline());
3449 }
John McCall0db42252009-12-16 02:06:49 +00003450 }
John McCall4fa53422009-10-01 00:25:31 +00003451
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003452 CurContext->addDecl(Namespc);
3453
John McCall4fa53422009-10-01 00:25:31 +00003454 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3455 // behaves as if it were replaced by
3456 // namespace unique { /* empty body */ }
3457 // using namespace unique;
3458 // namespace unique { namespace-body }
3459 // where all occurrences of 'unique' in a translation unit are
3460 // replaced by the same identifier and this identifier differs
3461 // from all other identifiers in the entire program.
3462
3463 // We just create the namespace with an empty name and then add an
3464 // implicit using declaration, just like the standard suggests.
3465 //
3466 // CodeGen enforces the "universally unique" aspect by giving all
3467 // declarations semantically contained within an anonymous
3468 // namespace internal linkage.
3469
John McCall0db42252009-12-16 02:06:49 +00003470 if (!PrevDecl) {
3471 UsingDirectiveDecl* UD
3472 = UsingDirectiveDecl::Create(Context, CurContext,
3473 /* 'using' */ LBrace,
3474 /* 'namespace' */ SourceLocation(),
3475 /* qualifier */ SourceRange(),
3476 /* NNS */ NULL,
3477 /* identifier */ SourceLocation(),
3478 Namespc,
3479 /* Ancestor */ CurContext);
3480 UD->setImplicit();
3481 CurContext->addDecl(UD);
3482 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003483 }
3484
3485 // Although we could have an invalid decl (i.e. the namespace name is a
3486 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003487 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3488 // for the namespace has the declarations that showed up in that particular
3489 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003490 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003491 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003492}
3493
Sebastian Redla6602e92009-11-23 15:34:23 +00003494/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3495/// is a namespace alias, returns the namespace it points to.
3496static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3497 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3498 return AD->getNamespace();
3499 return dyn_cast_or_null<NamespaceDecl>(D);
3500}
3501
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003502/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3503/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003504void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003505 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3506 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3507 Namespc->setRBracLoc(RBrace);
3508 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003509 if (Namespc->hasAttr<VisibilityAttr>())
3510 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003511}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003512
John McCall28a0cf72010-08-25 07:42:41 +00003513CXXRecordDecl *Sema::getStdBadAlloc() const {
3514 return cast_or_null<CXXRecordDecl>(
3515 StdBadAlloc.get(Context.getExternalSource()));
3516}
3517
3518NamespaceDecl *Sema::getStdNamespace() const {
3519 return cast_or_null<NamespaceDecl>(
3520 StdNamespace.get(Context.getExternalSource()));
3521}
3522
Douglas Gregorcdf87022010-06-29 17:53:46 +00003523/// \brief Retrieve the special "std" namespace, which may require us to
3524/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003525NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003526 if (!StdNamespace) {
3527 // The "std" namespace has not yet been defined, so build one implicitly.
3528 StdNamespace = NamespaceDecl::Create(Context,
3529 Context.getTranslationUnitDecl(),
3530 SourceLocation(),
3531 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003532 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003533 }
3534
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003535 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003536}
3537
John McCall48871652010-08-21 09:40:31 +00003538Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003539 SourceLocation UsingLoc,
3540 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003541 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003542 SourceLocation IdentLoc,
3543 IdentifierInfo *NamespcName,
3544 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003545 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3546 assert(NamespcName && "Invalid NamespcName.");
3547 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003548
3549 // This can only happen along a recovery path.
3550 while (S->getFlags() & Scope::TemplateParamScope)
3551 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003552 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003553
Douglas Gregor889ceb72009-02-03 19:21:40 +00003554 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003555 NestedNameSpecifier *Qualifier = 0;
3556 if (SS.isSet())
3557 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3558
Douglas Gregor34074322009-01-14 22:20:51 +00003559 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003560 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3561 LookupParsedName(R, S, &SS);
3562 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003563 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003564
Douglas Gregorcdf87022010-06-29 17:53:46 +00003565 if (R.empty()) {
3566 // Allow "using namespace std;" or "using namespace ::std;" even if
3567 // "std" hasn't been defined yet, for GCC compatibility.
3568 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3569 NamespcName->isStr("std")) {
3570 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003571 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003572 R.resolveKind();
3573 }
3574 // Otherwise, attempt typo correction.
3575 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3576 CTC_NoKeywords, 0)) {
3577 if (R.getAsSingle<NamespaceDecl>() ||
3578 R.getAsSingle<NamespaceAliasDecl>()) {
3579 if (DeclContext *DC = computeDeclContext(SS, false))
3580 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3581 << NamespcName << DC << Corrected << SS.getRange()
3582 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3583 else
3584 Diag(IdentLoc, diag::err_using_directive_suggest)
3585 << NamespcName << Corrected
3586 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3587 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3588 << Corrected;
3589
3590 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003591 } else {
3592 R.clear();
3593 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003594 }
3595 }
3596 }
3597
John McCall9f3059a2009-10-09 21:13:30 +00003598 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003599 NamedDecl *Named = R.getFoundDecl();
3600 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3601 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003602 // C++ [namespace.udir]p1:
3603 // A using-directive specifies that the names in the nominated
3604 // namespace can be used in the scope in which the
3605 // using-directive appears after the using-directive. During
3606 // unqualified name lookup (3.4.1), the names appear as if they
3607 // were declared in the nearest enclosing namespace which
3608 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003609 // namespace. [Note: in this context, "contains" means "contains
3610 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003611
3612 // Find enclosing context containing both using-directive and
3613 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003614 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003615 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3616 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3617 CommonAncestor = CommonAncestor->getParent();
3618
Sebastian Redla6602e92009-11-23 15:34:23 +00003619 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003620 SS.getRange(),
3621 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003622 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003623 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003624 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003625 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003626 }
3627
Douglas Gregor889ceb72009-02-03 19:21:40 +00003628 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003629 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003630}
3631
3632void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3633 // If scope has associated entity, then using directive is at namespace
3634 // or translation unit scope. We add UsingDirectiveDecls, into
3635 // it's lookup structure.
3636 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003637 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003638 else
3639 // Otherwise it is block-sope. using-directives will affect lookup
3640 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003641 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003642}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003643
Douglas Gregorfec52632009-06-20 00:51:54 +00003644
John McCall48871652010-08-21 09:40:31 +00003645Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003646 AccessSpecifier AS,
3647 bool HasUsingKeyword,
3648 SourceLocation UsingLoc,
3649 CXXScopeSpec &SS,
3650 UnqualifiedId &Name,
3651 AttributeList *AttrList,
3652 bool IsTypeName,
3653 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003654 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003655
Douglas Gregor220f4272009-11-04 16:30:06 +00003656 switch (Name.getKind()) {
3657 case UnqualifiedId::IK_Identifier:
3658 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003659 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003660 case UnqualifiedId::IK_ConversionFunctionId:
3661 break;
3662
3663 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003664 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003665 // C++0x inherited constructors.
3666 if (getLangOptions().CPlusPlus0x) break;
3667
Douglas Gregor220f4272009-11-04 16:30:06 +00003668 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3669 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003670 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003671
3672 case UnqualifiedId::IK_DestructorName:
3673 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3674 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003675 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003676
3677 case UnqualifiedId::IK_TemplateId:
3678 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3679 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003680 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003681 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003682
3683 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3684 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003685 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003686 return 0;
John McCall3969e302009-12-08 07:46:18 +00003687
John McCalla0097262009-12-11 02:10:03 +00003688 // Warn about using declarations.
3689 // TODO: store that the declaration was written without 'using' and
3690 // talk about access decls instead of using decls in the
3691 // diagnostics.
3692 if (!HasUsingKeyword) {
3693 UsingLoc = Name.getSourceRange().getBegin();
3694
3695 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003696 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003697 }
3698
Douglas Gregorc4356532010-12-16 00:46:58 +00003699 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3700 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3701 return 0;
3702
John McCall3f746822009-11-17 05:59:44 +00003703 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003704 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003705 /* IsInstantiation */ false,
3706 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003707 if (UD)
3708 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003709
John McCall48871652010-08-21 09:40:31 +00003710 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003711}
3712
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003713/// \brief Determine whether a using declaration considers the given
3714/// declarations as "equivalent", e.g., if they are redeclarations of
3715/// the same entity or are both typedefs of the same type.
3716static bool
3717IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3718 bool &SuppressRedeclaration) {
3719 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3720 SuppressRedeclaration = false;
3721 return true;
3722 }
3723
3724 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3725 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3726 SuppressRedeclaration = true;
3727 return Context.hasSameType(TD1->getUnderlyingType(),
3728 TD2->getUnderlyingType());
3729 }
3730
3731 return false;
3732}
3733
3734
John McCall84d87672009-12-10 09:41:52 +00003735/// Determines whether to create a using shadow decl for a particular
3736/// decl, given the set of decls existing prior to this using lookup.
3737bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3738 const LookupResult &Previous) {
3739 // Diagnose finding a decl which is not from a base class of the
3740 // current class. We do this now because there are cases where this
3741 // function will silently decide not to build a shadow decl, which
3742 // will pre-empt further diagnostics.
3743 //
3744 // We don't need to do this in C++0x because we do the check once on
3745 // the qualifier.
3746 //
3747 // FIXME: diagnose the following if we care enough:
3748 // struct A { int foo; };
3749 // struct B : A { using A::foo; };
3750 // template <class T> struct C : A {};
3751 // template <class T> struct D : C<T> { using B::foo; } // <---
3752 // This is invalid (during instantiation) in C++03 because B::foo
3753 // resolves to the using decl in B, which is not a base class of D<T>.
3754 // We can't diagnose it immediately because C<T> is an unknown
3755 // specialization. The UsingShadowDecl in D<T> then points directly
3756 // to A::foo, which will look well-formed when we instantiate.
3757 // The right solution is to not collapse the shadow-decl chain.
3758 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3759 DeclContext *OrigDC = Orig->getDeclContext();
3760
3761 // Handle enums and anonymous structs.
3762 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3763 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3764 while (OrigRec->isAnonymousStructOrUnion())
3765 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3766
3767 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3768 if (OrigDC == CurContext) {
3769 Diag(Using->getLocation(),
3770 diag::err_using_decl_nested_name_specifier_is_current_class)
3771 << Using->getNestedNameRange();
3772 Diag(Orig->getLocation(), diag::note_using_decl_target);
3773 return true;
3774 }
3775
3776 Diag(Using->getNestedNameRange().getBegin(),
3777 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3778 << Using->getTargetNestedNameDecl()
3779 << cast<CXXRecordDecl>(CurContext)
3780 << Using->getNestedNameRange();
3781 Diag(Orig->getLocation(), diag::note_using_decl_target);
3782 return true;
3783 }
3784 }
3785
3786 if (Previous.empty()) return false;
3787
3788 NamedDecl *Target = Orig;
3789 if (isa<UsingShadowDecl>(Target))
3790 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3791
John McCalla17e83e2009-12-11 02:33:26 +00003792 // If the target happens to be one of the previous declarations, we
3793 // don't have a conflict.
3794 //
3795 // FIXME: but we might be increasing its access, in which case we
3796 // should redeclare it.
3797 NamedDecl *NonTag = 0, *Tag = 0;
3798 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3799 I != E; ++I) {
3800 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003801 bool Result;
3802 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3803 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003804
3805 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3806 }
3807
John McCall84d87672009-12-10 09:41:52 +00003808 if (Target->isFunctionOrFunctionTemplate()) {
3809 FunctionDecl *FD;
3810 if (isa<FunctionTemplateDecl>(Target))
3811 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3812 else
3813 FD = cast<FunctionDecl>(Target);
3814
3815 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003816 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003817 case Ovl_Overload:
3818 return false;
3819
3820 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003821 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003822 break;
3823
3824 // We found a decl with the exact signature.
3825 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003826 // If we're in a record, we want to hide the target, so we
3827 // return true (without a diagnostic) to tell the caller not to
3828 // build a shadow decl.
3829 if (CurContext->isRecord())
3830 return true;
3831
3832 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003833 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003834 break;
3835 }
3836
3837 Diag(Target->getLocation(), diag::note_using_decl_target);
3838 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3839 return true;
3840 }
3841
3842 // Target is not a function.
3843
John McCall84d87672009-12-10 09:41:52 +00003844 if (isa<TagDecl>(Target)) {
3845 // No conflict between a tag and a non-tag.
3846 if (!Tag) return false;
3847
John McCalle29c5cd2009-12-10 19:51:03 +00003848 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003849 Diag(Target->getLocation(), diag::note_using_decl_target);
3850 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3851 return true;
3852 }
3853
3854 // No conflict between a tag and a non-tag.
3855 if (!NonTag) return false;
3856
John McCalle29c5cd2009-12-10 19:51:03 +00003857 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003858 Diag(Target->getLocation(), diag::note_using_decl_target);
3859 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3860 return true;
3861}
3862
John McCall3f746822009-11-17 05:59:44 +00003863/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003864UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003865 UsingDecl *UD,
3866 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003867
3868 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003869 NamedDecl *Target = Orig;
3870 if (isa<UsingShadowDecl>(Target)) {
3871 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3872 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003873 }
3874
3875 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003876 = UsingShadowDecl::Create(Context, CurContext,
3877 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003878 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003879
3880 Shadow->setAccess(UD->getAccess());
3881 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3882 Shadow->setInvalidDecl();
3883
John McCall3f746822009-11-17 05:59:44 +00003884 if (S)
John McCall3969e302009-12-08 07:46:18 +00003885 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003886 else
John McCall3969e302009-12-08 07:46:18 +00003887 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003888
John McCall3969e302009-12-08 07:46:18 +00003889
John McCall84d87672009-12-10 09:41:52 +00003890 return Shadow;
3891}
John McCall3969e302009-12-08 07:46:18 +00003892
John McCall84d87672009-12-10 09:41:52 +00003893/// Hides a using shadow declaration. This is required by the current
3894/// using-decl implementation when a resolvable using declaration in a
3895/// class is followed by a declaration which would hide or override
3896/// one or more of the using decl's targets; for example:
3897///
3898/// struct Base { void foo(int); };
3899/// struct Derived : Base {
3900/// using Base::foo;
3901/// void foo(int);
3902/// };
3903///
3904/// The governing language is C++03 [namespace.udecl]p12:
3905///
3906/// When a using-declaration brings names from a base class into a
3907/// derived class scope, member functions in the derived class
3908/// override and/or hide member functions with the same name and
3909/// parameter types in a base class (rather than conflicting).
3910///
3911/// There are two ways to implement this:
3912/// (1) optimistically create shadow decls when they're not hidden
3913/// by existing declarations, or
3914/// (2) don't create any shadow decls (or at least don't make them
3915/// visible) until we've fully parsed/instantiated the class.
3916/// The problem with (1) is that we might have to retroactively remove
3917/// a shadow decl, which requires several O(n) operations because the
3918/// decl structures are (very reasonably) not designed for removal.
3919/// (2) avoids this but is very fiddly and phase-dependent.
3920void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003921 if (Shadow->getDeclName().getNameKind() ==
3922 DeclarationName::CXXConversionFunctionName)
3923 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3924
John McCall84d87672009-12-10 09:41:52 +00003925 // Remove it from the DeclContext...
3926 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003927
John McCall84d87672009-12-10 09:41:52 +00003928 // ...and the scope, if applicable...
3929 if (S) {
John McCall48871652010-08-21 09:40:31 +00003930 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003931 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003932 }
3933
John McCall84d87672009-12-10 09:41:52 +00003934 // ...and the using decl.
3935 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3936
3937 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003938 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003939}
3940
John McCalle61f2ba2009-11-18 02:36:19 +00003941/// Builds a using declaration.
3942///
3943/// \param IsInstantiation - Whether this call arises from an
3944/// instantiation of an unresolved using declaration. We treat
3945/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003946NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3947 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003948 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003949 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003950 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003951 bool IsInstantiation,
3952 bool IsTypeName,
3953 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003954 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003955 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003956 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003957
Anders Carlssonf038fc22009-08-28 05:49:21 +00003958 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003959
Anders Carlsson59140b32009-08-28 03:16:11 +00003960 if (SS.isEmpty()) {
3961 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003962 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003963 }
Mike Stump11289f42009-09-09 15:08:12 +00003964
John McCall84d87672009-12-10 09:41:52 +00003965 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003966 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003967 ForRedeclaration);
3968 Previous.setHideTags(false);
3969 if (S) {
3970 LookupName(Previous, S);
3971
3972 // It is really dumb that we have to do this.
3973 LookupResult::Filter F = Previous.makeFilter();
3974 while (F.hasNext()) {
3975 NamedDecl *D = F.next();
3976 if (!isDeclInScope(D, CurContext, S))
3977 F.erase();
3978 }
3979 F.done();
3980 } else {
3981 assert(IsInstantiation && "no scope in non-instantiation");
3982 assert(CurContext->isRecord() && "scope not record in instantiation");
3983 LookupQualifiedName(Previous, CurContext);
3984 }
3985
Mike Stump11289f42009-09-09 15:08:12 +00003986 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003987 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3988
John McCall84d87672009-12-10 09:41:52 +00003989 // Check for invalid redeclarations.
3990 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3991 return 0;
3992
3993 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003994 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3995 return 0;
3996
John McCall84c16cf2009-11-12 03:15:40 +00003997 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003998 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003999 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004000 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004001 // FIXME: not all declaration name kinds are legal here
4002 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4003 UsingLoc, TypenameLoc,
4004 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004005 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004006 } else {
4007 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004008 UsingLoc, SS.getRange(),
4009 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004010 }
John McCallb96ec562009-12-04 22:46:56 +00004011 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004012 D = UsingDecl::Create(Context, CurContext,
4013 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00004014 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004015 }
John McCallb96ec562009-12-04 22:46:56 +00004016 D->setAccess(AS);
4017 CurContext->addDecl(D);
4018
4019 if (!LookupContext) return D;
4020 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004021
John McCall0b66eb32010-05-01 00:40:08 +00004022 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004023 UD->setInvalidDecl();
4024 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004025 }
4026
John McCall3969e302009-12-08 07:46:18 +00004027 // Look up the target name.
4028
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004029 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004030
John McCall3969e302009-12-08 07:46:18 +00004031 // Unlike most lookups, we don't always want to hide tag
4032 // declarations: tag names are visible through the using declaration
4033 // even if hidden by ordinary names, *except* in a dependent context
4034 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004035 if (!IsInstantiation)
4036 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004037
John McCall27b18f82009-11-17 02:14:36 +00004038 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004039
John McCall9f3059a2009-10-09 21:13:30 +00004040 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004041 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004042 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004043 UD->setInvalidDecl();
4044 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004045 }
4046
John McCallb96ec562009-12-04 22:46:56 +00004047 if (R.isAmbiguous()) {
4048 UD->setInvalidDecl();
4049 return UD;
4050 }
Mike Stump11289f42009-09-09 15:08:12 +00004051
John McCalle61f2ba2009-11-18 02:36:19 +00004052 if (IsTypeName) {
4053 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004054 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004055 Diag(IdentLoc, diag::err_using_typename_non_type);
4056 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4057 Diag((*I)->getUnderlyingDecl()->getLocation(),
4058 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004059 UD->setInvalidDecl();
4060 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004061 }
4062 } else {
4063 // If we asked for a non-typename and we got a type, error out,
4064 // but only if this is an instantiation of an unresolved using
4065 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004066 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004067 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4068 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004069 UD->setInvalidDecl();
4070 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004071 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004072 }
4073
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004074 // C++0x N2914 [namespace.udecl]p6:
4075 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004076 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004077 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4078 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004079 UD->setInvalidDecl();
4080 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
John McCall84d87672009-12-10 09:41:52 +00004083 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4084 if (!CheckUsingShadowDecl(UD, *I, Previous))
4085 BuildUsingShadowDecl(S, UD, *I);
4086 }
John McCall3f746822009-11-17 05:59:44 +00004087
4088 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004089}
4090
John McCall84d87672009-12-10 09:41:52 +00004091/// Checks that the given using declaration is not an invalid
4092/// redeclaration. Note that this is checking only for the using decl
4093/// itself, not for any ill-formedness among the UsingShadowDecls.
4094bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4095 bool isTypeName,
4096 const CXXScopeSpec &SS,
4097 SourceLocation NameLoc,
4098 const LookupResult &Prev) {
4099 // C++03 [namespace.udecl]p8:
4100 // C++0x [namespace.udecl]p10:
4101 // A using-declaration is a declaration and can therefore be used
4102 // repeatedly where (and only where) multiple declarations are
4103 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004104 //
John McCall032092f2010-11-29 18:01:58 +00004105 // That's in non-member contexts.
4106 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004107 return false;
4108
4109 NestedNameSpecifier *Qual
4110 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4111
4112 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4113 NamedDecl *D = *I;
4114
4115 bool DTypename;
4116 NestedNameSpecifier *DQual;
4117 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4118 DTypename = UD->isTypeName();
4119 DQual = UD->getTargetNestedNameDecl();
4120 } else if (UnresolvedUsingValueDecl *UD
4121 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4122 DTypename = false;
4123 DQual = UD->getTargetNestedNameSpecifier();
4124 } else if (UnresolvedUsingTypenameDecl *UD
4125 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4126 DTypename = true;
4127 DQual = UD->getTargetNestedNameSpecifier();
4128 } else continue;
4129
4130 // using decls differ if one says 'typename' and the other doesn't.
4131 // FIXME: non-dependent using decls?
4132 if (isTypeName != DTypename) continue;
4133
4134 // using decls differ if they name different scopes (but note that
4135 // template instantiation can cause this check to trigger when it
4136 // didn't before instantiation).
4137 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4138 Context.getCanonicalNestedNameSpecifier(DQual))
4139 continue;
4140
4141 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004142 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004143 return true;
4144 }
4145
4146 return false;
4147}
4148
John McCall3969e302009-12-08 07:46:18 +00004149
John McCallb96ec562009-12-04 22:46:56 +00004150/// Checks that the given nested-name qualifier used in a using decl
4151/// in the current context is appropriately related to the current
4152/// scope. If an error is found, diagnoses it and returns true.
4153bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4154 const CXXScopeSpec &SS,
4155 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004156 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004157
John McCall3969e302009-12-08 07:46:18 +00004158 if (!CurContext->isRecord()) {
4159 // C++03 [namespace.udecl]p3:
4160 // C++0x [namespace.udecl]p8:
4161 // A using-declaration for a class member shall be a member-declaration.
4162
4163 // If we weren't able to compute a valid scope, it must be a
4164 // dependent class scope.
4165 if (!NamedContext || NamedContext->isRecord()) {
4166 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4167 << SS.getRange();
4168 return true;
4169 }
4170
4171 // Otherwise, everything is known to be fine.
4172 return false;
4173 }
4174
4175 // The current scope is a record.
4176
4177 // If the named context is dependent, we can't decide much.
4178 if (!NamedContext) {
4179 // FIXME: in C++0x, we can diagnose if we can prove that the
4180 // nested-name-specifier does not refer to a base class, which is
4181 // still possible in some cases.
4182
4183 // Otherwise we have to conservatively report that things might be
4184 // okay.
4185 return false;
4186 }
4187
4188 if (!NamedContext->isRecord()) {
4189 // Ideally this would point at the last name in the specifier,
4190 // but we don't have that level of source info.
4191 Diag(SS.getRange().getBegin(),
4192 diag::err_using_decl_nested_name_specifier_is_not_class)
4193 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4194 return true;
4195 }
4196
Douglas Gregor7c842292010-12-21 07:41:49 +00004197 if (!NamedContext->isDependentContext() &&
4198 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4199 return true;
4200
John McCall3969e302009-12-08 07:46:18 +00004201 if (getLangOptions().CPlusPlus0x) {
4202 // C++0x [namespace.udecl]p3:
4203 // In a using-declaration used as a member-declaration, the
4204 // nested-name-specifier shall name a base class of the class
4205 // being defined.
4206
4207 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4208 cast<CXXRecordDecl>(NamedContext))) {
4209 if (CurContext == NamedContext) {
4210 Diag(NameLoc,
4211 diag::err_using_decl_nested_name_specifier_is_current_class)
4212 << SS.getRange();
4213 return true;
4214 }
4215
4216 Diag(SS.getRange().getBegin(),
4217 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4218 << (NestedNameSpecifier*) SS.getScopeRep()
4219 << cast<CXXRecordDecl>(CurContext)
4220 << SS.getRange();
4221 return true;
4222 }
4223
4224 return false;
4225 }
4226
4227 // C++03 [namespace.udecl]p4:
4228 // A using-declaration used as a member-declaration shall refer
4229 // to a member of a base class of the class being defined [etc.].
4230
4231 // Salient point: SS doesn't have to name a base class as long as
4232 // lookup only finds members from base classes. Therefore we can
4233 // diagnose here only if we can prove that that can't happen,
4234 // i.e. if the class hierarchies provably don't intersect.
4235
4236 // TODO: it would be nice if "definitely valid" results were cached
4237 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4238 // need to be repeated.
4239
4240 struct UserData {
4241 llvm::DenseSet<const CXXRecordDecl*> Bases;
4242
4243 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4244 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4245 Data->Bases.insert(Base);
4246 return true;
4247 }
4248
4249 bool hasDependentBases(const CXXRecordDecl *Class) {
4250 return !Class->forallBases(collect, this);
4251 }
4252
4253 /// Returns true if the base is dependent or is one of the
4254 /// accumulated base classes.
4255 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4256 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4257 return !Data->Bases.count(Base);
4258 }
4259
4260 bool mightShareBases(const CXXRecordDecl *Class) {
4261 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4262 }
4263 };
4264
4265 UserData Data;
4266
4267 // Returns false if we find a dependent base.
4268 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4269 return false;
4270
4271 // Returns false if the class has a dependent base or if it or one
4272 // of its bases is present in the base set of the current context.
4273 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4274 return false;
4275
4276 Diag(SS.getRange().getBegin(),
4277 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4278 << (NestedNameSpecifier*) SS.getScopeRep()
4279 << cast<CXXRecordDecl>(CurContext)
4280 << SS.getRange();
4281
4282 return true;
John McCallb96ec562009-12-04 22:46:56 +00004283}
4284
John McCall48871652010-08-21 09:40:31 +00004285Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004286 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004287 SourceLocation AliasLoc,
4288 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004289 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004290 SourceLocation IdentLoc,
4291 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004292
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004293 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004294 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4295 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004296
Anders Carlssondca83c42009-03-28 06:23:46 +00004297 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004298 NamedDecl *PrevDecl
4299 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4300 ForRedeclaration);
4301 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4302 PrevDecl = 0;
4303
4304 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004305 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004306 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004307 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004308 // FIXME: At some point, we'll want to create the (redundant)
4309 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004310 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004311 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004312 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314
Anders Carlssondca83c42009-03-28 06:23:46 +00004315 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4316 diag::err_redefinition_different_kind;
4317 Diag(AliasLoc, DiagID) << Alias;
4318 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004319 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004320 }
4321
John McCall27b18f82009-11-17 02:14:36 +00004322 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004323 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004324
John McCall9f3059a2009-10-09 21:13:30 +00004325 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004326 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4327 CTC_NoKeywords, 0)) {
4328 if (R.getAsSingle<NamespaceDecl>() ||
4329 R.getAsSingle<NamespaceAliasDecl>()) {
4330 if (DeclContext *DC = computeDeclContext(SS, false))
4331 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4332 << Ident << DC << Corrected << SS.getRange()
4333 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4334 else
4335 Diag(IdentLoc, diag::err_using_directive_suggest)
4336 << Ident << Corrected
4337 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4338
4339 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4340 << Corrected;
4341
4342 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004343 } else {
4344 R.clear();
4345 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004346 }
4347 }
4348
4349 if (R.empty()) {
4350 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004351 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004352 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004353 }
Mike Stump11289f42009-09-09 15:08:12 +00004354
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004355 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004356 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4357 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004358 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004359 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004360
John McCalld8d0d432010-02-16 06:53:13 +00004361 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004362 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004363}
4364
Douglas Gregora57478e2010-05-01 15:04:51 +00004365namespace {
4366 /// \brief Scoped object used to handle the state changes required in Sema
4367 /// to implicitly define the body of a C++ member function;
4368 class ImplicitlyDefinedFunctionScope {
4369 Sema &S;
4370 DeclContext *PreviousContext;
4371
4372 public:
4373 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4374 : S(S), PreviousContext(S.CurContext)
4375 {
4376 S.CurContext = Method;
4377 S.PushFunctionScope();
4378 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4379 }
4380
4381 ~ImplicitlyDefinedFunctionScope() {
4382 S.PopExpressionEvaluationContext();
4383 S.PopFunctionOrBlockScope();
4384 S.CurContext = PreviousContext;
4385 }
4386 };
4387}
4388
Sebastian Redlc15c3262010-09-13 22:02:47 +00004389static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4390 CXXRecordDecl *D) {
4391 ASTContext &Context = Self.Context;
4392 QualType ClassType = Context.getTypeDeclType(D);
4393 DeclarationName ConstructorName
4394 = Context.DeclarationNames.getCXXConstructorName(
4395 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4396
4397 DeclContext::lookup_const_iterator Con, ConEnd;
4398 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4399 Con != ConEnd; ++Con) {
4400 // FIXME: In C++0x, a constructor template can be a default constructor.
4401 if (isa<FunctionTemplateDecl>(*Con))
4402 continue;
4403
4404 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4405 if (Constructor->isDefaultConstructor())
4406 return Constructor;
4407 }
4408 return 0;
4409}
4410
Douglas Gregor0be31a22010-07-02 17:43:08 +00004411CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4412 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004413 // C++ [class.ctor]p5:
4414 // A default constructor for a class X is a constructor of class X
4415 // that can be called without an argument. If there is no
4416 // user-declared constructor for class X, a default constructor is
4417 // implicitly declared. An implicitly-declared default constructor
4418 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004419 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4420 "Should not build implicit default constructor!");
4421
Douglas Gregor6d880b12010-07-01 22:31:05 +00004422 // C++ [except.spec]p14:
4423 // An implicitly declared special member function (Clause 12) shall have an
4424 // exception-specification. [...]
4425 ImplicitExceptionSpecification ExceptSpec(Context);
4426
4427 // Direct base-class destructors.
4428 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4429 BEnd = ClassDecl->bases_end();
4430 B != BEnd; ++B) {
4431 if (B->isVirtual()) // Handled below.
4432 continue;
4433
Douglas Gregor9672f922010-07-03 00:47:00 +00004434 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4435 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4436 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4437 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004438 else if (CXXConstructorDecl *Constructor
4439 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004440 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004441 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004442 }
4443
4444 // Virtual base-class destructors.
4445 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4446 BEnd = ClassDecl->vbases_end();
4447 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004448 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4449 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4450 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4451 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4452 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004453 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004454 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004455 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004456 }
4457
4458 // Field destructors.
4459 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4460 FEnd = ClassDecl->field_end();
4461 F != FEnd; ++F) {
4462 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004463 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4464 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4465 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4466 ExceptSpec.CalledDecl(
4467 DeclareImplicitDefaultConstructor(FieldClassDecl));
4468 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004469 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004470 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004471 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004472 }
John McCalldb40c7f2010-12-14 08:05:40 +00004473
4474 FunctionProtoType::ExtProtoInfo EPI;
4475 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4476 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4477 EPI.NumExceptions = ExceptSpec.size();
4478 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004479
4480 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004481 CanQualType ClassType
4482 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4483 DeclarationName Name
4484 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004485 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004486 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004487 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004488 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004489 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004490 /*TInfo=*/0,
4491 /*isExplicit=*/false,
4492 /*isInline=*/true,
4493 /*isImplicitlyDeclared=*/true);
4494 DefaultCon->setAccess(AS_public);
4495 DefaultCon->setImplicit();
4496 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004497
4498 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004499 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4500
Douglas Gregor0be31a22010-07-02 17:43:08 +00004501 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004502 PushOnScopeChains(DefaultCon, S, false);
4503 ClassDecl->addDecl(DefaultCon);
4504
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004505 return DefaultCon;
4506}
4507
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004508void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4509 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004510 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004511 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004512 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004513
Anders Carlsson423f5d82010-04-23 16:04:08 +00004514 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004515 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004516
Douglas Gregora57478e2010-05-01 15:04:51 +00004517 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004518 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004519 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004520 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004521 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004522 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004523 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004524 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004525 }
Douglas Gregor73193272010-09-20 16:48:21 +00004526
4527 SourceLocation Loc = Constructor->getLocation();
4528 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4529
4530 Constructor->setUsed();
4531 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004532}
4533
Douglas Gregor0be31a22010-07-02 17:43:08 +00004534CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004535 // C++ [class.dtor]p2:
4536 // If a class has no user-declared destructor, a destructor is
4537 // declared implicitly. An implicitly-declared destructor is an
4538 // inline public member of its class.
4539
4540 // C++ [except.spec]p14:
4541 // An implicitly declared special member function (Clause 12) shall have
4542 // an exception-specification.
4543 ImplicitExceptionSpecification ExceptSpec(Context);
4544
4545 // Direct base-class destructors.
4546 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4547 BEnd = ClassDecl->bases_end();
4548 B != BEnd; ++B) {
4549 if (B->isVirtual()) // Handled below.
4550 continue;
4551
4552 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4553 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004554 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004555 }
4556
4557 // Virtual base-class destructors.
4558 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4559 BEnd = ClassDecl->vbases_end();
4560 B != BEnd; ++B) {
4561 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4562 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004563 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004564 }
4565
4566 // Field destructors.
4567 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4568 FEnd = ClassDecl->field_end();
4569 F != FEnd; ++F) {
4570 if (const RecordType *RecordTy
4571 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4572 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004573 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004574 }
4575
Douglas Gregor7454c562010-07-02 20:37:36 +00004576 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004577 FunctionProtoType::ExtProtoInfo EPI;
4578 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4579 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4580 EPI.NumExceptions = ExceptSpec.size();
4581 EPI.Exceptions = ExceptSpec.data();
4582 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004583
4584 CanQualType ClassType
4585 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4586 DeclarationName Name
4587 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004588 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004589 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004590 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004591 /*isInline=*/true,
4592 /*isImplicitlyDeclared=*/true);
4593 Destructor->setAccess(AS_public);
4594 Destructor->setImplicit();
4595 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004596
4597 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004598 ++ASTContext::NumImplicitDestructorsDeclared;
4599
4600 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004601 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004602 PushOnScopeChains(Destructor, S, false);
4603 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004604
4605 // This could be uniqued if it ever proves significant.
4606 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4607
4608 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004609
Douglas Gregorf1203042010-07-01 19:09:28 +00004610 return Destructor;
4611}
4612
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004613void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004614 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004615 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004616 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004617 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004618 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004619
Douglas Gregor54818f02010-05-12 16:39:35 +00004620 if (Destructor->isInvalidDecl())
4621 return;
4622
Douglas Gregora57478e2010-05-01 15:04:51 +00004623 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004624
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004625 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004626 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4627 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004628
Douglas Gregor54818f02010-05-12 16:39:35 +00004629 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004630 Diag(CurrentLocation, diag::note_member_synthesized_at)
4631 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4632
4633 Destructor->setInvalidDecl();
4634 return;
4635 }
4636
Douglas Gregor73193272010-09-20 16:48:21 +00004637 SourceLocation Loc = Destructor->getLocation();
4638 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4639
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004640 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004641 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004642}
4643
Douglas Gregorb139cd52010-05-01 20:49:11 +00004644/// \brief Builds a statement that copies the given entity from \p From to
4645/// \c To.
4646///
4647/// This routine is used to copy the members of a class with an
4648/// implicitly-declared copy assignment operator. When the entities being
4649/// copied are arrays, this routine builds for loops to copy them.
4650///
4651/// \param S The Sema object used for type-checking.
4652///
4653/// \param Loc The location where the implicit copy is being generated.
4654///
4655/// \param T The type of the expressions being copied. Both expressions must
4656/// have this type.
4657///
4658/// \param To The expression we are copying to.
4659///
4660/// \param From The expression we are copying from.
4661///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004662/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4663/// Otherwise, it's a non-static member subobject.
4664///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004665/// \param Depth Internal parameter recording the depth of the recursion.
4666///
4667/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004668static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004669BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004670 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004671 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004672 // C++0x [class.copy]p30:
4673 // Each subobject is assigned in the manner appropriate to its type:
4674 //
4675 // - if the subobject is of class type, the copy assignment operator
4676 // for the class is used (as if by explicit qualification; that is,
4677 // ignoring any possible virtual overriding functions in more derived
4678 // classes);
4679 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4680 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4681
4682 // Look for operator=.
4683 DeclarationName Name
4684 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4685 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4686 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4687
4688 // Filter out any result that isn't a copy-assignment operator.
4689 LookupResult::Filter F = OpLookup.makeFilter();
4690 while (F.hasNext()) {
4691 NamedDecl *D = F.next();
4692 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4693 if (Method->isCopyAssignmentOperator())
4694 continue;
4695
4696 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004697 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004698 F.done();
4699
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004700 // Suppress the protected check (C++ [class.protected]) for each of the
4701 // assignment operators we found. This strange dance is required when
4702 // we're assigning via a base classes's copy-assignment operator. To
4703 // ensure that we're getting the right base class subobject (without
4704 // ambiguities), we need to cast "this" to that subobject type; to
4705 // ensure that we don't go through the virtual call mechanism, we need
4706 // to qualify the operator= name with the base class (see below). However,
4707 // this means that if the base class has a protected copy assignment
4708 // operator, the protected member access check will fail. So, we
4709 // rewrite "protected" access to "public" access in this case, since we
4710 // know by construction that we're calling from a derived class.
4711 if (CopyingBaseSubobject) {
4712 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4713 L != LEnd; ++L) {
4714 if (L.getAccess() == AS_protected)
4715 L.setAccess(AS_public);
4716 }
4717 }
4718
Douglas Gregorb139cd52010-05-01 20:49:11 +00004719 // Create the nested-name-specifier that will be used to qualify the
4720 // reference to operator=; this is required to suppress the virtual
4721 // call mechanism.
4722 CXXScopeSpec SS;
4723 SS.setRange(Loc);
4724 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4725 T.getTypePtr()));
4726
4727 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004728 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004729 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004730 /*FirstQualifierInScope=*/0, OpLookup,
4731 /*TemplateArgs=*/0,
4732 /*SuppressQualifierCheck=*/true);
4733 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004734 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004735
4736 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004737
John McCalldadc5752010-08-24 06:29:42 +00004738 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004739 OpEqualRef.takeAs<Expr>(),
4740 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004741 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004742 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004743
4744 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004745 }
John McCallab8c2732010-03-16 06:11:48 +00004746
Douglas Gregorb139cd52010-05-01 20:49:11 +00004747 // - if the subobject is of scalar type, the built-in assignment
4748 // operator is used.
4749 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4750 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004751 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004752 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004753 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004754
4755 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004756 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004757
4758 // - if the subobject is an array, each element is assigned, in the
4759 // manner appropriate to the element type;
4760
4761 // Construct a loop over the array bounds, e.g.,
4762 //
4763 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4764 //
4765 // that will copy each of the array elements.
4766 QualType SizeType = S.Context.getSizeType();
4767
4768 // Create the iteration variable.
4769 IdentifierInfo *IterationVarName = 0;
4770 {
4771 llvm::SmallString<8> Str;
4772 llvm::raw_svector_ostream OS(Str);
4773 OS << "__i" << Depth;
4774 IterationVarName = &S.Context.Idents.get(OS.str());
4775 }
4776 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4777 IterationVarName, SizeType,
4778 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004779 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004780
4781 // Initialize the iteration variable to zero.
4782 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004783 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004784
4785 // Create a reference to the iteration variable; we'll use this several
4786 // times throughout.
4787 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004788 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004789 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4790
4791 // Create the DeclStmt that holds the iteration variable.
4792 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4793
4794 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004795 llvm::APInt Upper
4796 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004797 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004798 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004799 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4800 BO_NE, S.Context.BoolTy,
4801 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004802
4803 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004804 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004805 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4806 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004807
4808 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004809 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4810 IterationVarRef, Loc));
4811 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4812 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004813
4814 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004815 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4816 To, From, CopyingBaseSubobject,
4817 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004818 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004819 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004820
4821 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004822 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004823 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004824 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004825 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004826}
4827
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004828/// \brief Determine whether the given class has a copy assignment operator
4829/// that accepts a const-qualified argument.
4830static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4831 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4832
4833 if (!Class->hasDeclaredCopyAssignment())
4834 S.DeclareImplicitCopyAssignment(Class);
4835
4836 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4837 DeclarationName OpName
4838 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4839
4840 DeclContext::lookup_const_iterator Op, OpEnd;
4841 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4842 // C++ [class.copy]p9:
4843 // A user-declared copy assignment operator is a non-static non-template
4844 // member function of class X with exactly one parameter of type X, X&,
4845 // const X&, volatile X& or const volatile X&.
4846 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4847 if (!Method)
4848 continue;
4849
4850 if (Method->isStatic())
4851 continue;
4852 if (Method->getPrimaryTemplate())
4853 continue;
4854 const FunctionProtoType *FnType =
4855 Method->getType()->getAs<FunctionProtoType>();
4856 assert(FnType && "Overloaded operator has no prototype.");
4857 // Don't assert on this; an invalid decl might have been left in the AST.
4858 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4859 continue;
4860 bool AcceptsConst = true;
4861 QualType ArgType = FnType->getArgType(0);
4862 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4863 ArgType = Ref->getPointeeType();
4864 // Is it a non-const lvalue reference?
4865 if (!ArgType.isConstQualified())
4866 AcceptsConst = false;
4867 }
4868 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4869 continue;
4870
4871 // We have a single argument of type cv X or cv X&, i.e. we've found the
4872 // copy assignment operator. Return whether it accepts const arguments.
4873 return AcceptsConst;
4874 }
4875 assert(Class->isInvalidDecl() &&
4876 "No copy assignment operator declared in valid code.");
4877 return false;
4878}
4879
Douglas Gregor0be31a22010-07-02 17:43:08 +00004880CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004881 // Note: The following rules are largely analoguous to the copy
4882 // constructor rules. Note that virtual bases are not taken into account
4883 // for determining the argument type of the operator. Note also that
4884 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004885
4886
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004887 // C++ [class.copy]p10:
4888 // If the class definition does not explicitly declare a copy
4889 // assignment operator, one is declared implicitly.
4890 // The implicitly-defined copy assignment operator for a class X
4891 // will have the form
4892 //
4893 // X& X::operator=(const X&)
4894 //
4895 // if
4896 bool HasConstCopyAssignment = true;
4897
4898 // -- each direct base class B of X has a copy assignment operator
4899 // whose parameter is of type const B&, const volatile B& or B,
4900 // and
4901 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4902 BaseEnd = ClassDecl->bases_end();
4903 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4904 assert(!Base->getType()->isDependentType() &&
4905 "Cannot generate implicit members for class with dependent bases.");
4906 const CXXRecordDecl *BaseClassDecl
4907 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004908 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004909 }
4910
4911 // -- for all the nonstatic data members of X that are of a class
4912 // type M (or array thereof), each such class type has a copy
4913 // assignment operator whose parameter is of type const M&,
4914 // const volatile M& or M.
4915 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4916 FieldEnd = ClassDecl->field_end();
4917 HasConstCopyAssignment && Field != FieldEnd;
4918 ++Field) {
4919 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4920 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4921 const CXXRecordDecl *FieldClassDecl
4922 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004923 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004924 }
4925 }
4926
4927 // Otherwise, the implicitly declared copy assignment operator will
4928 // have the form
4929 //
4930 // X& X::operator=(X&)
4931 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4932 QualType RetType = Context.getLValueReferenceType(ArgType);
4933 if (HasConstCopyAssignment)
4934 ArgType = ArgType.withConst();
4935 ArgType = Context.getLValueReferenceType(ArgType);
4936
Douglas Gregor68e11362010-07-01 17:48:08 +00004937 // C++ [except.spec]p14:
4938 // An implicitly declared special member function (Clause 12) shall have an
4939 // exception-specification. [...]
4940 ImplicitExceptionSpecification ExceptSpec(Context);
4941 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4942 BaseEnd = ClassDecl->bases_end();
4943 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004944 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004945 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004946
4947 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4948 DeclareImplicitCopyAssignment(BaseClassDecl);
4949
Douglas Gregor68e11362010-07-01 17:48:08 +00004950 if (CXXMethodDecl *CopyAssign
4951 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4952 ExceptSpec.CalledDecl(CopyAssign);
4953 }
4954 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4955 FieldEnd = ClassDecl->field_end();
4956 Field != FieldEnd;
4957 ++Field) {
4958 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4959 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004960 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004961 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004962
4963 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4964 DeclareImplicitCopyAssignment(FieldClassDecl);
4965
Douglas Gregor68e11362010-07-01 17:48:08 +00004966 if (CXXMethodDecl *CopyAssign
4967 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4968 ExceptSpec.CalledDecl(CopyAssign);
4969 }
4970 }
4971
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004972 // An implicitly-declared copy assignment operator is an inline public
4973 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004974 FunctionProtoType::ExtProtoInfo EPI;
4975 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4976 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4977 EPI.NumExceptions = ExceptSpec.size();
4978 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004979 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004980 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004981 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004982 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004983 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004984 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004985 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004986 /*isInline=*/true);
4987 CopyAssignment->setAccess(AS_public);
4988 CopyAssignment->setImplicit();
4989 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004990
4991 // Add the parameter to the operator.
4992 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4993 ClassDecl->getLocation(),
4994 /*Id=*/0,
4995 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004996 SC_None,
4997 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004998 CopyAssignment->setParams(&FromParam, 1);
4999
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005000 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005001 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5002
Douglas Gregor0be31a22010-07-02 17:43:08 +00005003 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005004 PushOnScopeChains(CopyAssignment, S, false);
5005 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005006
5007 AddOverriddenMethods(ClassDecl, CopyAssignment);
5008 return CopyAssignment;
5009}
5010
Douglas Gregorb139cd52010-05-01 20:49:11 +00005011void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5012 CXXMethodDecl *CopyAssignOperator) {
5013 assert((CopyAssignOperator->isImplicit() &&
5014 CopyAssignOperator->isOverloadedOperator() &&
5015 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005016 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005017 "DefineImplicitCopyAssignment called for wrong function");
5018
5019 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5020
5021 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5022 CopyAssignOperator->setInvalidDecl();
5023 return;
5024 }
5025
5026 CopyAssignOperator->setUsed();
5027
5028 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005029 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005030
5031 // C++0x [class.copy]p30:
5032 // The implicitly-defined or explicitly-defaulted copy assignment operator
5033 // for a non-union class X performs memberwise copy assignment of its
5034 // subobjects. The direct base classes of X are assigned first, in the
5035 // order of their declaration in the base-specifier-list, and then the
5036 // immediate non-static data members of X are assigned, in the order in
5037 // which they were declared in the class definition.
5038
5039 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005040 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005041
5042 // The parameter for the "other" object, which we are copying from.
5043 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5044 Qualifiers OtherQuals = Other->getType().getQualifiers();
5045 QualType OtherRefType = Other->getType();
5046 if (const LValueReferenceType *OtherRef
5047 = OtherRefType->getAs<LValueReferenceType>()) {
5048 OtherRefType = OtherRef->getPointeeType();
5049 OtherQuals = OtherRefType.getQualifiers();
5050 }
5051
5052 // Our location for everything implicitly-generated.
5053 SourceLocation Loc = CopyAssignOperator->getLocation();
5054
5055 // Construct a reference to the "other" object. We'll be using this
5056 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005057 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005058 assert(OtherRef && "Reference to parameter cannot fail!");
5059
5060 // Construct the "this" pointer. We'll be using this throughout the generated
5061 // ASTs.
5062 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5063 assert(This && "Reference to this cannot fail!");
5064
5065 // Assign base classes.
5066 bool Invalid = false;
5067 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5068 E = ClassDecl->bases_end(); Base != E; ++Base) {
5069 // Form the assignment:
5070 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5071 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005072 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005073 Invalid = true;
5074 continue;
5075 }
5076
John McCallcf142162010-08-07 06:22:56 +00005077 CXXCastPath BasePath;
5078 BasePath.push_back(Base);
5079
Douglas Gregorb139cd52010-05-01 20:49:11 +00005080 // Construct the "from" expression, which is an implicit cast to the
5081 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005082 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005083 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005084 CK_UncheckedDerivedToBase,
5085 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005086
5087 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005088 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005089
5090 // Implicitly cast "this" to the appropriately-qualified base type.
5091 Expr *ToE = To.takeAs<Expr>();
5092 ImpCastExprToType(ToE,
5093 Context.getCVRQualifiedType(BaseType,
5094 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005095 CK_UncheckedDerivedToBase,
5096 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005097 To = Owned(ToE);
5098
5099 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005100 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005101 To.get(), From,
5102 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005103 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005104 Diag(CurrentLocation, diag::note_member_synthesized_at)
5105 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5106 CopyAssignOperator->setInvalidDecl();
5107 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005108 }
5109
5110 // Success! Record the copy.
5111 Statements.push_back(Copy.takeAs<Expr>());
5112 }
5113
5114 // \brief Reference to the __builtin_memcpy function.
5115 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005116 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005117 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005118
5119 // Assign non-static members.
5120 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5121 FieldEnd = ClassDecl->field_end();
5122 Field != FieldEnd; ++Field) {
5123 // Check for members of reference type; we can't copy those.
5124 if (Field->getType()->isReferenceType()) {
5125 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5126 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5127 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005128 Diag(CurrentLocation, diag::note_member_synthesized_at)
5129 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005130 Invalid = true;
5131 continue;
5132 }
5133
5134 // Check for members of const-qualified, non-class type.
5135 QualType BaseType = Context.getBaseElementType(Field->getType());
5136 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5137 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5138 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5139 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005140 Diag(CurrentLocation, diag::note_member_synthesized_at)
5141 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005142 Invalid = true;
5143 continue;
5144 }
5145
5146 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005147 if (FieldType->isIncompleteArrayType()) {
5148 assert(ClassDecl->hasFlexibleArrayMember() &&
5149 "Incomplete array type is not valid");
5150 continue;
5151 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005152
5153 // Build references to the field in the object we're copying from and to.
5154 CXXScopeSpec SS; // Intentionally empty
5155 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5156 LookupMemberName);
5157 MemberLookup.addDecl(*Field);
5158 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005159 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005160 Loc, /*IsArrow=*/false,
5161 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005162 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005163 Loc, /*IsArrow=*/true,
5164 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005165 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5166 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5167
5168 // If the field should be copied with __builtin_memcpy rather than via
5169 // explicit assignments, do so. This optimization only applies for arrays
5170 // of scalars and arrays of class type with trivial copy-assignment
5171 // operators.
5172 if (FieldType->isArrayType() &&
5173 (!BaseType->isRecordType() ||
5174 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5175 ->hasTrivialCopyAssignment())) {
5176 // Compute the size of the memory buffer to be copied.
5177 QualType SizeType = Context.getSizeType();
5178 llvm::APInt Size(Context.getTypeSize(SizeType),
5179 Context.getTypeSizeInChars(BaseType).getQuantity());
5180 for (const ConstantArrayType *Array
5181 = Context.getAsConstantArrayType(FieldType);
5182 Array;
5183 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005184 llvm::APInt ArraySize
5185 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005186 Size *= ArraySize;
5187 }
5188
5189 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005190 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5191 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005192
5193 bool NeedsCollectableMemCpy =
5194 (BaseType->isRecordType() &&
5195 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5196
5197 if (NeedsCollectableMemCpy) {
5198 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005199 // Create a reference to the __builtin_objc_memmove_collectable function.
5200 LookupResult R(*this,
5201 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005202 Loc, LookupOrdinaryName);
5203 LookupName(R, TUScope, true);
5204
5205 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5206 if (!CollectableMemCpy) {
5207 // Something went horribly wrong earlier, and we will have
5208 // complained about it.
5209 Invalid = true;
5210 continue;
5211 }
5212
5213 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5214 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005215 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005216 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5217 }
5218 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005219 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005220 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005221 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5222 LookupOrdinaryName);
5223 LookupName(R, TUScope, true);
5224
5225 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5226 if (!BuiltinMemCpy) {
5227 // Something went horribly wrong earlier, and we will have complained
5228 // about it.
5229 Invalid = true;
5230 continue;
5231 }
5232
5233 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5234 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005235 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005236 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5237 }
5238
John McCall37ad5512010-08-23 06:44:23 +00005239 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005240 CallArgs.push_back(To.takeAs<Expr>());
5241 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005242 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005243 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005244 if (NeedsCollectableMemCpy)
5245 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005246 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005247 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005248 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005249 else
5250 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005251 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005252 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005253 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005254
Douglas Gregorb139cd52010-05-01 20:49:11 +00005255 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5256 Statements.push_back(Call.takeAs<Expr>());
5257 continue;
5258 }
5259
5260 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005261 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005262 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005263 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005264 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005265 Diag(CurrentLocation, diag::note_member_synthesized_at)
5266 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5267 CopyAssignOperator->setInvalidDecl();
5268 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005269 }
5270
5271 // Success! Record the copy.
5272 Statements.push_back(Copy.takeAs<Stmt>());
5273 }
5274
5275 if (!Invalid) {
5276 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005277 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005278
John McCalldadc5752010-08-24 06:29:42 +00005279 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005280 if (Return.isInvalid())
5281 Invalid = true;
5282 else {
5283 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005284
5285 if (Trap.hasErrorOccurred()) {
5286 Diag(CurrentLocation, diag::note_member_synthesized_at)
5287 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5288 Invalid = true;
5289 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005290 }
5291 }
5292
5293 if (Invalid) {
5294 CopyAssignOperator->setInvalidDecl();
5295 return;
5296 }
5297
John McCalldadc5752010-08-24 06:29:42 +00005298 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005299 /*isStmtExpr=*/false);
5300 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5301 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005302}
5303
Douglas Gregor0be31a22010-07-02 17:43:08 +00005304CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5305 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005306 // C++ [class.copy]p4:
5307 // If the class definition does not explicitly declare a copy
5308 // constructor, one is declared implicitly.
5309
Douglas Gregor54be3392010-07-01 17:57:27 +00005310 // C++ [class.copy]p5:
5311 // The implicitly-declared copy constructor for a class X will
5312 // have the form
5313 //
5314 // X::X(const X&)
5315 //
5316 // if
5317 bool HasConstCopyConstructor = true;
5318
5319 // -- each direct or virtual base class B of X has a copy
5320 // constructor whose first parameter is of type const B& or
5321 // const volatile B&, and
5322 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5323 BaseEnd = ClassDecl->bases_end();
5324 HasConstCopyConstructor && Base != BaseEnd;
5325 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005326 // Virtual bases are handled below.
5327 if (Base->isVirtual())
5328 continue;
5329
Douglas Gregora6d69502010-07-02 23:41:54 +00005330 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005331 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005332 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5333 DeclareImplicitCopyConstructor(BaseClassDecl);
5334
Douglas Gregorcfe68222010-07-01 18:27:03 +00005335 HasConstCopyConstructor
5336 = BaseClassDecl->hasConstCopyConstructor(Context);
5337 }
5338
5339 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5340 BaseEnd = ClassDecl->vbases_end();
5341 HasConstCopyConstructor && Base != BaseEnd;
5342 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005343 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005344 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005345 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5346 DeclareImplicitCopyConstructor(BaseClassDecl);
5347
Douglas Gregor54be3392010-07-01 17:57:27 +00005348 HasConstCopyConstructor
5349 = BaseClassDecl->hasConstCopyConstructor(Context);
5350 }
5351
5352 // -- for all the nonstatic data members of X that are of a
5353 // class type M (or array thereof), each such class type
5354 // has a copy constructor whose first parameter is of type
5355 // const M& or const volatile M&.
5356 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5357 FieldEnd = ClassDecl->field_end();
5358 HasConstCopyConstructor && Field != FieldEnd;
5359 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005360 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005361 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005362 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005363 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005364 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5365 DeclareImplicitCopyConstructor(FieldClassDecl);
5366
Douglas Gregor54be3392010-07-01 17:57:27 +00005367 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005368 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005369 }
5370 }
5371
5372 // Otherwise, the implicitly declared copy constructor will have
5373 // the form
5374 //
5375 // X::X(X&)
5376 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5377 QualType ArgType = ClassType;
5378 if (HasConstCopyConstructor)
5379 ArgType = ArgType.withConst();
5380 ArgType = Context.getLValueReferenceType(ArgType);
5381
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005382 // C++ [except.spec]p14:
5383 // An implicitly declared special member function (Clause 12) shall have an
5384 // exception-specification. [...]
5385 ImplicitExceptionSpecification ExceptSpec(Context);
5386 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5387 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5388 BaseEnd = ClassDecl->bases_end();
5389 Base != BaseEnd;
5390 ++Base) {
5391 // Virtual bases are handled below.
5392 if (Base->isVirtual())
5393 continue;
5394
Douglas Gregora6d69502010-07-02 23:41:54 +00005395 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005396 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005397 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5398 DeclareImplicitCopyConstructor(BaseClassDecl);
5399
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005400 if (CXXConstructorDecl *CopyConstructor
5401 = BaseClassDecl->getCopyConstructor(Context, Quals))
5402 ExceptSpec.CalledDecl(CopyConstructor);
5403 }
5404 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5405 BaseEnd = ClassDecl->vbases_end();
5406 Base != BaseEnd;
5407 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005408 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005409 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005410 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5411 DeclareImplicitCopyConstructor(BaseClassDecl);
5412
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005413 if (CXXConstructorDecl *CopyConstructor
5414 = BaseClassDecl->getCopyConstructor(Context, Quals))
5415 ExceptSpec.CalledDecl(CopyConstructor);
5416 }
5417 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5418 FieldEnd = ClassDecl->field_end();
5419 Field != FieldEnd;
5420 ++Field) {
5421 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5422 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005423 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005424 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005425 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5426 DeclareImplicitCopyConstructor(FieldClassDecl);
5427
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005428 if (CXXConstructorDecl *CopyConstructor
5429 = FieldClassDecl->getCopyConstructor(Context, Quals))
5430 ExceptSpec.CalledDecl(CopyConstructor);
5431 }
5432 }
5433
Douglas Gregor54be3392010-07-01 17:57:27 +00005434 // An implicitly-declared copy constructor is an inline public
5435 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005436 FunctionProtoType::ExtProtoInfo EPI;
5437 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5438 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5439 EPI.NumExceptions = ExceptSpec.size();
5440 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005441 DeclarationName Name
5442 = Context.DeclarationNames.getCXXConstructorName(
5443 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005444 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005445 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005446 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005447 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005448 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005449 /*TInfo=*/0,
5450 /*isExplicit=*/false,
5451 /*isInline=*/true,
5452 /*isImplicitlyDeclared=*/true);
5453 CopyConstructor->setAccess(AS_public);
5454 CopyConstructor->setImplicit();
5455 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5456
Douglas Gregora6d69502010-07-02 23:41:54 +00005457 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005458 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5459
Douglas Gregor54be3392010-07-01 17:57:27 +00005460 // Add the parameter to the constructor.
5461 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5462 ClassDecl->getLocation(),
5463 /*IdentifierInfo=*/0,
5464 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005465 SC_None,
5466 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005467 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005468 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005469 PushOnScopeChains(CopyConstructor, S, false);
5470 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005471
5472 return CopyConstructor;
5473}
5474
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005475void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5476 CXXConstructorDecl *CopyConstructor,
5477 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005478 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005479 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005480 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005481 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005482
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005483 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005484 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005485
Douglas Gregora57478e2010-05-01 15:04:51 +00005486 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005487 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005488
Alexis Hunt1d792652011-01-08 20:30:50 +00005489 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005490 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005491 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005492 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005493 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005494 } else {
5495 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5496 CopyConstructor->getLocation(),
5497 MultiStmtArg(*this, 0, 0),
5498 /*isStmtExpr=*/false)
5499 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005500 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005501
5502 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005503}
5504
John McCalldadc5752010-08-24 06:29:42 +00005505ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005506Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005507 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005508 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005509 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005510 unsigned ConstructKind,
5511 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005512 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005513
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005514 // C++0x [class.copy]p34:
5515 // When certain criteria are met, an implementation is allowed to
5516 // omit the copy/move construction of a class object, even if the
5517 // copy/move constructor and/or destructor for the object have
5518 // side effects. [...]
5519 // - when a temporary class object that has not been bound to a
5520 // reference (12.2) would be copied/moved to a class object
5521 // with the same cv-unqualified type, the copy/move operation
5522 // can be omitted by constructing the temporary object
5523 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005524 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5525 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005526 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005527 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005528 }
Mike Stump11289f42009-09-09 15:08:12 +00005529
5530 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005531 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005532 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005533}
5534
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005535/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5536/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005537ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005538Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5539 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005540 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005541 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005542 unsigned ConstructKind,
5543 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005544 unsigned NumExprs = ExprArgs.size();
5545 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005546
Douglas Gregor27381f32009-11-23 12:27:39 +00005547 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005548 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005549 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005550 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005551 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5552 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005553}
5554
Mike Stump11289f42009-09-09 15:08:12 +00005555bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005556 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005557 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005558 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005559 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005560 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005561 move(Exprs), false, CXXConstructExpr::CK_Complete,
5562 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005563 if (TempResult.isInvalid())
5564 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005565
Anders Carlsson6eb55572009-08-25 05:12:04 +00005566 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005567 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005568 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005569 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005570 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005571
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005572 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005573}
5574
John McCall03c48482010-02-02 09:10:11 +00005575void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5576 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005577 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005578 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005579 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005580 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005581 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005582 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005583 << VD->getDeclName()
5584 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005585
John McCall386dfc72010-09-18 05:25:11 +00005586 // TODO: this should be re-enabled for static locals by !CXAAtExit
5587 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005588 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005589 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005590}
5591
Mike Stump11289f42009-09-09 15:08:12 +00005592/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005593/// ActOnDeclarator, when a C++ direct initializer is present.
5594/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005595void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005596 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005597 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005598 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005599 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005600
5601 // If there is no declaration, there was an error parsing it. Just ignore
5602 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005603 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005604 return;
Mike Stump11289f42009-09-09 15:08:12 +00005605
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005606 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5607 if (!VDecl) {
5608 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5609 RealDecl->setInvalidDecl();
5610 return;
5611 }
5612
Douglas Gregor402250f2009-08-26 21:14:46 +00005613 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005614 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005615 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5616 //
5617 // Clients that want to distinguish between the two forms, can check for
5618 // direct initializer using VarDecl::hasCXXDirectInitializer().
5619 // A major benefit is that clients that don't particularly care about which
5620 // exactly form was it (like the CodeGen) can handle both cases without
5621 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005622
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005623 // C++ 8.5p11:
5624 // The form of initialization (using parentheses or '=') is generally
5625 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005626 // class type.
5627
Douglas Gregor50dc2192010-02-11 22:55:30 +00005628 if (!VDecl->getType()->isDependentType() &&
5629 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005630 diag::err_typecheck_decl_incomplete_type)) {
5631 VDecl->setInvalidDecl();
5632 return;
5633 }
5634
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005635 // The variable can not have an abstract class type.
5636 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5637 diag::err_abstract_type_in_decl,
5638 AbstractVariableType))
5639 VDecl->setInvalidDecl();
5640
Sebastian Redl5ca79842010-02-01 20:16:42 +00005641 const VarDecl *Def;
5642 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005643 Diag(VDecl->getLocation(), diag::err_redefinition)
5644 << VDecl->getDeclName();
5645 Diag(Def->getLocation(), diag::note_previous_definition);
5646 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005647 return;
5648 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005649
Douglas Gregorf0f83692010-08-24 05:27:49 +00005650 // C++ [class.static.data]p4
5651 // If a static data member is of const integral or const
5652 // enumeration type, its declaration in the class definition can
5653 // specify a constant-initializer which shall be an integral
5654 // constant expression (5.19). In that case, the member can appear
5655 // in integral constant expressions. The member shall still be
5656 // defined in a namespace scope if it is used in the program and the
5657 // namespace scope definition shall not contain an initializer.
5658 //
5659 // We already performed a redefinition check above, but for static
5660 // data members we also need to check whether there was an in-class
5661 // declaration with an initializer.
5662 const VarDecl* PrevInit = 0;
5663 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5664 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5665 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5666 return;
5667 }
5668
Douglas Gregor71f39c92010-12-16 01:31:22 +00005669 bool IsDependent = false;
5670 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5671 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5672 VDecl->setInvalidDecl();
5673 return;
5674 }
5675
5676 if (Exprs.get()[I]->isTypeDependent())
5677 IsDependent = true;
5678 }
5679
Douglas Gregor50dc2192010-02-11 22:55:30 +00005680 // If either the declaration has a dependent type or if any of the
5681 // expressions is type-dependent, we represent the initialization
5682 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005683 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005684 // Let clients know that initialization was done with a direct initializer.
5685 VDecl->setCXXDirectInitializer(true);
5686
5687 // Store the initialization expressions as a ParenListExpr.
5688 unsigned NumExprs = Exprs.size();
5689 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5690 (Expr **)Exprs.release(),
5691 NumExprs, RParenLoc));
5692 return;
5693 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005694
5695 // Capture the variable that is being initialized and the style of
5696 // initialization.
5697 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5698
5699 // FIXME: Poor source location information.
5700 InitializationKind Kind
5701 = InitializationKind::CreateDirect(VDecl->getLocation(),
5702 LParenLoc, RParenLoc);
5703
5704 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005705 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005706 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005707 if (Result.isInvalid()) {
5708 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005709 return;
5710 }
John McCallacf0ee52010-10-08 02:01:28 +00005711
5712 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005713
Douglas Gregora40433a2010-12-07 00:41:46 +00005714 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005715 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005716 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005717
John McCall8b7fd8f12011-01-19 11:48:09 +00005718 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005719}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005720
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005721/// \brief Given a constructor and the set of arguments provided for the
5722/// constructor, convert the arguments and add any required default arguments
5723/// to form a proper call to this constructor.
5724///
5725/// \returns true if an error occurred, false otherwise.
5726bool
5727Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5728 MultiExprArg ArgsPtr,
5729 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005730 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005731 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5732 unsigned NumArgs = ArgsPtr.size();
5733 Expr **Args = (Expr **)ArgsPtr.get();
5734
5735 const FunctionProtoType *Proto
5736 = Constructor->getType()->getAs<FunctionProtoType>();
5737 assert(Proto && "Constructor without a prototype?");
5738 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005739
5740 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005741 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005742 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005743 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005744 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005745
5746 VariadicCallType CallType =
5747 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5748 llvm::SmallVector<Expr *, 8> AllArgs;
5749 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5750 Proto, 0, Args, NumArgs, AllArgs,
5751 CallType);
5752 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5753 ConvertedArgs.push_back(AllArgs[i]);
5754 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005755}
5756
Anders Carlssone363c8e2009-12-12 00:32:00 +00005757static inline bool
5758CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5759 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005760 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005761 if (isa<NamespaceDecl>(DC)) {
5762 return SemaRef.Diag(FnDecl->getLocation(),
5763 diag::err_operator_new_delete_declared_in_namespace)
5764 << FnDecl->getDeclName();
5765 }
5766
5767 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005768 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005769 return SemaRef.Diag(FnDecl->getLocation(),
5770 diag::err_operator_new_delete_declared_static)
5771 << FnDecl->getDeclName();
5772 }
5773
Anders Carlsson60659a82009-12-12 02:43:16 +00005774 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005775}
5776
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005777static inline bool
5778CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5779 CanQualType ExpectedResultType,
5780 CanQualType ExpectedFirstParamType,
5781 unsigned DependentParamTypeDiag,
5782 unsigned InvalidParamTypeDiag) {
5783 QualType ResultType =
5784 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5785
5786 // Check that the result type is not dependent.
5787 if (ResultType->isDependentType())
5788 return SemaRef.Diag(FnDecl->getLocation(),
5789 diag::err_operator_new_delete_dependent_result_type)
5790 << FnDecl->getDeclName() << ExpectedResultType;
5791
5792 // Check that the result type is what we expect.
5793 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5794 return SemaRef.Diag(FnDecl->getLocation(),
5795 diag::err_operator_new_delete_invalid_result_type)
5796 << FnDecl->getDeclName() << ExpectedResultType;
5797
5798 // A function template must have at least 2 parameters.
5799 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5800 return SemaRef.Diag(FnDecl->getLocation(),
5801 diag::err_operator_new_delete_template_too_few_parameters)
5802 << FnDecl->getDeclName();
5803
5804 // The function decl must have at least 1 parameter.
5805 if (FnDecl->getNumParams() == 0)
5806 return SemaRef.Diag(FnDecl->getLocation(),
5807 diag::err_operator_new_delete_too_few_parameters)
5808 << FnDecl->getDeclName();
5809
5810 // Check the the first parameter type is not dependent.
5811 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5812 if (FirstParamType->isDependentType())
5813 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5814 << FnDecl->getDeclName() << ExpectedFirstParamType;
5815
5816 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005817 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005818 ExpectedFirstParamType)
5819 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5820 << FnDecl->getDeclName() << ExpectedFirstParamType;
5821
5822 return false;
5823}
5824
Anders Carlsson12308f42009-12-11 23:23:22 +00005825static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005826CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005827 // C++ [basic.stc.dynamic.allocation]p1:
5828 // A program is ill-formed if an allocation function is declared in a
5829 // namespace scope other than global scope or declared static in global
5830 // scope.
5831 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5832 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005833
5834 CanQualType SizeTy =
5835 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5836
5837 // C++ [basic.stc.dynamic.allocation]p1:
5838 // The return type shall be void*. The first parameter shall have type
5839 // std::size_t.
5840 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5841 SizeTy,
5842 diag::err_operator_new_dependent_param_type,
5843 diag::err_operator_new_param_type))
5844 return true;
5845
5846 // C++ [basic.stc.dynamic.allocation]p1:
5847 // The first parameter shall not have an associated default argument.
5848 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005849 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005850 diag::err_operator_new_default_arg)
5851 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5852
5853 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005854}
5855
5856static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005857CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5858 // C++ [basic.stc.dynamic.deallocation]p1:
5859 // A program is ill-formed if deallocation functions are declared in a
5860 // namespace scope other than global scope or declared static in global
5861 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005862 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5863 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005864
5865 // C++ [basic.stc.dynamic.deallocation]p2:
5866 // Each deallocation function shall return void and its first parameter
5867 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005868 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5869 SemaRef.Context.VoidPtrTy,
5870 diag::err_operator_delete_dependent_param_type,
5871 diag::err_operator_delete_param_type))
5872 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005873
Anders Carlsson12308f42009-12-11 23:23:22 +00005874 return false;
5875}
5876
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005877/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5878/// of this overloaded operator is well-formed. If so, returns false;
5879/// otherwise, emits appropriate diagnostics and returns true.
5880bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005881 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005882 "Expected an overloaded operator declaration");
5883
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005884 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5885
Mike Stump11289f42009-09-09 15:08:12 +00005886 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005887 // The allocation and deallocation functions, operator new,
5888 // operator new[], operator delete and operator delete[], are
5889 // described completely in 3.7.3. The attributes and restrictions
5890 // found in the rest of this subclause do not apply to them unless
5891 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005892 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005893 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005894
Anders Carlsson22f443f2009-12-12 00:26:23 +00005895 if (Op == OO_New || Op == OO_Array_New)
5896 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005897
5898 // C++ [over.oper]p6:
5899 // An operator function shall either be a non-static member
5900 // function or be a non-member function and have at least one
5901 // parameter whose type is a class, a reference to a class, an
5902 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005903 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5904 if (MethodDecl->isStatic())
5905 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005906 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005907 } else {
5908 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005909 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5910 ParamEnd = FnDecl->param_end();
5911 Param != ParamEnd; ++Param) {
5912 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005913 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5914 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005915 ClassOrEnumParam = true;
5916 break;
5917 }
5918 }
5919
Douglas Gregord69246b2008-11-17 16:14:12 +00005920 if (!ClassOrEnumParam)
5921 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005922 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005923 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005924 }
5925
5926 // C++ [over.oper]p8:
5927 // An operator function cannot have default arguments (8.3.6),
5928 // except where explicitly stated below.
5929 //
Mike Stump11289f42009-09-09 15:08:12 +00005930 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005931 // (C++ [over.call]p1).
5932 if (Op != OO_Call) {
5933 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5934 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005935 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005936 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005937 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005938 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005939 }
5940 }
5941
Douglas Gregor6cf08062008-11-10 13:38:07 +00005942 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5943 { false, false, false }
5944#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5945 , { Unary, Binary, MemberOnly }
5946#include "clang/Basic/OperatorKinds.def"
5947 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005948
Douglas Gregor6cf08062008-11-10 13:38:07 +00005949 bool CanBeUnaryOperator = OperatorUses[Op][0];
5950 bool CanBeBinaryOperator = OperatorUses[Op][1];
5951 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005952
5953 // C++ [over.oper]p8:
5954 // [...] Operator functions cannot have more or fewer parameters
5955 // than the number required for the corresponding operator, as
5956 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005957 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005958 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005959 if (Op != OO_Call &&
5960 ((NumParams == 1 && !CanBeUnaryOperator) ||
5961 (NumParams == 2 && !CanBeBinaryOperator) ||
5962 (NumParams < 1) || (NumParams > 2))) {
5963 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005964 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005965 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005966 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005967 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005968 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005969 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005970 assert(CanBeBinaryOperator &&
5971 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005972 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005973 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005974
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005975 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005976 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005977 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005978
Douglas Gregord69246b2008-11-17 16:14:12 +00005979 // Overloaded operators other than operator() cannot be variadic.
5980 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005981 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005982 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005983 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005984 }
5985
5986 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005987 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5988 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005989 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005990 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005991 }
5992
5993 // C++ [over.inc]p1:
5994 // The user-defined function called operator++ implements the
5995 // prefix and postfix ++ operator. If this function is a member
5996 // function with no parameters, or a non-member function with one
5997 // parameter of class or enumeration type, it defines the prefix
5998 // increment operator ++ for objects of that type. If the function
5999 // is a member function with one parameter (which shall be of type
6000 // int) or a non-member function with two parameters (the second
6001 // of which shall be of type int), it defines the postfix
6002 // increment operator ++ for objects of that type.
6003 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6004 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6005 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006006 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006007 ParamIsInt = BT->getKind() == BuiltinType::Int;
6008
Chris Lattner2b786902008-11-21 07:50:02 +00006009 if (!ParamIsInt)
6010 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006011 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006012 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006013 }
6014
Douglas Gregord69246b2008-11-17 16:14:12 +00006015 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006016}
Chris Lattner3b024a32008-12-17 07:09:26 +00006017
Alexis Huntc88db062010-01-13 09:01:02 +00006018/// CheckLiteralOperatorDeclaration - Check whether the declaration
6019/// of this literal operator function is well-formed. If so, returns
6020/// false; otherwise, emits appropriate diagnostics and returns true.
6021bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6022 DeclContext *DC = FnDecl->getDeclContext();
6023 Decl::Kind Kind = DC->getDeclKind();
6024 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6025 Kind != Decl::LinkageSpec) {
6026 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6027 << FnDecl->getDeclName();
6028 return true;
6029 }
6030
6031 bool Valid = false;
6032
Alexis Hunt7dd26172010-04-07 23:11:06 +00006033 // template <char...> type operator "" name() is the only valid template
6034 // signature, and the only valid signature with no parameters.
6035 if (FnDecl->param_size() == 0) {
6036 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6037 // Must have only one template parameter
6038 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6039 if (Params->size() == 1) {
6040 NonTypeTemplateParmDecl *PmDecl =
6041 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006042
Alexis Hunt7dd26172010-04-07 23:11:06 +00006043 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006044 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6045 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6046 Valid = true;
6047 }
6048 }
6049 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006050 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006051 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6052
Alexis Huntc88db062010-01-13 09:01:02 +00006053 QualType T = (*Param)->getType();
6054
Alexis Hunt079a6f72010-04-07 22:57:35 +00006055 // unsigned long long int, long double, and any character type are allowed
6056 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006057 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6058 Context.hasSameType(T, Context.LongDoubleTy) ||
6059 Context.hasSameType(T, Context.CharTy) ||
6060 Context.hasSameType(T, Context.WCharTy) ||
6061 Context.hasSameType(T, Context.Char16Ty) ||
6062 Context.hasSameType(T, Context.Char32Ty)) {
6063 if (++Param == FnDecl->param_end())
6064 Valid = true;
6065 goto FinishedParams;
6066 }
6067
Alexis Hunt079a6f72010-04-07 22:57:35 +00006068 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006069 const PointerType *PT = T->getAs<PointerType>();
6070 if (!PT)
6071 goto FinishedParams;
6072 T = PT->getPointeeType();
6073 if (!T.isConstQualified())
6074 goto FinishedParams;
6075 T = T.getUnqualifiedType();
6076
6077 // Move on to the second parameter;
6078 ++Param;
6079
6080 // If there is no second parameter, the first must be a const char *
6081 if (Param == FnDecl->param_end()) {
6082 if (Context.hasSameType(T, Context.CharTy))
6083 Valid = true;
6084 goto FinishedParams;
6085 }
6086
6087 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6088 // are allowed as the first parameter to a two-parameter function
6089 if (!(Context.hasSameType(T, Context.CharTy) ||
6090 Context.hasSameType(T, Context.WCharTy) ||
6091 Context.hasSameType(T, Context.Char16Ty) ||
6092 Context.hasSameType(T, Context.Char32Ty)))
6093 goto FinishedParams;
6094
6095 // The second and final parameter must be an std::size_t
6096 T = (*Param)->getType().getUnqualifiedType();
6097 if (Context.hasSameType(T, Context.getSizeType()) &&
6098 ++Param == FnDecl->param_end())
6099 Valid = true;
6100 }
6101
6102 // FIXME: This diagnostic is absolutely terrible.
6103FinishedParams:
6104 if (!Valid) {
6105 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6106 << FnDecl->getDeclName();
6107 return true;
6108 }
6109
6110 return false;
6111}
6112
Douglas Gregor07665a62009-01-05 19:45:36 +00006113/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6114/// linkage specification, including the language and (if present)
6115/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6116/// the location of the language string literal, which is provided
6117/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6118/// the '{' brace. Otherwise, this linkage specification does not
6119/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006120Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6121 SourceLocation LangLoc,
6122 llvm::StringRef Lang,
6123 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006124 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006125 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006126 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006127 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006128 Language = LinkageSpecDecl::lang_cxx;
6129 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006130 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006131 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006132 }
Mike Stump11289f42009-09-09 15:08:12 +00006133
Chris Lattner438e5012008-12-17 07:13:27 +00006134 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006135
Douglas Gregor07665a62009-01-05 19:45:36 +00006136 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006137 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006138 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006139 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006140 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006141 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006142}
6143
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006144/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006145/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6146/// valid, it's the position of the closing '}' brace in a linkage
6147/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006148Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6149 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006150 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006151 if (LinkageSpec)
6152 PopDeclContext();
6153 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006154}
6155
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006156/// \brief Perform semantic analysis for the variable declaration that
6157/// occurs within a C++ catch clause, returning the newly-created
6158/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006159VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006160 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006161 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006162 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006163 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006164 QualType ExDeclType = TInfo->getType();
6165
Sebastian Redl54c04d42008-12-22 19:15:10 +00006166 // Arrays and functions decay.
6167 if (ExDeclType->isArrayType())
6168 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6169 else if (ExDeclType->isFunctionType())
6170 ExDeclType = Context.getPointerType(ExDeclType);
6171
6172 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6173 // The exception-declaration shall not denote a pointer or reference to an
6174 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006175 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006176 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006177 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006178 Invalid = true;
6179 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006180
Douglas Gregor104ee002010-03-08 01:47:36 +00006181 // GCC allows catching pointers and references to incomplete types
6182 // as an extension; so do we, but we warn by default.
6183
Sebastian Redl54c04d42008-12-22 19:15:10 +00006184 QualType BaseType = ExDeclType;
6185 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006186 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006187 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006188 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006189 BaseType = Ptr->getPointeeType();
6190 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006191 DK = diag::ext_catch_incomplete_ptr;
6192 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006193 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006194 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006195 BaseType = Ref->getPointeeType();
6196 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006197 DK = diag::ext_catch_incomplete_ref;
6198 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006199 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006200 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006201 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6202 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006203 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006204
Mike Stump11289f42009-09-09 15:08:12 +00006205 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006206 RequireNonAbstractType(Loc, ExDeclType,
6207 diag::err_abstract_type_in_decl,
6208 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006209 Invalid = true;
6210
John McCall2ca705e2010-07-24 00:37:23 +00006211 // Only the non-fragile NeXT runtime currently supports C++ catches
6212 // of ObjC types, and no runtime supports catching ObjC types by value.
6213 if (!Invalid && getLangOptions().ObjC1) {
6214 QualType T = ExDeclType;
6215 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6216 T = RT->getPointeeType();
6217
6218 if (T->isObjCObjectType()) {
6219 Diag(Loc, diag::err_objc_object_catch);
6220 Invalid = true;
6221 } else if (T->isObjCObjectPointerType()) {
6222 if (!getLangOptions().NeXTRuntime) {
6223 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6224 Invalid = true;
6225 } else if (!getLangOptions().ObjCNonFragileABI) {
6226 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6227 Invalid = true;
6228 }
6229 }
6230 }
6231
Mike Stump11289f42009-09-09 15:08:12 +00006232 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006233 Name, ExDeclType, TInfo, SC_None,
6234 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006235 ExDecl->setExceptionVariable(true);
6236
Douglas Gregor6de584c2010-03-05 23:38:39 +00006237 if (!Invalid) {
6238 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6239 // C++ [except.handle]p16:
6240 // The object declared in an exception-declaration or, if the
6241 // exception-declaration does not specify a name, a temporary (12.2) is
6242 // copy-initialized (8.5) from the exception object. [...]
6243 // The object is destroyed when the handler exits, after the destruction
6244 // of any automatic objects initialized within the handler.
6245 //
6246 // We just pretend to initialize the object with itself, then make sure
6247 // it can be destroyed later.
6248 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6249 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006250 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006251 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6252 SourceLocation());
6253 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006254 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006255 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006256 if (Result.isInvalid())
6257 Invalid = true;
6258 else
6259 FinalizeVarWithDestructor(ExDecl, RecordTy);
6260 }
6261 }
6262
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006263 if (Invalid)
6264 ExDecl->setInvalidDecl();
6265
6266 return ExDecl;
6267}
6268
6269/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6270/// handler.
John McCall48871652010-08-21 09:40:31 +00006271Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006272 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006273 bool Invalid = D.isInvalidType();
6274
6275 // Check for unexpanded parameter packs.
6276 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6277 UPPC_ExceptionType)) {
6278 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6279 D.getIdentifierLoc());
6280 Invalid = true;
6281 }
6282
Sebastian Redl54c04d42008-12-22 19:15:10 +00006283 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006284 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006285 LookupOrdinaryName,
6286 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006287 // The scope should be freshly made just for us. There is just no way
6288 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006289 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006290 if (PrevDecl->isTemplateParameter()) {
6291 // Maybe we will complain about the shadowed template parameter.
6292 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006293 }
6294 }
6295
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006296 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006297 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6298 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006299 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006300 }
6301
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006302 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006303 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006304 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006305
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006306 if (Invalid)
6307 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006308
Sebastian Redl54c04d42008-12-22 19:15:10 +00006309 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006310 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006311 PushOnScopeChains(ExDecl, S);
6312 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006313 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006314
Douglas Gregor758a8692009-06-17 21:51:59 +00006315 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006316 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006317}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006318
John McCall48871652010-08-21 09:40:31 +00006319Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006320 Expr *AssertExpr,
6321 Expr *AssertMessageExpr_) {
6322 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006323
Anders Carlsson54b26982009-03-14 00:33:21 +00006324 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6325 llvm::APSInt Value(32);
6326 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6327 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6328 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006329 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006330 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006331
Anders Carlsson54b26982009-03-14 00:33:21 +00006332 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006333 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006334 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006335 }
6336 }
Mike Stump11289f42009-09-09 15:08:12 +00006337
Douglas Gregoref68fee2010-12-15 23:55:21 +00006338 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6339 return 0;
6340
Mike Stump11289f42009-09-09 15:08:12 +00006341 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006342 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006343
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006344 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006345 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006346}
Sebastian Redlf769df52009-03-24 22:27:57 +00006347
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006348/// \brief Perform semantic analysis of the given friend type declaration.
6349///
6350/// \returns A friend declaration that.
6351FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6352 TypeSourceInfo *TSInfo) {
6353 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6354
6355 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006356 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006357
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006358 if (!getLangOptions().CPlusPlus0x) {
6359 // C++03 [class.friend]p2:
6360 // An elaborated-type-specifier shall be used in a friend declaration
6361 // for a class.*
6362 //
6363 // * The class-key of the elaborated-type-specifier is required.
6364 if (!ActiveTemplateInstantiations.empty()) {
6365 // Do not complain about the form of friend template types during
6366 // template instantiation; we will already have complained when the
6367 // template was declared.
6368 } else if (!T->isElaboratedTypeSpecifier()) {
6369 // If we evaluated the type to a record type, suggest putting
6370 // a tag in front.
6371 if (const RecordType *RT = T->getAs<RecordType>()) {
6372 RecordDecl *RD = RT->getDecl();
6373
6374 std::string InsertionText = std::string(" ") + RD->getKindName();
6375
6376 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6377 << (unsigned) RD->getTagKind()
6378 << T
6379 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6380 InsertionText);
6381 } else {
6382 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6383 << T
6384 << SourceRange(FriendLoc, TypeRange.getEnd());
6385 }
6386 } else if (T->getAs<EnumType>()) {
6387 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006388 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006389 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006390 }
6391 }
6392
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006393 // C++0x [class.friend]p3:
6394 // If the type specifier in a friend declaration designates a (possibly
6395 // cv-qualified) class type, that class is declared as a friend; otherwise,
6396 // the friend declaration is ignored.
6397
6398 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6399 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006400
6401 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6402}
6403
John McCallace48cd2010-10-19 01:40:49 +00006404/// Handle a friend tag declaration where the scope specifier was
6405/// templated.
6406Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6407 unsigned TagSpec, SourceLocation TagLoc,
6408 CXXScopeSpec &SS,
6409 IdentifierInfo *Name, SourceLocation NameLoc,
6410 AttributeList *Attr,
6411 MultiTemplateParamsArg TempParamLists) {
6412 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6413
6414 bool isExplicitSpecialization = false;
6415 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6416 bool Invalid = false;
6417
6418 if (TemplateParameterList *TemplateParams
6419 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6420 TempParamLists.get(),
6421 TempParamLists.size(),
6422 /*friend*/ true,
6423 isExplicitSpecialization,
6424 Invalid)) {
6425 --NumMatchedTemplateParamLists;
6426
6427 if (TemplateParams->size() > 0) {
6428 // This is a declaration of a class template.
6429 if (Invalid)
6430 return 0;
6431
6432 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6433 SS, Name, NameLoc, Attr,
6434 TemplateParams, AS_public).take();
6435 } else {
6436 // The "template<>" header is extraneous.
6437 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6438 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6439 isExplicitSpecialization = true;
6440 }
6441 }
6442
6443 if (Invalid) return 0;
6444
6445 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6446
6447 bool isAllExplicitSpecializations = true;
6448 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6449 if (TempParamLists.get()[I]->size()) {
6450 isAllExplicitSpecializations = false;
6451 break;
6452 }
6453 }
6454
6455 // FIXME: don't ignore attributes.
6456
6457 // If it's explicit specializations all the way down, just forget
6458 // about the template header and build an appropriate non-templated
6459 // friend. TODO: for source fidelity, remember the headers.
6460 if (isAllExplicitSpecializations) {
6461 ElaboratedTypeKeyword Keyword
6462 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6463 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6464 TagLoc, SS.getRange(), NameLoc);
6465 if (T.isNull())
6466 return 0;
6467
6468 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6469 if (isa<DependentNameType>(T)) {
6470 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6471 TL.setKeywordLoc(TagLoc);
6472 TL.setQualifierRange(SS.getRange());
6473 TL.setNameLoc(NameLoc);
6474 } else {
6475 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6476 TL.setKeywordLoc(TagLoc);
6477 TL.setQualifierRange(SS.getRange());
6478 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6479 }
6480
6481 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6482 TSI, FriendLoc);
6483 Friend->setAccess(AS_public);
6484 CurContext->addDecl(Friend);
6485 return Friend;
6486 }
6487
6488 // Handle the case of a templated-scope friend class. e.g.
6489 // template <class T> class A<T>::B;
6490 // FIXME: we don't support these right now.
6491 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6492 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6493 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6494 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6495 TL.setKeywordLoc(TagLoc);
6496 TL.setQualifierRange(SS.getRange());
6497 TL.setNameLoc(NameLoc);
6498
6499 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6500 TSI, FriendLoc);
6501 Friend->setAccess(AS_public);
6502 Friend->setUnsupportedFriend(true);
6503 CurContext->addDecl(Friend);
6504 return Friend;
6505}
6506
6507
John McCall11083da2009-09-16 22:47:08 +00006508/// Handle a friend type declaration. This works in tandem with
6509/// ActOnTag.
6510///
6511/// Notes on friend class templates:
6512///
6513/// We generally treat friend class declarations as if they were
6514/// declaring a class. So, for example, the elaborated type specifier
6515/// in a friend declaration is required to obey the restrictions of a
6516/// class-head (i.e. no typedefs in the scope chain), template
6517/// parameters are required to match up with simple template-ids, &c.
6518/// However, unlike when declaring a template specialization, it's
6519/// okay to refer to a template specialization without an empty
6520/// template parameter declaration, e.g.
6521/// friend class A<T>::B<unsigned>;
6522/// We permit this as a special case; if there are any template
6523/// parameters present at all, require proper matching, i.e.
6524/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006525Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006526 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006527 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006528
6529 assert(DS.isFriendSpecified());
6530 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6531
John McCall11083da2009-09-16 22:47:08 +00006532 // Try to convert the decl specifier to a type. This works for
6533 // friend templates because ActOnTag never produces a ClassTemplateDecl
6534 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006535 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006536 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6537 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006538 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006539 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006540
Douglas Gregor6c110f32010-12-16 01:14:37 +00006541 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6542 return 0;
6543
John McCall11083da2009-09-16 22:47:08 +00006544 // This is definitely an error in C++98. It's probably meant to
6545 // be forbidden in C++0x, too, but the specification is just
6546 // poorly written.
6547 //
6548 // The problem is with declarations like the following:
6549 // template <T> friend A<T>::foo;
6550 // where deciding whether a class C is a friend or not now hinges
6551 // on whether there exists an instantiation of A that causes
6552 // 'foo' to equal C. There are restrictions on class-heads
6553 // (which we declare (by fiat) elaborated friend declarations to
6554 // be) that makes this tractable.
6555 //
6556 // FIXME: handle "template <> friend class A<T>;", which
6557 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006558 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006559 Diag(Loc, diag::err_tagless_friend_type_template)
6560 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006561 return 0;
John McCall11083da2009-09-16 22:47:08 +00006562 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006563
John McCallaa74a0c2009-08-28 07:59:38 +00006564 // C++98 [class.friend]p1: A friend of a class is a function
6565 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006566 // This is fixed in DR77, which just barely didn't make the C++03
6567 // deadline. It's also a very silly restriction that seriously
6568 // affects inner classes and which nobody else seems to implement;
6569 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006570 //
6571 // But note that we could warn about it: it's always useless to
6572 // friend one of your own members (it's not, however, worthless to
6573 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006574
John McCall11083da2009-09-16 22:47:08 +00006575 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006576 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006577 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006578 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006579 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006580 TSI,
John McCall11083da2009-09-16 22:47:08 +00006581 DS.getFriendSpecLoc());
6582 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006583 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6584
6585 if (!D)
John McCall48871652010-08-21 09:40:31 +00006586 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006587
John McCall11083da2009-09-16 22:47:08 +00006588 D->setAccess(AS_public);
6589 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006590
John McCall48871652010-08-21 09:40:31 +00006591 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006592}
6593
John McCallde3fd222010-10-12 23:13:28 +00006594Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6595 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006596 const DeclSpec &DS = D.getDeclSpec();
6597
6598 assert(DS.isFriendSpecified());
6599 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6600
6601 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006602 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6603 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006604
6605 // C++ [class.friend]p1
6606 // A friend of a class is a function or class....
6607 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006608 // It *doesn't* see through dependent types, which is correct
6609 // according to [temp.arg.type]p3:
6610 // If a declaration acquires a function type through a
6611 // type dependent on a template-parameter and this causes
6612 // a declaration that does not use the syntactic form of a
6613 // function declarator to have a function type, the program
6614 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006615 if (!T->isFunctionType()) {
6616 Diag(Loc, diag::err_unexpected_friend);
6617
6618 // It might be worthwhile to try to recover by creating an
6619 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006620 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006621 }
6622
6623 // C++ [namespace.memdef]p3
6624 // - If a friend declaration in a non-local class first declares a
6625 // class or function, the friend class or function is a member
6626 // of the innermost enclosing namespace.
6627 // - The name of the friend is not found by simple name lookup
6628 // until a matching declaration is provided in that namespace
6629 // scope (either before or after the class declaration granting
6630 // friendship).
6631 // - If a friend function is called, its name may be found by the
6632 // name lookup that considers functions from namespaces and
6633 // classes associated with the types of the function arguments.
6634 // - When looking for a prior declaration of a class or a function
6635 // declared as a friend, scopes outside the innermost enclosing
6636 // namespace scope are not considered.
6637
John McCallde3fd222010-10-12 23:13:28 +00006638 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006639 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6640 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006641 assert(Name);
6642
Douglas Gregor6c110f32010-12-16 01:14:37 +00006643 // Check for unexpanded parameter packs.
6644 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6645 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6646 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6647 return 0;
6648
John McCall07e91c02009-08-06 02:15:43 +00006649 // The context we found the declaration in, or in which we should
6650 // create the declaration.
6651 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006652 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006653 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006654 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006655
John McCallde3fd222010-10-12 23:13:28 +00006656 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006657
John McCallde3fd222010-10-12 23:13:28 +00006658 // There are four cases here.
6659 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006660 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006661 // there as appropriate.
6662 // Recover from invalid scope qualifiers as if they just weren't there.
6663 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006664 // C++0x [namespace.memdef]p3:
6665 // If the name in a friend declaration is neither qualified nor
6666 // a template-id and the declaration is a function or an
6667 // elaborated-type-specifier, the lookup to determine whether
6668 // the entity has been previously declared shall not consider
6669 // any scopes outside the innermost enclosing namespace.
6670 // C++0x [class.friend]p11:
6671 // If a friend declaration appears in a local class and the name
6672 // specified is an unqualified name, a prior declaration is
6673 // looked up without considering scopes that are outside the
6674 // innermost enclosing non-class scope. For a friend function
6675 // declaration, if there is no prior declaration, the program is
6676 // ill-formed.
6677 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006678 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006679
John McCallf7cfb222010-10-13 05:45:15 +00006680 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006681 DC = CurContext;
6682 while (true) {
6683 // Skip class contexts. If someone can cite chapter and verse
6684 // for this behavior, that would be nice --- it's what GCC and
6685 // EDG do, and it seems like a reasonable intent, but the spec
6686 // really only says that checks for unqualified existing
6687 // declarations should stop at the nearest enclosing namespace,
6688 // not that they should only consider the nearest enclosing
6689 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006690 while (DC->isRecord())
6691 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006692
John McCall1f82f242009-11-18 22:49:29 +00006693 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006694
6695 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006696 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006697 break;
John McCallf7cfb222010-10-13 05:45:15 +00006698
John McCallf4776592010-10-14 22:22:28 +00006699 if (isTemplateId) {
6700 if (isa<TranslationUnitDecl>(DC)) break;
6701 } else {
6702 if (DC->isFileContext()) break;
6703 }
John McCall07e91c02009-08-06 02:15:43 +00006704 DC = DC->getParent();
6705 }
6706
6707 // C++ [class.friend]p1: A friend of a class is a function or
6708 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006709 // C++0x changes this for both friend types and functions.
6710 // Most C++ 98 compilers do seem to give an error here, so
6711 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006712 if (!Previous.empty() && DC->Equals(CurContext)
6713 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006714 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006715
John McCallccbc0322010-10-13 06:22:15 +00006716 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006717
John McCallde3fd222010-10-12 23:13:28 +00006718 // - There's a non-dependent scope specifier, in which case we
6719 // compute it and do a previous lookup there for a function
6720 // or function template.
6721 } else if (!SS.getScopeRep()->isDependent()) {
6722 DC = computeDeclContext(SS);
6723 if (!DC) return 0;
6724
6725 if (RequireCompleteDeclContext(SS, DC)) return 0;
6726
6727 LookupQualifiedName(Previous, DC);
6728
6729 // Ignore things found implicitly in the wrong scope.
6730 // TODO: better diagnostics for this case. Suggesting the right
6731 // qualified scope would be nice...
6732 LookupResult::Filter F = Previous.makeFilter();
6733 while (F.hasNext()) {
6734 NamedDecl *D = F.next();
6735 if (!DC->InEnclosingNamespaceSetOf(
6736 D->getDeclContext()->getRedeclContext()))
6737 F.erase();
6738 }
6739 F.done();
6740
6741 if (Previous.empty()) {
6742 D.setInvalidType();
6743 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6744 return 0;
6745 }
6746
6747 // C++ [class.friend]p1: A friend of a class is a function or
6748 // class that is not a member of the class . . .
6749 if (DC->Equals(CurContext))
6750 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6751
6752 // - There's a scope specifier that does not match any template
6753 // parameter lists, in which case we use some arbitrary context,
6754 // create a method or method template, and wait for instantiation.
6755 // - There's a scope specifier that does match some template
6756 // parameter lists, which we don't handle right now.
6757 } else {
6758 DC = CurContext;
6759 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006760 }
6761
John McCallf7cfb222010-10-13 05:45:15 +00006762 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006763 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006764 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6765 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6766 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006767 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006768 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6769 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006770 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006771 }
John McCall07e91c02009-08-06 02:15:43 +00006772 }
6773
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006774 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006775 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006776 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006777 IsDefinition,
6778 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006779 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006780
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006781 assert(ND->getDeclContext() == DC);
6782 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006783
John McCall759e32b2009-08-31 22:39:49 +00006784 // Add the function declaration to the appropriate lookup tables,
6785 // adjusting the redeclarations list as necessary. We don't
6786 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006787 //
John McCall759e32b2009-08-31 22:39:49 +00006788 // Also update the scope-based lookup if the target context's
6789 // lookup context is in lexical scope.
6790 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006791 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006792 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006793 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006794 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006795 }
John McCallaa74a0c2009-08-28 07:59:38 +00006796
6797 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006798 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006799 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006800 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006801 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006802
John McCallde3fd222010-10-12 23:13:28 +00006803 if (ND->isInvalidDecl())
6804 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006805 else {
6806 FunctionDecl *FD;
6807 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6808 FD = FTD->getTemplatedDecl();
6809 else
6810 FD = cast<FunctionDecl>(ND);
6811
6812 // Mark templated-scope function declarations as unsupported.
6813 if (FD->getNumTemplateParameterLists())
6814 FrD->setUnsupportedFriend(true);
6815 }
John McCallde3fd222010-10-12 23:13:28 +00006816
John McCall48871652010-08-21 09:40:31 +00006817 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006818}
6819
John McCall48871652010-08-21 09:40:31 +00006820void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6821 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006822
Sebastian Redlf769df52009-03-24 22:27:57 +00006823 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6824 if (!Fn) {
6825 Diag(DelLoc, diag::err_deleted_non_function);
6826 return;
6827 }
6828 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6829 Diag(DelLoc, diag::err_deleted_decl_not_first);
6830 Diag(Prev->getLocation(), diag::note_previous_declaration);
6831 // If the declaration wasn't the first, we delete the function anyway for
6832 // recovery.
6833 }
6834 Fn->setDeleted();
6835}
Sebastian Redl4c018662009-04-27 21:33:24 +00006836
6837static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6838 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6839 ++CI) {
6840 Stmt *SubStmt = *CI;
6841 if (!SubStmt)
6842 continue;
6843 if (isa<ReturnStmt>(SubStmt))
6844 Self.Diag(SubStmt->getSourceRange().getBegin(),
6845 diag::err_return_in_constructor_handler);
6846 if (!isa<Expr>(SubStmt))
6847 SearchForReturnInStmt(Self, SubStmt);
6848 }
6849}
6850
6851void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6852 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6853 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6854 SearchForReturnInStmt(*this, Handler);
6855 }
6856}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006857
Mike Stump11289f42009-09-09 15:08:12 +00006858bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006859 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006860 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6861 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006862
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006863 if (Context.hasSameType(NewTy, OldTy) ||
6864 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006865 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006866
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006867 // Check if the return types are covariant
6868 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006869
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006870 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006871 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6872 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006873 NewClassTy = NewPT->getPointeeType();
6874 OldClassTy = OldPT->getPointeeType();
6875 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006876 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6877 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6878 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6879 NewClassTy = NewRT->getPointeeType();
6880 OldClassTy = OldRT->getPointeeType();
6881 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006882 }
6883 }
Mike Stump11289f42009-09-09 15:08:12 +00006884
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006885 // The return types aren't either both pointers or references to a class type.
6886 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006887 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006888 diag::err_different_return_type_for_overriding_virtual_function)
6889 << New->getDeclName() << NewTy << OldTy;
6890 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006891
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006892 return true;
6893 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006894
Anders Carlssone60365b2009-12-31 18:34:24 +00006895 // C++ [class.virtual]p6:
6896 // If the return type of D::f differs from the return type of B::f, the
6897 // class type in the return type of D::f shall be complete at the point of
6898 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006899 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6900 if (!RT->isBeingDefined() &&
6901 RequireCompleteType(New->getLocation(), NewClassTy,
6902 PDiag(diag::err_covariant_return_incomplete)
6903 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006904 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006905 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006906
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006907 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006908 // Check if the new class derives from the old class.
6909 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6910 Diag(New->getLocation(),
6911 diag::err_covariant_return_not_derived)
6912 << New->getDeclName() << NewTy << OldTy;
6913 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6914 return true;
6915 }
Mike Stump11289f42009-09-09 15:08:12 +00006916
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006917 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006918 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006919 diag::err_covariant_return_inaccessible_base,
6920 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6921 // FIXME: Should this point to the return type?
6922 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006923 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6924 return true;
6925 }
6926 }
Mike Stump11289f42009-09-09 15:08:12 +00006927
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006928 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006929 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006930 Diag(New->getLocation(),
6931 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006932 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006933 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6934 return true;
6935 };
Mike Stump11289f42009-09-09 15:08:12 +00006936
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006937
6938 // The new class type must have the same or less qualifiers as the old type.
6939 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6940 Diag(New->getLocation(),
6941 diag::err_covariant_return_type_class_type_more_qualified)
6942 << New->getDeclName() << NewTy << OldTy;
6943 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6944 return true;
6945 };
Mike Stump11289f42009-09-09 15:08:12 +00006946
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006947 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006948}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006949
Douglas Gregor21920e372009-12-01 17:24:26 +00006950/// \brief Mark the given method pure.
6951///
6952/// \param Method the method to be marked pure.
6953///
6954/// \param InitRange the source range that covers the "0" initializer.
6955bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6956 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6957 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006958 return false;
6959 }
6960
6961 if (!Method->isInvalidDecl())
6962 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6963 << Method->getDeclName() << InitRange;
6964 return true;
6965}
6966
John McCall1f4ee7b2009-12-19 09:28:58 +00006967/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6968/// an initializer for the out-of-line declaration 'Dcl'. The scope
6969/// is a fresh scope pushed for just this purpose.
6970///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006971/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6972/// static data member of class X, names should be looked up in the scope of
6973/// class X.
John McCall48871652010-08-21 09:40:31 +00006974void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006975 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006976 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006977
John McCall1f4ee7b2009-12-19 09:28:58 +00006978 // We should only get called for declarations with scope specifiers, like:
6979 // int foo::bar;
6980 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006981 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006982}
6983
6984/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006985/// initializer for the out-of-line declaration 'D'.
6986void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006987 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006988 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006989
John McCall1f4ee7b2009-12-19 09:28:58 +00006990 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006991 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006992}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006993
6994/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6995/// C++ if/switch/while/for statement.
6996/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006997DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006998 // C++ 6.4p2:
6999 // The declarator shall not specify a function or an array.
7000 // The type-specifier-seq shall not contain typedef and shall not declare a
7001 // new class or enumeration.
7002 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7003 "Parser allowed 'typedef' as storage class of condition decl.");
7004
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007005 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007006 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7007 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007008
7009 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7010 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7011 // would be created and CXXConditionDeclExpr wants a VarDecl.
7012 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7013 << D.getSourceRange();
7014 return DeclResult();
7015 } else if (OwnedTag && OwnedTag->isDefinition()) {
7016 // The type-specifier-seq shall not declare a new class or enumeration.
7017 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7018 }
7019
John McCall48871652010-08-21 09:40:31 +00007020 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007021 if (!Dcl)
7022 return DeclResult();
7023
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007024 return Dcl;
7025}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007026
Douglas Gregor88d292c2010-05-13 16:44:06 +00007027void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7028 bool DefinitionRequired) {
7029 // Ignore any vtable uses in unevaluated operands or for classes that do
7030 // not have a vtable.
7031 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7032 CurContext->isDependentContext() ||
7033 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007034 return;
7035
Douglas Gregor88d292c2010-05-13 16:44:06 +00007036 // Try to insert this class into the map.
7037 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7038 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7039 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7040 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007041 // If we already had an entry, check to see if we are promoting this vtable
7042 // to required a definition. If so, we need to reappend to the VTableUses
7043 // list, since we may have already processed the first entry.
7044 if (DefinitionRequired && !Pos.first->second) {
7045 Pos.first->second = true;
7046 } else {
7047 // Otherwise, we can early exit.
7048 return;
7049 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007050 }
7051
7052 // Local classes need to have their virtual members marked
7053 // immediately. For all other classes, we mark their virtual members
7054 // at the end of the translation unit.
7055 if (Class->isLocalClass())
7056 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007057 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007058 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007059}
7060
Douglas Gregor88d292c2010-05-13 16:44:06 +00007061bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007062 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007063 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007064
Douglas Gregor88d292c2010-05-13 16:44:06 +00007065 // Note: The VTableUses vector could grow as a result of marking
7066 // the members of a class as "used", so we check the size each
7067 // time through the loop and prefer indices (with are stable) to
7068 // iterators (which are not).
7069 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007070 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007071 if (!Class)
7072 continue;
7073
7074 SourceLocation Loc = VTableUses[I].second;
7075
7076 // If this class has a key function, but that key function is
7077 // defined in another translation unit, we don't need to emit the
7078 // vtable even though we're using it.
7079 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007080 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007081 switch (KeyFunction->getTemplateSpecializationKind()) {
7082 case TSK_Undeclared:
7083 case TSK_ExplicitSpecialization:
7084 case TSK_ExplicitInstantiationDeclaration:
7085 // The key function is in another translation unit.
7086 continue;
7087
7088 case TSK_ExplicitInstantiationDefinition:
7089 case TSK_ImplicitInstantiation:
7090 // We will be instantiating the key function.
7091 break;
7092 }
7093 } else if (!KeyFunction) {
7094 // If we have a class with no key function that is the subject
7095 // of an explicit instantiation declaration, suppress the
7096 // vtable; it will live with the explicit instantiation
7097 // definition.
7098 bool IsExplicitInstantiationDeclaration
7099 = Class->getTemplateSpecializationKind()
7100 == TSK_ExplicitInstantiationDeclaration;
7101 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7102 REnd = Class->redecls_end();
7103 R != REnd; ++R) {
7104 TemplateSpecializationKind TSK
7105 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7106 if (TSK == TSK_ExplicitInstantiationDeclaration)
7107 IsExplicitInstantiationDeclaration = true;
7108 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7109 IsExplicitInstantiationDeclaration = false;
7110 break;
7111 }
7112 }
7113
7114 if (IsExplicitInstantiationDeclaration)
7115 continue;
7116 }
7117
7118 // Mark all of the virtual members of this class as referenced, so
7119 // that we can build a vtable. Then, tell the AST consumer that a
7120 // vtable for this class is required.
7121 MarkVirtualMembersReferenced(Loc, Class);
7122 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7123 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7124
7125 // Optionally warn if we're emitting a weak vtable.
7126 if (Class->getLinkage() == ExternalLinkage &&
7127 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007128 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007129 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7130 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007131 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007132 VTableUses.clear();
7133
Anders Carlsson82fccd02009-12-07 08:24:59 +00007134 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007135}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007136
Rafael Espindola5b334082010-03-26 00:36:59 +00007137void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7138 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007139 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7140 e = RD->method_end(); i != e; ++i) {
7141 CXXMethodDecl *MD = *i;
7142
7143 // C++ [basic.def.odr]p2:
7144 // [...] A virtual member function is used if it is not pure. [...]
7145 if (MD->isVirtual() && !MD->isPure())
7146 MarkDeclarationReferenced(Loc, MD);
7147 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007148
7149 // Only classes that have virtual bases need a VTT.
7150 if (RD->getNumVBases() == 0)
7151 return;
7152
7153 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7154 e = RD->bases_end(); i != e; ++i) {
7155 const CXXRecordDecl *Base =
7156 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007157 if (Base->getNumVBases() == 0)
7158 continue;
7159 MarkVirtualMembersReferenced(Loc, Base);
7160 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007161}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007162
7163/// SetIvarInitializers - This routine builds initialization ASTs for the
7164/// Objective-C implementation whose ivars need be initialized.
7165void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7166 if (!getLangOptions().CPlusPlus)
7167 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007168 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007169 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7170 CollectIvarsToConstructOrDestruct(OID, ivars);
7171 if (ivars.empty())
7172 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007173 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007174 for (unsigned i = 0; i < ivars.size(); i++) {
7175 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007176 if (Field->isInvalidDecl())
7177 continue;
7178
Alexis Hunt1d792652011-01-08 20:30:50 +00007179 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007180 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7181 InitializationKind InitKind =
7182 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7183
7184 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007185 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007186 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007187 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007188 // Note, MemberInit could actually come back empty if no initialization
7189 // is required (e.g., because it would call a trivial default constructor)
7190 if (!MemberInit.get() || MemberInit.isInvalid())
7191 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007192
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007193 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007194 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7195 SourceLocation(),
7196 MemberInit.takeAs<Expr>(),
7197 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007198 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007199
7200 // Be sure that the destructor is accessible and is marked as referenced.
7201 if (const RecordType *RecordTy
7202 = Context.getBaseElementType(Field->getType())
7203 ->getAs<RecordType>()) {
7204 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007205 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007206 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7207 CheckDestructorAccess(Field->getLocation(), Destructor,
7208 PDiag(diag::err_access_dtor_ivar)
7209 << Context.getBaseElementType(Field->getType()));
7210 }
7211 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007212 }
7213 ObjCImplementation->setIvarInitializers(Context,
7214 AllToInit.data(), AllToInit.size());
7215 }
7216}