blob: 9981b1f6c8986983d80b8d2c09a86b1e44d78171 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
296
297 // int f(int);
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000300 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000301 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000302 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000303
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl *Older = Old->getPreviousDeclaration();
307 Older; Older = Older->getPreviousDeclaration()) {
308 if (!Older->getParamDecl(p)->hasDefaultArg())
309 break;
310
311 OldParam = Older->getParamDecl(p);
312 }
313
314 Diag(OldParam->getLocation(), diag::note_previous_definition)
315 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000316 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000317 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000320 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000321 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000322 if (OldParam->hasUninstantiatedDefaultArg())
323 NewParam->setUninstantiatedDefaultArg(
324 OldParam->getUninstantiatedDefaultArg());
325 else
John McCalle61b02b2010-05-04 01:53:42 +0000326 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000327 } else if (NewParam->hasDefaultArg()) {
328 if (New->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam->getLocation(),
331 diag::err_param_default_argument_template_redecl)
332 << NewParam->getDefaultArgRange();
333 Diag(Old->getLocation(), diag::note_template_prev_declaration)
334 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000335 } else if (New->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation &&
337 New->getTemplateSpecializationKind() != TSK_Undeclared) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
346 // instantiated.
347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
349 << New->getDeclName()
350 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000351 } else if (New->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
356 //
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
360 // dependent type.
361 int WhichKind = 2;
362 if (CXXRecordDecl *Record
363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
364 if (Record->getDescribedClassTemplate())
365 WhichKind = 0;
366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
367 WhichKind = 1;
368 else
369 WhichKind = 2;
370 }
371
372 Diag(NewParam->getLocation(),
373 diag::err_param_default_argument_member_template_redecl)
374 << WhichKind
375 << NewParam->getDefaultArgRange();
376 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000377 }
378 }
379
Douglas Gregorf40863c2010-02-12 07:32:17 +0000380 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000382
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000383 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000384}
385
386/// CheckCXXDefaultArguments - Verify that the default arguments for a
387/// function declaration are well-formed according to C++
388/// [dcl.fct.default].
389void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
390 unsigned NumParams = FD->getNumParams();
391 unsigned p;
392
393 // Find first parameter with a default argument
394 for (p = 0; p < NumParams; ++p) {
395 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000396 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 break;
398 }
399
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000407 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000409 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000410 if (Param->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000414 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000415 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000416 else
Mike Stump11289f42009-09-09 15:08:12 +0000417 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000418 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner199abbc2008-04-08 05:04:30 +0000420 LastMissingDefaultArg = p;
421 }
422 }
423
424 if (LastMissingDefaultArg > 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p = 0; p <= LastMissingDefaultArg; ++p) {
430 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000431 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 Param->setDefaultArg(0);
433 }
434 }
435 }
436}
Douglas Gregor556877c2008-04-13 21:30:24 +0000437
Douglas Gregor61956c42008-10-31 09:07:45 +0000438/// isCurrentClassName - Determine whether the identifier II is the
439/// name of the class type currently being defined. In the case of
440/// nested classes, this will only return true if II is the name of
441/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000442bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
443 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000444 assert(getLangOptions().CPlusPlus && "No class names in C!");
445
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000446 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000447 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000448 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
450 } else
451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
452
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000453 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000454 return &II == CurDecl->getIdentifier();
455 else
456 return false;
457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000460///
461/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462/// and returns NULL otherwise.
463CXXBaseSpecifier *
464Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
465 SourceRange SpecifierRange,
466 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000467 TypeSourceInfo *TInfo,
468 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000469 QualType BaseType = TInfo->getType();
470
Douglas Gregor463421d2009-03-03 04:44:36 +0000471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class->isUnion()) {
474 Diag(Class->getLocation(), diag::err_base_clause_on_union)
475 << SpecifierRange;
476 return 0;
477 }
478
Douglas Gregor752a5952011-01-03 22:36:02 +0000479 if (EllipsisLoc.isValid() &&
480 !TInfo->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
482 << TInfo->getTypeLoc().getSourceRange();
483 EllipsisLoc = SourceLocation();
484 }
485
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000489 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000490
491 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492
493 // Base specifiers must be record types.
494 if (!BaseType->isRecordType()) {
495 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
496 return 0;
497 }
498
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType->isUnionType()) {
502 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
503 return 0;
504 }
505
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
508 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000510 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000511 << SpecifierRange)) {
512 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000513 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000514 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000515
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000517 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000518 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000519 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000520 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000521 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
522 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000523
Alexis Hunt96d5c762009-11-21 08:43:09 +0000524 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
525 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
526 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000527 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
528 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000529 return 0;
530 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000531
John McCall3696dcb2010-08-17 07:23:57 +0000532 if (BaseDecl->isInvalidDecl())
533 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534
535 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000537 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000538 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539}
540
Douglas Gregor556877c2008-04-13 21:30:24 +0000541/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
542/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000543/// example:
544/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000545/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000546BaseResult
John McCall48871652010-08-21 09:40:31 +0000547Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000548 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000549 ParsedType basetype, SourceLocation BaseLoc,
550 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000551 if (!classdecl)
552 return true;
553
Douglas Gregorc40290e2009-03-09 23:48:35 +0000554 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000555 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000556 if (!Class)
557 return true;
558
Nick Lewycky19b9f952010-07-26 16:56:01 +0000559 TypeSourceInfo *TInfo = 0;
560 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000561
Douglas Gregor752a5952011-01-03 22:36:02 +0000562 if (EllipsisLoc.isInvalid() &&
563 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000564 UPPC_BaseType))
565 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000566
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000568 Virtual, Access, TInfo,
569 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000573}
Douglas Gregor556877c2008-04-13 21:30:24 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575/// \brief Performs the actual work of attaching the given base class
576/// specifiers to a C++ class.
577bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
578 unsigned NumBases) {
579 if (NumBases == 0)
580 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000581
582 // Used to keep track of which base types we have already seen, so
583 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000584 // that the key is always the unqualified canonical type of the base
585 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
587
588 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000589 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000594 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000595 if (!Class->hasObjectMember()) {
596 if (const RecordType *FDTTy =
597 NewBaseType.getTypePtr()->getAs<RecordType>())
598 if (FDTTy->getDecl()->hasObjectMember())
599 Class->setHasObjectMember(true);
600 }
601
Douglas Gregor29a92472008-10-22 17:49:05 +0000602 if (KnownBaseTypes[NewBaseType]) {
603 // C++ [class.mi]p3:
604 // A class shall not be specified as a direct base class of a
605 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000607 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000610
611 // Delete the duplicate base class specifier; we're going to
612 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000613 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000614
615 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 } else {
617 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 KnownBaseTypes[NewBaseType] = Bases[idx];
619 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 }
621 }
622
623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000624 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000625
626 // Delete the remaining (good) base class specifiers, since their
627 // data has been copied into the CXXRecordDecl.
628 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000629 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000630
631 return Invalid;
632}
633
634/// ActOnBaseSpecifiers - Attach the given base specifiers to the
635/// class, after checking whether there are any duplicate base
636/// classes.
John McCall48871652010-08-21 09:40:31 +0000637void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 unsigned NumBases) {
639 if (!ClassDecl || !Bases || !NumBases)
640 return;
641
642 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000643 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000645}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000646
John McCalle78aac42010-03-10 03:28:59 +0000647static CXXRecordDecl *GetClassForType(QualType T) {
648 if (const RecordType *RT = T->getAs<RecordType>())
649 return cast<CXXRecordDecl>(RT->getDecl());
650 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
651 return ICT->getDecl();
652 else
653 return 0;
654}
655
Douglas Gregor36d1b142009-10-06 17:59:45 +0000656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
John McCalle78aac42010-03-10 03:28:59 +0000661
662 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
663 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000664 return false;
665
John McCalle78aac42010-03-10 03:28:59 +0000666 CXXRecordDecl *BaseRD = GetClassForType(Base);
667 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000668 return false;
669
John McCall67da35c2010-02-04 22:26:26 +0000670 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
671 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000672}
673
674/// \brief Determine whether the type \p Derived is a C++ class that is
675/// derived from the type \p Base.
676bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
677 if (!getLangOptions().CPlusPlus)
678 return false;
679
John McCalle78aac42010-03-10 03:28:59 +0000680 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
681 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000682 return false;
683
John McCalle78aac42010-03-10 03:28:59 +0000684 CXXRecordDecl *BaseRD = GetClassForType(Base);
685 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686 return false;
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688 return DerivedRD->isDerivedFrom(BaseRD, Paths);
689}
690
Anders Carlssona70cff62010-04-24 19:06:50 +0000691void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000693 assert(BasePathArray.empty() && "Base path array must be empty!");
694 assert(Paths.isRecordingPaths() && "Must record paths!");
695
696 const CXXBasePath &Path = Paths.front();
697
698 // We first go backward and check if we have a virtual base.
699 // FIXME: It would be better if CXXBasePath had the base specifier for
700 // the nearest virtual base.
701 unsigned Start = 0;
702 for (unsigned I = Path.size(); I != 0; --I) {
703 if (Path[I - 1].Base->isVirtual()) {
704 Start = I - 1;
705 break;
706 }
707 }
708
709 // Now add all bases.
710 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000711 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000712}
713
Douglas Gregor88d292c2010-05-13 16:44:06 +0000714/// \brief Determine whether the given base path includes a virtual
715/// base class.
John McCallcf142162010-08-07 06:22:56 +0000716bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
717 for (CXXCastPath::const_iterator B = BasePath.begin(),
718 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000719 B != BEnd; ++B)
720 if ((*B)->isVirtual())
721 return true;
722
723 return false;
724}
725
Douglas Gregor36d1b142009-10-06 17:59:45 +0000726/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
727/// conversion (where Derived and Base are class types) is
728/// well-formed, meaning that the conversion is unambiguous (and
729/// that all of the base classes are accessible). Returns true
730/// and emits a diagnostic if the code is ill-formed, returns false
731/// otherwise. Loc is the location where this routine should point to
732/// if there is an error, and Range is the source range to highlight
733/// if there is an error.
734bool
735Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000736 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000737 unsigned AmbigiousBaseConvID,
738 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000739 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000740 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 // First, determine whether the path from Derived to Base is
742 // ambiguous. This is slightly more expensive than checking whether
743 // the Derived to Base conversion exists, because here we need to
744 // explore multiple paths to determine if there is an ambiguity.
745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
746 /*DetectVirtual=*/false);
747 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
748 assert(DerivationOkay &&
749 "Can only be used with a derived-to-base conversion");
750 (void)DerivationOkay;
751
752 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000753 if (InaccessibleBaseID) {
754 // Check that the base class can be accessed.
755 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
756 InaccessibleBaseID)) {
757 case AR_inaccessible:
758 return true;
759 case AR_accessible:
760 case AR_dependent:
761 case AR_delayed:
762 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000763 }
John McCall5b0829a2010-02-10 09:31:12 +0000764 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000765
766 // Build a base path if necessary.
767 if (BasePath)
768 BuildBasePathArray(Paths, *BasePath);
769 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000770 }
771
772 // We know that the derived-to-base conversion is ambiguous, and
773 // we're going to produce a diagnostic. Perform the derived-to-base
774 // search just one more time to compute all of the possible paths so
775 // that we can print them out. This is more expensive than any of
776 // the previous derived-to-base checks we've done, but at this point
777 // performance isn't as much of an issue.
778 Paths.clear();
779 Paths.setRecordingPaths(true);
780 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(StillOkay && "Can only be used with a derived-to-base conversion");
782 (void)StillOkay;
783
784 // Build up a textual representation of the ambiguous paths, e.g.,
785 // D -> B -> A, that will be used to illustrate the ambiguous
786 // conversions in the diagnostic. We only print one of the paths
787 // to each base class subobject.
788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
789
790 Diag(Loc, AmbigiousBaseConvID)
791 << Derived << Base << PathDisplayStr << Range << Name;
792 return true;
793}
794
795bool
796Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000797 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000798 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000799 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000801 IgnoreAccess ? 0
802 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000804 Loc, Range, DeclarationName(),
805 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806}
807
808
809/// @brief Builds a string representing ambiguous paths from a
810/// specific derived class to different subobjects of the same base
811/// class.
812///
813/// This function builds a string that can be used in error messages
814/// to show the different paths that one can take through the
815/// inheritance hierarchy to go from the derived class to different
816/// subobjects of a base class. The result looks something like this:
817/// @code
818/// struct D -> struct B -> struct A
819/// struct D -> struct C -> struct A
820/// @endcode
821std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
822 std::string PathDisplayStr;
823 std::set<unsigned> DisplayedPaths;
824 for (CXXBasePaths::paths_iterator Path = Paths.begin();
825 Path != Paths.end(); ++Path) {
826 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
827 // We haven't displayed a path to this particular base
828 // class subobject yet.
829 PathDisplayStr += "\n ";
830 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
831 for (CXXBasePath::const_iterator Element = Path->begin();
832 Element != Path->end(); ++Element)
833 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
834 }
835 }
836
837 return PathDisplayStr;
838}
839
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000840//===----------------------------------------------------------------------===//
841// C++ class member Handling
842//===----------------------------------------------------------------------===//
843
Abramo Bagnarad7340582010-06-05 05:09:32 +0000844/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000845Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
846 SourceLocation ASLoc,
847 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000848 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000849 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000850 ASLoc, ColonLoc);
851 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000852 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853}
854
Anders Carlssonfd835532011-01-20 05:57:14 +0000855/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000856void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000857 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
858 if (!MD || !MD->isVirtual())
859 return;
860
861 // C++0x [class.virtual]p3:
862 // If a virtual function is marked with the virt-specifier override and does
863 // not override a member function of a base class,
864 // the program is ill-formed.
865 bool HasOverriddenMethods =
866 MD->begin_overridden_methods() != MD->end_overridden_methods();
867 if (MD->isMarkedOverride() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000868 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000869 diag::err_function_marked_override_not_overriding)
870 << MD->getDeclName();
871 return;
872 }
873}
874
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000875/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
876/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
877/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000878/// any.
John McCall48871652010-08-21 09:40:31 +0000879Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000880Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000881 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000882 ExprTy *BW, const VirtSpecifiers &VS,
883 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000884 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000886 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
887 DeclarationName Name = NameInfo.getName();
888 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000889
890 // For anonymous bitfields, the location should point to the type.
891 if (Loc.isInvalid())
892 Loc = D.getSourceRange().getBegin();
893
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 Expr *BitWidth = static_cast<Expr*>(BW);
895 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000896
John McCallb1cd7da2010-06-04 08:34:12 +0000897 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000898 assert(!DS.isFriendSpecified());
899
John McCallb1cd7da2010-06-04 08:34:12 +0000900 bool isFunc = false;
901 if (D.isFunctionDeclarator())
902 isFunc = true;
903 else if (D.getNumTypeObjects() == 0 &&
904 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000905 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000906 isFunc = TDType->isFunctionType();
907 }
908
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000909 // C++ 9.2p6: A member shall not be declared to have automatic storage
910 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000911 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
912 // data members and cannot be applied to names declared const or static,
913 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000914 switch (DS.getStorageClassSpec()) {
915 case DeclSpec::SCS_unspecified:
916 case DeclSpec::SCS_typedef:
917 case DeclSpec::SCS_static:
918 // FALL THROUGH.
919 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000920 case DeclSpec::SCS_mutable:
921 if (isFunc) {
922 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000923 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000924 else
Chris Lattner3b054132008-11-19 05:08:23 +0000925 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000926
Sebastian Redl8071edb2008-11-17 23:24:37 +0000927 // FIXME: It would be nicer if the keyword was ignored only for this
928 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000929 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000930 }
931 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000932 default:
933 if (DS.getStorageClassSpecLoc().isValid())
934 Diag(DS.getStorageClassSpecLoc(),
935 diag::err_storageclass_invalid_for_member);
936 else
937 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
938 D.getMutableDeclSpec().ClearStorageClassSpecs();
939 }
940
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000941 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
942 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000943 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000944
945 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000946 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000947 CXXScopeSpec &SS = D.getCXXScopeSpec();
948
949
950 if (SS.isSet() && !SS.isInvalid()) {
951 // The user provided a superfluous scope specifier inside a class
952 // definition:
953 //
954 // class X {
955 // int X::member;
956 // };
957 DeclContext *DC = 0;
958 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
959 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
960 << Name << FixItHint::CreateRemoval(SS.getRange());
961 else
962 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
963 << Name << SS.getRange();
964
965 SS.clear();
966 }
967
Douglas Gregor3447e762009-08-20 22:52:58 +0000968 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +0000969 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000970 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
971 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000972 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000973 } else {
John McCall48871652010-08-21 09:40:31 +0000974 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000975 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000976 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000977 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000978
979 // Non-instance-fields can't have a bitfield.
980 if (BitWidth) {
981 if (Member->isInvalidDecl()) {
982 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000983 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000984 // C++ 9.6p3: A bit-field shall not be a static member.
985 // "static member 'A' cannot be a bit-field"
986 Diag(Loc, diag::err_static_not_bitfield)
987 << Name << BitWidth->getSourceRange();
988 } else if (isa<TypedefDecl>(Member)) {
989 // "typedef member 'x' cannot be a bit-field"
990 Diag(Loc, diag::err_typedef_not_bitfield)
991 << Name << BitWidth->getSourceRange();
992 } else {
993 // A function typedef ("typedef int f(); f a;").
994 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
995 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000996 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000997 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattnerd26760a2009-03-05 23:01:03 +00001000 BitWidth = 0;
1001 Member->setInvalidDecl();
1002 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001003
1004 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001005
Douglas Gregor3447e762009-08-20 22:52:58 +00001006 // If we have declared a member function template, set the access of the
1007 // templated declaration as well.
1008 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1009 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001010 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001011
Anders Carlsson13a69102011-01-20 04:34:22 +00001012 if (VS.isOverrideSpecified()) {
1013 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1014 if (!MD || !MD->isVirtual()) {
1015 Diag(Member->getLocStart(),
1016 diag::override_keyword_only_allowed_on_virtual_member_functions)
1017 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001018 } else
1019 MD->setIsMarkedOverride(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001020 }
1021 if (VS.isFinalSpecified()) {
1022 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1023 if (!MD || !MD->isVirtual()) {
1024 Diag(Member->getLocStart(),
1025 diag::override_keyword_only_allowed_on_virtual_member_functions)
1026 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001027 } else
1028 MD->setIsMarkedFinal(true);
Anders Carlsson13a69102011-01-20 04:34:22 +00001029 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001030
Anders Carlssonc87f8612011-01-20 06:29:02 +00001031 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001032
Douglas Gregor92751d42008-11-17 22:58:34 +00001033 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001034
Douglas Gregor0c880302009-03-11 23:00:04 +00001035 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001036 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001037 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001038 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001039
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001040 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001041 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001042 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001043 }
John McCall48871652010-08-21 09:40:31 +00001044 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001045}
1046
Douglas Gregor15e77a22009-12-31 09:10:24 +00001047/// \brief Find the direct and/or virtual base specifiers that
1048/// correspond to the given base type, for use in base initialization
1049/// within a constructor.
1050static bool FindBaseInitializer(Sema &SemaRef,
1051 CXXRecordDecl *ClassDecl,
1052 QualType BaseType,
1053 const CXXBaseSpecifier *&DirectBaseSpec,
1054 const CXXBaseSpecifier *&VirtualBaseSpec) {
1055 // First, check for a direct base class.
1056 DirectBaseSpec = 0;
1057 for (CXXRecordDecl::base_class_const_iterator Base
1058 = ClassDecl->bases_begin();
1059 Base != ClassDecl->bases_end(); ++Base) {
1060 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1061 // We found a direct base of this type. That's what we're
1062 // initializing.
1063 DirectBaseSpec = &*Base;
1064 break;
1065 }
1066 }
1067
1068 // Check for a virtual base class.
1069 // FIXME: We might be able to short-circuit this if we know in advance that
1070 // there are no virtual bases.
1071 VirtualBaseSpec = 0;
1072 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1073 // We haven't found a base yet; search the class hierarchy for a
1074 // virtual base class.
1075 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1076 /*DetectVirtual=*/false);
1077 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1078 BaseType, Paths)) {
1079 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1080 Path != Paths.end(); ++Path) {
1081 if (Path->back().Base->isVirtual()) {
1082 VirtualBaseSpec = Path->back().Base;
1083 break;
1084 }
1085 }
1086 }
1087 }
1088
1089 return DirectBaseSpec || VirtualBaseSpec;
1090}
1091
Douglas Gregore8381c02008-11-05 04:29:56 +00001092/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001093MemInitResult
John McCall48871652010-08-21 09:40:31 +00001094Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001095 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001096 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001097 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001098 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001099 SourceLocation IdLoc,
1100 SourceLocation LParenLoc,
1101 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001102 SourceLocation RParenLoc,
1103 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001104 if (!ConstructorD)
1105 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001107 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001108
1109 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001110 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001111 if (!Constructor) {
1112 // The user wrote a constructor initializer on a function that is
1113 // not a C++ constructor. Ignore the error for now, because we may
1114 // have more member initializers coming; we'll diagnose it just
1115 // once in ActOnMemInitializers.
1116 return true;
1117 }
1118
1119 CXXRecordDecl *ClassDecl = Constructor->getParent();
1120
1121 // C++ [class.base.init]p2:
1122 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001123 // constructor's class and, if not found in that scope, are looked
1124 // up in the scope containing the constructor's definition.
1125 // [Note: if the constructor's class contains a member with the
1126 // same name as a direct or virtual base class of the class, a
1127 // mem-initializer-id naming the member or base class and composed
1128 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001129 // mem-initializer-id for the hidden base class may be specified
1130 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001131 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001132 // Look for a member, first.
1133 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001134 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001135 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001136 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001137 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001138
Douglas Gregor44e7df62011-01-04 00:32:56 +00001139 if (Member) {
1140 if (EllipsisLoc.isValid())
1141 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1142 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1143
Francois Pichetd583da02010-12-04 09:14:42 +00001144 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001145 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001146 }
1147
Francois Pichetd583da02010-12-04 09:14:42 +00001148 // Handle anonymous union case.
1149 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001150 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1151 if (EllipsisLoc.isValid())
1152 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1153 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1154
Francois Pichetd583da02010-12-04 09:14:42 +00001155 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1156 NumArgs, IdLoc,
1157 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001158 }
Francois Pichetd583da02010-12-04 09:14:42 +00001159 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001160 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001161 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001162 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001163 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001164
1165 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001166 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001167 } else {
1168 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1169 LookupParsedName(R, S, &SS);
1170
1171 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1172 if (!TyD) {
1173 if (R.isAmbiguous()) return true;
1174
John McCallda6841b2010-04-09 19:01:14 +00001175 // We don't want access-control diagnostics here.
1176 R.suppressDiagnostics();
1177
Douglas Gregora3b624a2010-01-19 06:46:48 +00001178 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1179 bool NotUnknownSpecialization = false;
1180 DeclContext *DC = computeDeclContext(SS, false);
1181 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1182 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1183
1184 if (!NotUnknownSpecialization) {
1185 // When the scope specifier can refer to a member of an unknown
1186 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001187 BaseType = CheckTypenameType(ETK_None,
1188 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001189 *MemberOrBase, SourceLocation(),
1190 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001191 if (BaseType.isNull())
1192 return true;
1193
Douglas Gregora3b624a2010-01-19 06:46:48 +00001194 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001195 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001196 }
1197 }
1198
Douglas Gregor15e77a22009-12-31 09:10:24 +00001199 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001200 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001201 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1202 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001203 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001204 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001205 // We have found a non-static data member with a similar
1206 // name to what was typed; complain and initialize that
1207 // member.
1208 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1209 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001210 << FixItHint::CreateReplacement(R.getNameLoc(),
1211 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001212 Diag(Member->getLocation(), diag::note_previous_decl)
1213 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001214
1215 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1216 LParenLoc, RParenLoc);
1217 }
1218 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1219 const CXXBaseSpecifier *DirectBaseSpec;
1220 const CXXBaseSpecifier *VirtualBaseSpec;
1221 if (FindBaseInitializer(*this, ClassDecl,
1222 Context.getTypeDeclType(Type),
1223 DirectBaseSpec, VirtualBaseSpec)) {
1224 // We have found a direct or virtual base class with a
1225 // similar name to what was typed; complain and initialize
1226 // that base class.
1227 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1228 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001229 << FixItHint::CreateReplacement(R.getNameLoc(),
1230 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001231
1232 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1233 : VirtualBaseSpec;
1234 Diag(BaseSpec->getSourceRange().getBegin(),
1235 diag::note_base_class_specified_here)
1236 << BaseSpec->getType()
1237 << BaseSpec->getSourceRange();
1238
Douglas Gregor15e77a22009-12-31 09:10:24 +00001239 TyD = Type;
1240 }
1241 }
1242 }
1243
Douglas Gregora3b624a2010-01-19 06:46:48 +00001244 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001245 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1246 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1247 return true;
1248 }
John McCallb5a0d312009-12-21 10:41:20 +00001249 }
1250
Douglas Gregora3b624a2010-01-19 06:46:48 +00001251 if (BaseType.isNull()) {
1252 BaseType = Context.getTypeDeclType(TyD);
1253 if (SS.isSet()) {
1254 NestedNameSpecifier *Qualifier =
1255 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001256
Douglas Gregora3b624a2010-01-19 06:46:48 +00001257 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001258 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001259 }
John McCallb5a0d312009-12-21 10:41:20 +00001260 }
1261 }
Mike Stump11289f42009-09-09 15:08:12 +00001262
John McCallbcd03502009-12-07 02:54:59 +00001263 if (!TInfo)
1264 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001265
John McCallbcd03502009-12-07 02:54:59 +00001266 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001267 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001268}
1269
John McCalle22a04a2009-11-04 23:02:40 +00001270/// Checks an initializer expression for use of uninitialized fields, such as
1271/// containing the field that is being initialized. Returns true if there is an
1272/// uninitialized field was used an updates the SourceLocation parameter; false
1273/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001274static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001275 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001276 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001277 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1278
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001279 if (isa<CallExpr>(S)) {
1280 // Do not descend into function calls or constructors, as the use
1281 // of an uninitialized field may be valid. One would have to inspect
1282 // the contents of the function/ctor to determine if it is safe or not.
1283 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1284 // may be safe, depending on what the function/ctor does.
1285 return false;
1286 }
1287 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1288 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001289
1290 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1291 // The member expression points to a static data member.
1292 assert(VD->isStaticDataMember() &&
1293 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001294 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001295 return false;
1296 }
1297
1298 if (isa<EnumConstantDecl>(RhsField)) {
1299 // The member expression points to an enum.
1300 return false;
1301 }
1302
John McCalle22a04a2009-11-04 23:02:40 +00001303 if (RhsField == LhsField) {
1304 // Initializing a field with itself. Throw a warning.
1305 // But wait; there are exceptions!
1306 // Exception #1: The field may not belong to this record.
1307 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001308 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001309 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1310 // Even though the field matches, it does not belong to this record.
1311 return false;
1312 }
1313 // None of the exceptions triggered; return true to indicate an
1314 // uninitialized field was used.
1315 *L = ME->getMemberLoc();
1316 return true;
1317 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001318 } else if (isa<SizeOfAlignOfExpr>(S)) {
1319 // sizeof/alignof doesn't reference contents, do not warn.
1320 return false;
1321 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1322 // address-of doesn't reference contents (the pointer may be dereferenced
1323 // in the same expression but it would be rare; and weird).
1324 if (UOE->getOpcode() == UO_AddrOf)
1325 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001326 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001327 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1328 it != e; ++it) {
1329 if (!*it) {
1330 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001331 continue;
1332 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001333 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1334 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001335 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001336 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001337}
1338
John McCallfaf5fb42010-08-26 23:41:50 +00001339MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001340Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001341 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001342 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001343 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001344 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1345 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1346 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001347 "Member must be a FieldDecl or IndirectFieldDecl");
1348
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001349 if (Member->isInvalidDecl())
1350 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001351
John McCalle22a04a2009-11-04 23:02:40 +00001352 // Diagnose value-uses of fields to initialize themselves, e.g.
1353 // foo(foo)
1354 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001355 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001356 for (unsigned i = 0; i < NumArgs; ++i) {
1357 SourceLocation L;
1358 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1359 // FIXME: Return true in the case when other fields are used before being
1360 // uninitialized. For example, let this field be the i'th field. When
1361 // initializing the i'th field, throw a warning if any of the >= i'th
1362 // fields are used, as they are not yet initialized.
1363 // Right now we are only handling the case where the i'th field uses
1364 // itself in its initializer.
1365 Diag(L, diag::warn_field_is_uninit);
1366 }
1367 }
1368
Eli Friedman8e1433b2009-07-29 19:44:27 +00001369 bool HasDependentArg = false;
1370 for (unsigned i = 0; i < NumArgs; i++)
1371 HasDependentArg |= Args[i]->isTypeDependent();
1372
Chandler Carruthd44c3102010-12-06 09:23:57 +00001373 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001374 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001375 // Can't check initialization for a member of dependent type or when
1376 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001377 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1378 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001379
1380 // Erase any temporaries within this evaluation context; we're not
1381 // going to track them in the AST, since we'll be rebuilding the
1382 // ASTs during template instantiation.
1383 ExprTemporaries.erase(
1384 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1385 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001386 } else {
1387 // Initialize the member.
1388 InitializedEntity MemberEntity =
1389 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1390 : InitializedEntity::InitializeMember(IndirectMember, 0);
1391 InitializationKind Kind =
1392 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001393
Chandler Carruthd44c3102010-12-06 09:23:57 +00001394 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1395
1396 ExprResult MemberInit =
1397 InitSeq.Perform(*this, MemberEntity, Kind,
1398 MultiExprArg(*this, Args, NumArgs), 0);
1399 if (MemberInit.isInvalid())
1400 return true;
1401
1402 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1403
1404 // C++0x [class.base.init]p7:
1405 // The initialization of each base and member constitutes a
1406 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001407 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001408 if (MemberInit.isInvalid())
1409 return true;
1410
1411 // If we are in a dependent context, template instantiation will
1412 // perform this type-checking again. Just save the arguments that we
1413 // received in a ParenListExpr.
1414 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1415 // of the information that we have about the member
1416 // initializer. However, deconstructing the ASTs is a dicey process,
1417 // and this approach is far more likely to get the corner cases right.
1418 if (CurContext->isDependentContext())
1419 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1420 RParenLoc);
1421 else
1422 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001423 }
1424
Chandler Carruthd44c3102010-12-06 09:23:57 +00001425 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001426 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001427 IdLoc, LParenLoc, Init,
1428 RParenLoc);
1429 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001430 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001431 IdLoc, LParenLoc, Init,
1432 RParenLoc);
1433 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001434}
1435
John McCallfaf5fb42010-08-26 23:41:50 +00001436MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001437Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1438 Expr **Args, unsigned NumArgs,
1439 SourceLocation LParenLoc,
1440 SourceLocation RParenLoc,
1441 CXXRecordDecl *ClassDecl,
1442 SourceLocation EllipsisLoc) {
1443 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1444 if (!LangOpts.CPlusPlus0x)
1445 return Diag(Loc, diag::err_delegation_0x_only)
1446 << TInfo->getTypeLoc().getLocalSourceRange();
1447
1448 return Diag(Loc, diag::err_delegation_unimplemented)
1449 << TInfo->getTypeLoc().getLocalSourceRange();
1450}
1451
1452MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001453Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001454 Expr **Args, unsigned NumArgs,
1455 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001456 CXXRecordDecl *ClassDecl,
1457 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001458 bool HasDependentArg = false;
1459 for (unsigned i = 0; i < NumArgs; i++)
1460 HasDependentArg |= Args[i]->isTypeDependent();
1461
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001462 SourceLocation BaseLoc
1463 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1464
1465 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1466 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1467 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1468
1469 // C++ [class.base.init]p2:
1470 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001471 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001472 // of that class, the mem-initializer is ill-formed. A
1473 // mem-initializer-list can initialize a base class using any
1474 // name that denotes that base class type.
1475 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1476
Douglas Gregor44e7df62011-01-04 00:32:56 +00001477 if (EllipsisLoc.isValid()) {
1478 // This is a pack expansion.
1479 if (!BaseType->containsUnexpandedParameterPack()) {
1480 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1481 << SourceRange(BaseLoc, RParenLoc);
1482
1483 EllipsisLoc = SourceLocation();
1484 }
1485 } else {
1486 // Check for any unexpanded parameter packs.
1487 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1488 return true;
1489
1490 for (unsigned I = 0; I != NumArgs; ++I)
1491 if (DiagnoseUnexpandedParameterPack(Args[I]))
1492 return true;
1493 }
1494
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001495 // Check for direct and virtual base classes.
1496 const CXXBaseSpecifier *DirectBaseSpec = 0;
1497 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1498 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001499 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1500 BaseType))
1501 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1502 LParenLoc, RParenLoc, ClassDecl,
1503 EllipsisLoc);
1504
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001505 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1506 VirtualBaseSpec);
1507
1508 // C++ [base.class.init]p2:
1509 // Unless the mem-initializer-id names a nonstatic data member of the
1510 // constructor's class or a direct or virtual base of that class, the
1511 // mem-initializer is ill-formed.
1512 if (!DirectBaseSpec && !VirtualBaseSpec) {
1513 // If the class has any dependent bases, then it's possible that
1514 // one of those types will resolve to the same type as
1515 // BaseType. Therefore, just treat this as a dependent base
1516 // class initialization. FIXME: Should we try to check the
1517 // initialization anyway? It seems odd.
1518 if (ClassDecl->hasAnyDependentBases())
1519 Dependent = true;
1520 else
1521 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1522 << BaseType << Context.getTypeDeclType(ClassDecl)
1523 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1524 }
1525 }
1526
1527 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001528 // Can't check initialization for a base of dependent type or when
1529 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001530 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001531 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1532 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001533
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001534 // Erase any temporaries within this evaluation context; we're not
1535 // going to track them in the AST, since we'll be rebuilding the
1536 // ASTs during template instantiation.
1537 ExprTemporaries.erase(
1538 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1539 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001540
Alexis Hunt1d792652011-01-08 20:30:50 +00001541 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001542 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001543 LParenLoc,
1544 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001545 RParenLoc,
1546 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001547 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001548
1549 // C++ [base.class.init]p2:
1550 // If a mem-initializer-id is ambiguous because it designates both
1551 // a direct non-virtual base class and an inherited virtual base
1552 // class, the mem-initializer is ill-formed.
1553 if (DirectBaseSpec && VirtualBaseSpec)
1554 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001555 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001556
1557 CXXBaseSpecifier *BaseSpec
1558 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1559 if (!BaseSpec)
1560 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1561
1562 // Initialize the base.
1563 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001564 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001565 InitializationKind Kind =
1566 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1567
1568 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1569
John McCalldadc5752010-08-24 06:29:42 +00001570 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001571 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001572 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001573 if (BaseInit.isInvalid())
1574 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001575
1576 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001577
1578 // C++0x [class.base.init]p7:
1579 // The initialization of each base and member constitutes a
1580 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001581 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001582 if (BaseInit.isInvalid())
1583 return true;
1584
1585 // If we are in a dependent context, template instantiation will
1586 // perform this type-checking again. Just save the arguments that we
1587 // received in a ParenListExpr.
1588 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1589 // of the information that we have about the base
1590 // initializer. However, deconstructing the ASTs is a dicey process,
1591 // and this approach is far more likely to get the corner cases right.
1592 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001593 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001594 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1595 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001596 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001597 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001598 LParenLoc,
1599 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001600 RParenLoc,
1601 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001602 }
1603
Alexis Hunt1d792652011-01-08 20:30:50 +00001604 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001605 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001606 LParenLoc,
1607 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001608 RParenLoc,
1609 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001610}
1611
Anders Carlsson1b00e242010-04-23 03:10:23 +00001612/// ImplicitInitializerKind - How an implicit base or member initializer should
1613/// initialize its base or member.
1614enum ImplicitInitializerKind {
1615 IIK_Default,
1616 IIK_Copy,
1617 IIK_Move
1618};
1619
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001620static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001621BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001622 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001623 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001624 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001625 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001626 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001627 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1628 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001629
John McCalldadc5752010-08-24 06:29:42 +00001630 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001631
1632 switch (ImplicitInitKind) {
1633 case IIK_Default: {
1634 InitializationKind InitKind
1635 = InitializationKind::CreateDefault(Constructor->getLocation());
1636 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1637 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001638 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001639 break;
1640 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001641
Anders Carlsson1b00e242010-04-23 03:10:23 +00001642 case IIK_Copy: {
1643 ParmVarDecl *Param = Constructor->getParamDecl(0);
1644 QualType ParamType = Param->getType().getNonReferenceType();
1645
1646 Expr *CopyCtorArg =
1647 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001648 Constructor->getLocation(), ParamType,
1649 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001650
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001651 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001652 QualType ArgTy =
1653 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1654 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001655
1656 CXXCastPath BasePath;
1657 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001658 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001659 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001660 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001661
Anders Carlsson1b00e242010-04-23 03:10:23 +00001662 InitializationKind InitKind
1663 = InitializationKind::CreateDirect(Constructor->getLocation(),
1664 SourceLocation(), SourceLocation());
1665 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1666 &CopyCtorArg, 1);
1667 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001668 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001669 break;
1670 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001671
Anders Carlsson1b00e242010-04-23 03:10:23 +00001672 case IIK_Move:
1673 assert(false && "Unhandled initializer kind!");
1674 }
John McCallb268a282010-08-23 23:25:46 +00001675
Douglas Gregora40433a2010-12-07 00:41:46 +00001676 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001677 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001678 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001679
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001680 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001681 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001682 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1683 SourceLocation()),
1684 BaseSpec->isVirtual(),
1685 SourceLocation(),
1686 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001687 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001688 SourceLocation());
1689
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001690 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001691}
1692
Anders Carlsson3c1db572010-04-23 02:15:47 +00001693static bool
1694BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001695 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001696 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001697 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001698 if (Field->isInvalidDecl())
1699 return true;
1700
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001701 SourceLocation Loc = Constructor->getLocation();
1702
Anders Carlsson423f5d82010-04-23 16:04:08 +00001703 if (ImplicitInitKind == IIK_Copy) {
1704 ParmVarDecl *Param = Constructor->getParamDecl(0);
1705 QualType ParamType = Param->getType().getNonReferenceType();
1706
1707 Expr *MemberExprBase =
1708 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001709 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001710
1711 // Build a reference to this field within the parameter.
1712 CXXScopeSpec SS;
1713 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1714 Sema::LookupMemberName);
1715 MemberLookup.addDecl(Field, AS_public);
1716 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001717 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001718 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001719 ParamType, Loc,
1720 /*IsArrow=*/false,
1721 SS,
1722 /*FirstQualifierInScope=*/0,
1723 MemberLookup,
1724 /*TemplateArgs=*/0);
1725 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001726 return true;
1727
Douglas Gregor94f9a482010-05-05 05:51:00 +00001728 // When the field we are copying is an array, create index variables for
1729 // each dimension of the array. We use these index variables to subscript
1730 // the source array, and other clients (e.g., CodeGen) will perform the
1731 // necessary iteration with these index variables.
1732 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1733 QualType BaseType = Field->getType();
1734 QualType SizeType = SemaRef.Context.getSizeType();
1735 while (const ConstantArrayType *Array
1736 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1737 // Create the iteration variable for this array index.
1738 IdentifierInfo *IterationVarName = 0;
1739 {
1740 llvm::SmallString<8> Str;
1741 llvm::raw_svector_ostream OS(Str);
1742 OS << "__i" << IndexVariables.size();
1743 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1744 }
1745 VarDecl *IterationVar
1746 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1747 IterationVarName, SizeType,
1748 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001749 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001750 IndexVariables.push_back(IterationVar);
1751
1752 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001753 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001754 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001755 assert(!IterationVarRef.isInvalid() &&
1756 "Reference to invented variable cannot fail!");
1757
1758 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001759 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001760 Loc,
John McCallb268a282010-08-23 23:25:46 +00001761 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001762 Loc);
1763 if (CopyCtorArg.isInvalid())
1764 return true;
1765
1766 BaseType = Array->getElementType();
1767 }
1768
1769 // Construct the entity that we will be initializing. For an array, this
1770 // will be first element in the array, which may require several levels
1771 // of array-subscript entities.
1772 llvm::SmallVector<InitializedEntity, 4> Entities;
1773 Entities.reserve(1 + IndexVariables.size());
1774 Entities.push_back(InitializedEntity::InitializeMember(Field));
1775 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1776 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1777 0,
1778 Entities.back()));
1779
1780 // Direct-initialize to use the copy constructor.
1781 InitializationKind InitKind =
1782 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1783
1784 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1785 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1786 &CopyCtorArgE, 1);
1787
John McCalldadc5752010-08-24 06:29:42 +00001788 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001789 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001790 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001791 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001792 if (MemberInit.isInvalid())
1793 return true;
1794
1795 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001796 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001797 MemberInit.takeAs<Expr>(), Loc,
1798 IndexVariables.data(),
1799 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001800 return false;
1801 }
1802
Anders Carlsson423f5d82010-04-23 16:04:08 +00001803 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1804
Anders Carlsson3c1db572010-04-23 02:15:47 +00001805 QualType FieldBaseElementType =
1806 SemaRef.Context.getBaseElementType(Field->getType());
1807
Anders Carlsson3c1db572010-04-23 02:15:47 +00001808 if (FieldBaseElementType->isRecordType()) {
1809 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001810 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001811 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001812
1813 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001814 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001815 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001816
Douglas Gregora40433a2010-12-07 00:41:46 +00001817 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001818 if (MemberInit.isInvalid())
1819 return true;
1820
1821 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001822 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001823 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001824 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001825 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001826 return false;
1827 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001828
1829 if (FieldBaseElementType->isReferenceType()) {
1830 SemaRef.Diag(Constructor->getLocation(),
1831 diag::err_uninitialized_member_in_ctor)
1832 << (int)Constructor->isImplicit()
1833 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1834 << 0 << Field->getDeclName();
1835 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1836 return true;
1837 }
1838
1839 if (FieldBaseElementType.isConstQualified()) {
1840 SemaRef.Diag(Constructor->getLocation(),
1841 diag::err_uninitialized_member_in_ctor)
1842 << (int)Constructor->isImplicit()
1843 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1844 << 1 << Field->getDeclName();
1845 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1846 return true;
1847 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001848
1849 // Nothing to initialize.
1850 CXXMemberInit = 0;
1851 return false;
1852}
John McCallbc83b3f2010-05-20 23:23:51 +00001853
1854namespace {
1855struct BaseAndFieldInfo {
1856 Sema &S;
1857 CXXConstructorDecl *Ctor;
1858 bool AnyErrorsInInits;
1859 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001860 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1861 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001862
1863 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1864 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1865 // FIXME: Handle implicit move constructors.
1866 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1867 IIK = IIK_Copy;
1868 else
1869 IIK = IIK_Default;
1870 }
1871};
1872}
1873
1874static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1875 FieldDecl *Top, FieldDecl *Field) {
1876
Chandler Carruth139e9622010-06-30 02:59:29 +00001877 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001878 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001879 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001880 return false;
1881 }
1882
1883 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1884 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1885 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001886 CXXRecordDecl *FieldClassDecl
1887 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001888
1889 // Even though union members never have non-trivial default
1890 // constructions in C++03, we still build member initializers for aggregate
1891 // record types which can be union members, and C++0x allows non-trivial
1892 // default constructors for union members, so we ensure that only one
1893 // member is initialized for these.
1894 if (FieldClassDecl->isUnion()) {
1895 // First check for an explicit initializer for one field.
1896 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1897 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001898 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001899 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001900
1901 // Once we've initialized a field of an anonymous union, the union
1902 // field in the class is also initialized, so exit immediately.
1903 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001904 } else if ((*FA)->isAnonymousStructOrUnion()) {
1905 if (CollectFieldInitializer(Info, Top, *FA))
1906 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001907 }
1908 }
1909
1910 // Fallthrough and construct a default initializer for the union as
1911 // a whole, which can call its default constructor if such a thing exists
1912 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1913 // behavior going forward with C++0x, when anonymous unions there are
1914 // finalized, we should revisit this.
1915 } else {
1916 // For structs, we simply descend through to initialize all members where
1917 // necessary.
1918 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1919 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1920 if (CollectFieldInitializer(Info, Top, *FA))
1921 return true;
1922 }
1923 }
John McCallbc83b3f2010-05-20 23:23:51 +00001924 }
1925
1926 // Don't try to build an implicit initializer if there were semantic
1927 // errors in any of the initializers (and therefore we might be
1928 // missing some that the user actually wrote).
1929 if (Info.AnyErrorsInInits)
1930 return false;
1931
Alexis Hunt1d792652011-01-08 20:30:50 +00001932 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001933 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1934 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001935
Francois Pichetd583da02010-12-04 09:14:42 +00001936 if (Init)
1937 Info.AllToInit.push_back(Init);
1938
John McCallbc83b3f2010-05-20 23:23:51 +00001939 return false;
1940}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001941
Eli Friedman9cf6b592009-11-09 19:20:36 +00001942bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001943Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1944 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001945 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001946 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001947 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001948 // Just store the initializers as written, they will be checked during
1949 // instantiation.
1950 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001951 Constructor->setNumCtorInitializers(NumInitializers);
1952 CXXCtorInitializer **baseOrMemberInitializers =
1953 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001954 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001955 NumInitializers * sizeof(CXXCtorInitializer*));
1956 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001957 }
1958
1959 return false;
1960 }
1961
John McCallbc83b3f2010-05-20 23:23:51 +00001962 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001963
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001964 // We need to build the initializer AST according to order of construction
1965 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001966 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001967 if (!ClassDecl)
1968 return true;
1969
Eli Friedman9cf6b592009-11-09 19:20:36 +00001970 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001971
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001972 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001973 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001974
1975 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001976 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001977 else
Francois Pichetd583da02010-12-04 09:14:42 +00001978 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001979 }
1980
Anders Carlsson43c64af2010-04-21 19:52:01 +00001981 // Keep track of the direct virtual bases.
1982 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1983 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1984 E = ClassDecl->bases_end(); I != E; ++I) {
1985 if (I->isVirtual())
1986 DirectVBases.insert(I);
1987 }
1988
Anders Carlssondb0a9652010-04-02 06:26:44 +00001989 // Push virtual bases before others.
1990 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1991 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1992
Alexis Hunt1d792652011-01-08 20:30:50 +00001993 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001994 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1995 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001996 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001997 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00001998 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001999 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002000 VBase, IsInheritedVirtualBase,
2001 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002002 HadError = true;
2003 continue;
2004 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002005
John McCallbc83b3f2010-05-20 23:23:51 +00002006 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002007 }
2008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
John McCallbc83b3f2010-05-20 23:23:51 +00002010 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002011 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2012 E = ClassDecl->bases_end(); Base != E; ++Base) {
2013 // Virtuals are in the virtual base list and already constructed.
2014 if (Base->isVirtual())
2015 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Alexis Hunt1d792652011-01-08 20:30:50 +00002017 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002018 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2019 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002020 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002021 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002022 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002023 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002024 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002025 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002026 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002027 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002028
John McCallbc83b3f2010-05-20 23:23:51 +00002029 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002030 }
2031 }
Mike Stump11289f42009-09-09 15:08:12 +00002032
John McCallbc83b3f2010-05-20 23:23:51 +00002033 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002034 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002035 E = ClassDecl->field_end(); Field != E; ++Field) {
2036 if ((*Field)->getType()->isIncompleteArrayType()) {
2037 assert(ClassDecl->hasFlexibleArrayMember() &&
2038 "Incomplete array type is not valid");
2039 continue;
2040 }
John McCallbc83b3f2010-05-20 23:23:51 +00002041 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002042 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002043 }
Mike Stump11289f42009-09-09 15:08:12 +00002044
John McCallbc83b3f2010-05-20 23:23:51 +00002045 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002046 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002047 Constructor->setNumCtorInitializers(NumInitializers);
2048 CXXCtorInitializer **baseOrMemberInitializers =
2049 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002050 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002051 NumInitializers * sizeof(CXXCtorInitializer*));
2052 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002053
John McCalla6309952010-03-16 21:39:52 +00002054 // Constructors implicitly reference the base and member
2055 // destructors.
2056 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2057 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002058 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002059
2060 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002061}
2062
Eli Friedman952c15d2009-07-21 19:28:10 +00002063static void *GetKeyForTopLevelField(FieldDecl *Field) {
2064 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002065 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002066 if (RT->getDecl()->isAnonymousStructOrUnion())
2067 return static_cast<void *>(RT->getDecl());
2068 }
2069 return static_cast<void *>(Field);
2070}
2071
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002072static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002073 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002074}
2075
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002076static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002077 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002078 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002079 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002080
Eli Friedman952c15d2009-07-21 19:28:10 +00002081 // For fields injected into the class via declaration of an anonymous union,
2082 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002083 FieldDecl *Field = Member->getAnyMember();
2084
John McCall23eebd92010-04-10 09:28:51 +00002085 // If the field is a member of an anonymous struct or union, our key
2086 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002087 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002088 if (RD->isAnonymousStructOrUnion()) {
2089 while (true) {
2090 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2091 if (Parent->isAnonymousStructOrUnion())
2092 RD = Parent;
2093 else
2094 break;
2095 }
2096
Anders Carlsson83ac3122010-03-30 16:19:37 +00002097 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002098 }
Mike Stump11289f42009-09-09 15:08:12 +00002099
Anders Carlssona942dcd2010-03-30 15:39:27 +00002100 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002101}
2102
Anders Carlssone857b292010-04-02 03:37:03 +00002103static void
2104DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002105 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002106 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002107 unsigned NumInits) {
2108 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002109 return;
Mike Stump11289f42009-09-09 15:08:12 +00002110
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002111 // Don't check initializers order unless the warning is enabled at the
2112 // location of at least one initializer.
2113 bool ShouldCheckOrder = false;
2114 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002115 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002116 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2117 Init->getSourceLocation())
2118 != Diagnostic::Ignored) {
2119 ShouldCheckOrder = true;
2120 break;
2121 }
2122 }
2123 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002124 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002125
John McCallbb7b6582010-04-10 07:37:23 +00002126 // Build the list of bases and members in the order that they'll
2127 // actually be initialized. The explicit initializers should be in
2128 // this same order but may be missing things.
2129 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002130
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002131 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2132
John McCallbb7b6582010-04-10 07:37:23 +00002133 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002134 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002135 ClassDecl->vbases_begin(),
2136 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002137 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002138
John McCallbb7b6582010-04-10 07:37:23 +00002139 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002140 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002141 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002142 if (Base->isVirtual())
2143 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002144 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
John McCallbb7b6582010-04-10 07:37:23 +00002147 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002148 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2149 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002150 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002151
John McCallbb7b6582010-04-10 07:37:23 +00002152 unsigned NumIdealInits = IdealInitKeys.size();
2153 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002154
Alexis Hunt1d792652011-01-08 20:30:50 +00002155 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002156 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002157 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002158 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002159
2160 // Scan forward to try to find this initializer in the idealized
2161 // initializers list.
2162 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2163 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002164 break;
John McCallbb7b6582010-04-10 07:37:23 +00002165
2166 // If we didn't find this initializer, it must be because we
2167 // scanned past it on a previous iteration. That can only
2168 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002169 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002170 Sema::SemaDiagnosticBuilder D =
2171 SemaRef.Diag(PrevInit->getSourceLocation(),
2172 diag::warn_initializer_out_of_order);
2173
Francois Pichetd583da02010-12-04 09:14:42 +00002174 if (PrevInit->isAnyMemberInitializer())
2175 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002176 else
2177 D << 1 << PrevInit->getBaseClassInfo()->getType();
2178
Francois Pichetd583da02010-12-04 09:14:42 +00002179 if (Init->isAnyMemberInitializer())
2180 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002181 else
2182 D << 1 << Init->getBaseClassInfo()->getType();
2183
2184 // Move back to the initializer's location in the ideal list.
2185 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2186 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002187 break;
John McCallbb7b6582010-04-10 07:37:23 +00002188
2189 assert(IdealIndex != NumIdealInits &&
2190 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002191 }
John McCallbb7b6582010-04-10 07:37:23 +00002192
2193 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002194 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002195}
2196
John McCall23eebd92010-04-10 09:28:51 +00002197namespace {
2198bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002199 CXXCtorInitializer *Init,
2200 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002201 if (!PrevInit) {
2202 PrevInit = Init;
2203 return false;
2204 }
2205
2206 if (FieldDecl *Field = Init->getMember())
2207 S.Diag(Init->getSourceLocation(),
2208 diag::err_multiple_mem_initialization)
2209 << Field->getDeclName()
2210 << Init->getSourceRange();
2211 else {
John McCall424cec92011-01-19 06:33:43 +00002212 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002213 assert(BaseClass && "neither field nor base");
2214 S.Diag(Init->getSourceLocation(),
2215 diag::err_multiple_base_initialization)
2216 << QualType(BaseClass, 0)
2217 << Init->getSourceRange();
2218 }
2219 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2220 << 0 << PrevInit->getSourceRange();
2221
2222 return true;
2223}
2224
Alexis Hunt1d792652011-01-08 20:30:50 +00002225typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002226typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2227
2228bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002229 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002230 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002231 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002232 RecordDecl *Parent = Field->getParent();
2233 if (!Parent->isAnonymousStructOrUnion())
2234 return false;
2235
2236 NamedDecl *Child = Field;
2237 do {
2238 if (Parent->isUnion()) {
2239 UnionEntry &En = Unions[Parent];
2240 if (En.first && En.first != Child) {
2241 S.Diag(Init->getSourceLocation(),
2242 diag::err_multiple_mem_union_initialization)
2243 << Field->getDeclName()
2244 << Init->getSourceRange();
2245 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2246 << 0 << En.second->getSourceRange();
2247 return true;
2248 } else if (!En.first) {
2249 En.first = Child;
2250 En.second = Init;
2251 }
2252 }
2253
2254 Child = Parent;
2255 Parent = cast<RecordDecl>(Parent->getDeclContext());
2256 } while (Parent->isAnonymousStructOrUnion());
2257
2258 return false;
2259}
2260}
2261
Anders Carlssone857b292010-04-02 03:37:03 +00002262/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002263void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002264 SourceLocation ColonLoc,
2265 MemInitTy **meminits, unsigned NumMemInits,
2266 bool AnyErrors) {
2267 if (!ConstructorDecl)
2268 return;
2269
2270 AdjustDeclIfTemplate(ConstructorDecl);
2271
2272 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002273 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002274
2275 if (!Constructor) {
2276 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2277 return;
2278 }
2279
Alexis Hunt1d792652011-01-08 20:30:50 +00002280 CXXCtorInitializer **MemInits =
2281 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002282
2283 // Mapping for the duplicate initializers check.
2284 // For member initializers, this is keyed with a FieldDecl*.
2285 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002286 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002287
2288 // Mapping for the inconsistent anonymous-union initializers check.
2289 RedundantUnionMap MemberUnions;
2290
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002291 bool HadError = false;
2292 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002293 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002294
Abramo Bagnara341d7832010-05-26 18:09:23 +00002295 // Set the source order index.
2296 Init->setSourceOrder(i);
2297
Francois Pichetd583da02010-12-04 09:14:42 +00002298 if (Init->isAnyMemberInitializer()) {
2299 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002300 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2301 CheckRedundantUnionInit(*this, Init, MemberUnions))
2302 HadError = true;
2303 } else {
2304 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2305 if (CheckRedundantInit(*this, Init, Members[Key]))
2306 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002307 }
Anders Carlssone857b292010-04-02 03:37:03 +00002308 }
2309
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002310 if (HadError)
2311 return;
2312
Anders Carlssone857b292010-04-02 03:37:03 +00002313 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002314
Alexis Hunt1d792652011-01-08 20:30:50 +00002315 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002316}
2317
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002318void
John McCalla6309952010-03-16 21:39:52 +00002319Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2320 CXXRecordDecl *ClassDecl) {
2321 // Ignore dependent contexts.
2322 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002323 return;
John McCall1064d7e2010-03-16 05:22:47 +00002324
2325 // FIXME: all the access-control diagnostics are positioned on the
2326 // field/base declaration. That's probably good; that said, the
2327 // user might reasonably want to know why the destructor is being
2328 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002329
Anders Carlssondee9a302009-11-17 04:44:12 +00002330 // Non-static data members.
2331 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2332 E = ClassDecl->field_end(); I != E; ++I) {
2333 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002334 if (Field->isInvalidDecl())
2335 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002336 QualType FieldType = Context.getBaseElementType(Field->getType());
2337
2338 const RecordType* RT = FieldType->getAs<RecordType>();
2339 if (!RT)
2340 continue;
2341
2342 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2343 if (FieldClassDecl->hasTrivialDestructor())
2344 continue;
2345
Douglas Gregore71edda2010-07-01 22:47:18 +00002346 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002347 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002348 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002349 << Field->getDeclName()
2350 << FieldType);
2351
John McCalla6309952010-03-16 21:39:52 +00002352 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002353 }
2354
John McCall1064d7e2010-03-16 05:22:47 +00002355 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2356
Anders Carlssondee9a302009-11-17 04:44:12 +00002357 // Bases.
2358 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2359 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002360 // Bases are always records in a well-formed non-dependent class.
2361 const RecordType *RT = Base->getType()->getAs<RecordType>();
2362
2363 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002364 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002365 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002366
2367 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002368 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002369 if (BaseClassDecl->hasTrivialDestructor())
2370 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002371
Douglas Gregore71edda2010-07-01 22:47:18 +00002372 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002373
2374 // FIXME: caret should be on the start of the class name
2375 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002376 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002377 << Base->getType()
2378 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002379
John McCalla6309952010-03-16 21:39:52 +00002380 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002381 }
2382
2383 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002384 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2385 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002386
2387 // Bases are always records in a well-formed non-dependent class.
2388 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2389
2390 // Ignore direct virtual bases.
2391 if (DirectVirtualBases.count(RT))
2392 continue;
2393
Anders Carlssondee9a302009-11-17 04:44:12 +00002394 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002395 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002396 if (BaseClassDecl->hasTrivialDestructor())
2397 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002398
Douglas Gregore71edda2010-07-01 22:47:18 +00002399 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002400 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002401 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002402 << VBase->getType());
2403
John McCalla6309952010-03-16 21:39:52 +00002404 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002405 }
2406}
2407
John McCall48871652010-08-21 09:40:31 +00002408void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002409 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002410 return;
Mike Stump11289f42009-09-09 15:08:12 +00002411
Mike Stump11289f42009-09-09 15:08:12 +00002412 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002413 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002414 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002415}
2416
Mike Stump11289f42009-09-09 15:08:12 +00002417bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002418 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002419 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002420 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002421 else
John McCall02db245d2010-08-18 09:41:07 +00002422 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002423}
2424
Anders Carlssoneabf7702009-08-27 00:13:57 +00002425bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002426 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002427 if (!getLangOptions().CPlusPlus)
2428 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002429
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002430 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002431 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002433 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002434 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002435 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002436 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002437
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002438 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002439 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002440 }
Mike Stump11289f42009-09-09 15:08:12 +00002441
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002442 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002443 if (!RT)
2444 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002445
John McCall67da35c2010-02-04 22:26:26 +00002446 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002447
John McCall02db245d2010-08-18 09:41:07 +00002448 // We can't answer whether something is abstract until it has a
2449 // definition. If it's currently being defined, we'll walk back
2450 // over all the declarations when we have a full definition.
2451 const CXXRecordDecl *Def = RD->getDefinition();
2452 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002453 return false;
2454
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002455 if (!RD->isAbstract())
2456 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002457
Anders Carlssoneabf7702009-08-27 00:13:57 +00002458 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002459 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002460
John McCall02db245d2010-08-18 09:41:07 +00002461 return true;
2462}
2463
2464void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2465 // Check if we've already emitted the list of pure virtual functions
2466 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002467 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002468 return;
Mike Stump11289f42009-09-09 15:08:12 +00002469
Douglas Gregor4165bd62010-03-23 23:47:56 +00002470 CXXFinalOverriderMap FinalOverriders;
2471 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002472
Anders Carlssona2f74f32010-06-03 01:00:02 +00002473 // Keep a set of seen pure methods so we won't diagnose the same method
2474 // more than once.
2475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2476
Douglas Gregor4165bd62010-03-23 23:47:56 +00002477 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2478 MEnd = FinalOverriders.end();
2479 M != MEnd;
2480 ++M) {
2481 for (OverridingMethods::iterator SO = M->second.begin(),
2482 SOEnd = M->second.end();
2483 SO != SOEnd; ++SO) {
2484 // C++ [class.abstract]p4:
2485 // A class is abstract if it contains or inherits at least one
2486 // pure virtual function for which the final overrider is pure
2487 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregor4165bd62010-03-23 23:47:56 +00002489 //
2490 if (SO->second.size() != 1)
2491 continue;
2492
2493 if (!SO->second.front().Method->isPure())
2494 continue;
2495
Anders Carlssona2f74f32010-06-03 01:00:02 +00002496 if (!SeenPureMethods.insert(SO->second.front().Method))
2497 continue;
2498
Douglas Gregor4165bd62010-03-23 23:47:56 +00002499 Diag(SO->second.front().Method->getLocation(),
2500 diag::note_pure_virtual_function)
2501 << SO->second.front().Method->getDeclName();
2502 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002503 }
2504
2505 if (!PureVirtualClassDiagSet)
2506 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2507 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002508}
2509
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002510namespace {
John McCall02db245d2010-08-18 09:41:07 +00002511struct AbstractUsageInfo {
2512 Sema &S;
2513 CXXRecordDecl *Record;
2514 CanQualType AbstractType;
2515 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002516
John McCall02db245d2010-08-18 09:41:07 +00002517 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2518 : S(S), Record(Record),
2519 AbstractType(S.Context.getCanonicalType(
2520 S.Context.getTypeDeclType(Record))),
2521 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002522
John McCall02db245d2010-08-18 09:41:07 +00002523 void DiagnoseAbstractType() {
2524 if (Invalid) return;
2525 S.DiagnoseAbstractType(Record);
2526 Invalid = true;
2527 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002528
John McCall02db245d2010-08-18 09:41:07 +00002529 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2530};
2531
2532struct CheckAbstractUsage {
2533 AbstractUsageInfo &Info;
2534 const NamedDecl *Ctx;
2535
2536 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2537 : Info(Info), Ctx(Ctx) {}
2538
2539 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2540 switch (TL.getTypeLocClass()) {
2541#define ABSTRACT_TYPELOC(CLASS, PARENT)
2542#define TYPELOC(CLASS, PARENT) \
2543 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2544#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002545 }
John McCall02db245d2010-08-18 09:41:07 +00002546 }
Mike Stump11289f42009-09-09 15:08:12 +00002547
John McCall02db245d2010-08-18 09:41:07 +00002548 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2549 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2550 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2551 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2552 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002553 }
John McCall02db245d2010-08-18 09:41:07 +00002554 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002555
John McCall02db245d2010-08-18 09:41:07 +00002556 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2557 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
John McCall02db245d2010-08-18 09:41:07 +00002560 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2561 // Visit the type parameters from a permissive context.
2562 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2563 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2564 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2565 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2566 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2567 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002568 }
John McCall02db245d2010-08-18 09:41:07 +00002569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
John McCall02db245d2010-08-18 09:41:07 +00002571 // Visit pointee types from a permissive context.
2572#define CheckPolymorphic(Type) \
2573 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2574 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2575 }
2576 CheckPolymorphic(PointerTypeLoc)
2577 CheckPolymorphic(ReferenceTypeLoc)
2578 CheckPolymorphic(MemberPointerTypeLoc)
2579 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002580
John McCall02db245d2010-08-18 09:41:07 +00002581 /// Handle all the types we haven't given a more specific
2582 /// implementation for above.
2583 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2584 // Every other kind of type that we haven't called out already
2585 // that has an inner type is either (1) sugar or (2) contains that
2586 // inner type in some way as a subobject.
2587 if (TypeLoc Next = TL.getNextTypeLoc())
2588 return Visit(Next, Sel);
2589
2590 // If there's no inner type and we're in a permissive context,
2591 // don't diagnose.
2592 if (Sel == Sema::AbstractNone) return;
2593
2594 // Check whether the type matches the abstract type.
2595 QualType T = TL.getType();
2596 if (T->isArrayType()) {
2597 Sel = Sema::AbstractArrayType;
2598 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002599 }
John McCall02db245d2010-08-18 09:41:07 +00002600 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2601 if (CT != Info.AbstractType) return;
2602
2603 // It matched; do some magic.
2604 if (Sel == Sema::AbstractArrayType) {
2605 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2606 << T << TL.getSourceRange();
2607 } else {
2608 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2609 << Sel << T << TL.getSourceRange();
2610 }
2611 Info.DiagnoseAbstractType();
2612 }
2613};
2614
2615void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2616 Sema::AbstractDiagSelID Sel) {
2617 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2618}
2619
2620}
2621
2622/// Check for invalid uses of an abstract type in a method declaration.
2623static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2624 CXXMethodDecl *MD) {
2625 // No need to do the check on definitions, which require that
2626 // the return/param types be complete.
2627 if (MD->isThisDeclarationADefinition())
2628 return;
2629
2630 // For safety's sake, just ignore it if we don't have type source
2631 // information. This should never happen for non-implicit methods,
2632 // but...
2633 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2634 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2635}
2636
2637/// Check for invalid uses of an abstract type within a class definition.
2638static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2639 CXXRecordDecl *RD) {
2640 for (CXXRecordDecl::decl_iterator
2641 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2642 Decl *D = *I;
2643 if (D->isImplicit()) continue;
2644
2645 // Methods and method templates.
2646 if (isa<CXXMethodDecl>(D)) {
2647 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2648 } else if (isa<FunctionTemplateDecl>(D)) {
2649 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2650 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2651
2652 // Fields and static variables.
2653 } else if (isa<FieldDecl>(D)) {
2654 FieldDecl *FD = cast<FieldDecl>(D);
2655 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2656 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2657 } else if (isa<VarDecl>(D)) {
2658 VarDecl *VD = cast<VarDecl>(D);
2659 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2660 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2661
2662 // Nested classes and class templates.
2663 } else if (isa<CXXRecordDecl>(D)) {
2664 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2665 } else if (isa<ClassTemplateDecl>(D)) {
2666 CheckAbstractClassUsage(Info,
2667 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2668 }
2669 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002670}
2671
Douglas Gregorc99f1552009-12-03 18:33:45 +00002672/// \brief Perform semantic checks on a class definition that has been
2673/// completing, introducing implicitly-declared members, checking for
2674/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002675void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002676 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002677 return;
2678
John McCall02db245d2010-08-18 09:41:07 +00002679 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2680 AbstractUsageInfo Info(*this, Record);
2681 CheckAbstractClassUsage(Info, Record);
2682 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002683
2684 // If this is not an aggregate type and has no user-declared constructor,
2685 // complain about any non-static data members of reference or const scalar
2686 // type, since they will never get initializers.
2687 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2688 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2689 bool Complained = false;
2690 for (RecordDecl::field_iterator F = Record->field_begin(),
2691 FEnd = Record->field_end();
2692 F != FEnd; ++F) {
2693 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002694 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002695 if (!Complained) {
2696 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2697 << Record->getTagKind() << Record;
2698 Complained = true;
2699 }
2700
2701 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2702 << F->getType()->isReferenceType()
2703 << F->getDeclName();
2704 }
2705 }
2706 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002707
2708 if (Record->isDynamicClass())
2709 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002710
2711 if (Record->getIdentifier()) {
2712 // C++ [class.mem]p13:
2713 // If T is the name of a class, then each of the following shall have a
2714 // name different from T:
2715 // - every member of every anonymous union that is a member of class T.
2716 //
2717 // C++ [class.mem]p14:
2718 // In addition, if class T has a user-declared constructor (12.1), every
2719 // non-static data member of class T shall have a name different from T.
2720 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002721 R.first != R.second; ++R.first) {
2722 NamedDecl *D = *R.first;
2723 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2724 isa<IndirectFieldDecl>(D)) {
2725 Diag(D->getLocation(), diag::err_member_name_of_class)
2726 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002727 break;
2728 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002729 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002730 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002731}
2732
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002733void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002734 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002735 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002736 SourceLocation RBrac,
2737 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002738 if (!TagDecl)
2739 return;
Mike Stump11289f42009-09-09 15:08:12 +00002740
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002741 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002742
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002743 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002744 // strict aliasing violation!
2745 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002746 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002747
Douglas Gregor0be31a22010-07-02 17:43:08 +00002748 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002749 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002750}
2751
Douglas Gregor95755162010-07-01 05:10:53 +00002752namespace {
2753 /// \brief Helper class that collects exception specifications for
2754 /// implicitly-declared special member functions.
2755 class ImplicitExceptionSpecification {
2756 ASTContext &Context;
2757 bool AllowsAllExceptions;
2758 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2759 llvm::SmallVector<QualType, 4> Exceptions;
2760
2761 public:
2762 explicit ImplicitExceptionSpecification(ASTContext &Context)
2763 : Context(Context), AllowsAllExceptions(false) { }
2764
2765 /// \brief Whether the special member function should have any
2766 /// exception specification at all.
2767 bool hasExceptionSpecification() const {
2768 return !AllowsAllExceptions;
2769 }
2770
2771 /// \brief Whether the special member function should have a
2772 /// throw(...) exception specification (a Microsoft extension).
2773 bool hasAnyExceptionSpecification() const {
2774 return false;
2775 }
2776
2777 /// \brief The number of exceptions in the exception specification.
2778 unsigned size() const { return Exceptions.size(); }
2779
2780 /// \brief The set of exceptions in the exception specification.
2781 const QualType *data() const { return Exceptions.data(); }
2782
2783 /// \brief Note that
2784 void CalledDecl(CXXMethodDecl *Method) {
2785 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002786 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002787 return;
2788
2789 const FunctionProtoType *Proto
2790 = Method->getType()->getAs<FunctionProtoType>();
2791
2792 // If this function can throw any exceptions, make a note of that.
2793 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2794 AllowsAllExceptions = true;
2795 ExceptionsSeen.clear();
2796 Exceptions.clear();
2797 return;
2798 }
2799
2800 // Record the exceptions in this function's exception specification.
2801 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2802 EEnd = Proto->exception_end();
2803 E != EEnd; ++E)
2804 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2805 Exceptions.push_back(*E);
2806 }
2807 };
2808}
2809
2810
Douglas Gregor05379422008-11-03 17:51:48 +00002811/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2812/// special functions, such as the default constructor, copy
2813/// constructor, or destructor, to the given C++ class (C++
2814/// [special]p1). This routine can only be executed just before the
2815/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002816void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002817 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002818 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002819
Douglas Gregor54be3392010-07-01 17:57:27 +00002820 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002821 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002822
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002823 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2824 ++ASTContext::NumImplicitCopyAssignmentOperators;
2825
2826 // If we have a dynamic class, then the copy assignment operator may be
2827 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2828 // it shows up in the right place in the vtable and that we diagnose
2829 // problems with the implicit exception specification.
2830 if (ClassDecl->isDynamicClass())
2831 DeclareImplicitCopyAssignment(ClassDecl);
2832 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002833
Douglas Gregor7454c562010-07-02 20:37:36 +00002834 if (!ClassDecl->hasUserDeclaredDestructor()) {
2835 ++ASTContext::NumImplicitDestructors;
2836
2837 // If we have a dynamic class, then the destructor may be virtual, so we
2838 // have to declare the destructor immediately. This ensures that, e.g., it
2839 // shows up in the right place in the vtable and that we diagnose problems
2840 // with the implicit exception specification.
2841 if (ClassDecl->isDynamicClass())
2842 DeclareImplicitDestructor(ClassDecl);
2843 }
Douglas Gregor05379422008-11-03 17:51:48 +00002844}
2845
John McCall48871652010-08-21 09:40:31 +00002846void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002847 if (!D)
2848 return;
2849
2850 TemplateParameterList *Params = 0;
2851 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2852 Params = Template->getTemplateParameters();
2853 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2854 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2855 Params = PartialSpec->getTemplateParameters();
2856 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002857 return;
2858
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002859 for (TemplateParameterList::iterator Param = Params->begin(),
2860 ParamEnd = Params->end();
2861 Param != ParamEnd; ++Param) {
2862 NamedDecl *Named = cast<NamedDecl>(*Param);
2863 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002864 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002865 IdResolver.AddDecl(Named);
2866 }
2867 }
2868}
2869
John McCall48871652010-08-21 09:40:31 +00002870void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002871 if (!RecordD) return;
2872 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002873 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002874 PushDeclContext(S, Record);
2875}
2876
John McCall48871652010-08-21 09:40:31 +00002877void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002878 if (!RecordD) return;
2879 PopDeclContext();
2880}
2881
Douglas Gregor4d87df52008-12-16 21:30:33 +00002882/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2883/// parsing a top-level (non-nested) C++ class, and we are now
2884/// parsing those parts of the given Method declaration that could
2885/// not be parsed earlier (C++ [class.mem]p2), such as default
2886/// arguments. This action should enter the scope of the given
2887/// Method declaration as if we had just parsed the qualified method
2888/// name. However, it should not bring the parameters into scope;
2889/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002890void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002891}
2892
2893/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2894/// C++ method declaration. We're (re-)introducing the given
2895/// function parameter into scope for use in parsing later parts of
2896/// the method declaration. For example, we could see an
2897/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002898void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002899 if (!ParamD)
2900 return;
Mike Stump11289f42009-09-09 15:08:12 +00002901
John McCall48871652010-08-21 09:40:31 +00002902 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002903
2904 // If this parameter has an unparsed default argument, clear it out
2905 // to make way for the parsed default argument.
2906 if (Param->hasUnparsedDefaultArg())
2907 Param->setDefaultArg(0);
2908
John McCall48871652010-08-21 09:40:31 +00002909 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002910 if (Param->getDeclName())
2911 IdResolver.AddDecl(Param);
2912}
2913
2914/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2915/// processing the delayed method declaration for Method. The method
2916/// declaration is now considered finished. There may be a separate
2917/// ActOnStartOfFunctionDef action later (not necessarily
2918/// immediately!) for this method, if it was also defined inside the
2919/// class body.
John McCall48871652010-08-21 09:40:31 +00002920void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002921 if (!MethodD)
2922 return;
Mike Stump11289f42009-09-09 15:08:12 +00002923
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002924 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002925
John McCall48871652010-08-21 09:40:31 +00002926 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002927
2928 // Now that we have our default arguments, check the constructor
2929 // again. It could produce additional diagnostics or affect whether
2930 // the class has implicitly-declared destructors, among other
2931 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002932 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2933 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002934
2935 // Check the default arguments, which we may have added.
2936 if (!Method->isInvalidDecl())
2937 CheckCXXDefaultArguments(Method);
2938}
2939
Douglas Gregor831c93f2008-11-05 20:51:48 +00002940/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002941/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002942/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002943/// emit diagnostics and set the invalid bit to true. In any case, the type
2944/// will be updated to reflect a well-formed type for the constructor and
2945/// returned.
2946QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002947 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002948 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002949
2950 // C++ [class.ctor]p3:
2951 // A constructor shall not be virtual (10.3) or static (9.4). A
2952 // constructor can be invoked for a const, volatile or const
2953 // volatile object. A constructor shall not be declared const,
2954 // volatile, or const volatile (9.3.2).
2955 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002956 if (!D.isInvalidType())
2957 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2958 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2959 << SourceRange(D.getIdentifierLoc());
2960 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002961 }
John McCall8e7d6562010-08-26 03:08:43 +00002962 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002963 if (!D.isInvalidType())
2964 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2965 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2966 << SourceRange(D.getIdentifierLoc());
2967 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002968 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002969 }
Mike Stump11289f42009-09-09 15:08:12 +00002970
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002971 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00002972 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002973 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002974 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2975 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002976 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2978 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002979 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2981 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00002982 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002983 }
Mike Stump11289f42009-09-09 15:08:12 +00002984
Douglas Gregor831c93f2008-11-05 20:51:48 +00002985 // Rebuild the function type "R" without any type qualifiers (in
2986 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002987 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002988 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002989 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
2990 return R;
2991
2992 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2993 EPI.TypeQuals = 0;
2994
Chris Lattner38378bf2009-04-25 08:28:21 +00002995 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00002996 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002997}
2998
Douglas Gregor4d87df52008-12-16 21:30:33 +00002999/// CheckConstructor - Checks a fully-formed constructor for
3000/// well-formedness, issuing any diagnostics required. Returns true if
3001/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003002void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003003 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003004 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3005 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003006 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003007
3008 // C++ [class.copy]p3:
3009 // A declaration of a constructor for a class X is ill-formed if
3010 // its first parameter is of type (optionally cv-qualified) X and
3011 // either there are no other parameters or else all other
3012 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003013 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003014 ((Constructor->getNumParams() == 1) ||
3015 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003016 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3017 Constructor->getTemplateSpecializationKind()
3018 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003019 QualType ParamType = Constructor->getParamDecl(0)->getType();
3020 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3021 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003022 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003023 const char *ConstRef
3024 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3025 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003026 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003027 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003028
3029 // FIXME: Rather that making the constructor invalid, we should endeavor
3030 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003031 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003032 }
3033 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003034}
3035
John McCalldeb646e2010-08-04 01:04:25 +00003036/// CheckDestructor - Checks a fully-formed destructor definition for
3037/// well-formedness, issuing any diagnostics required. Returns true
3038/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003039bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003040 CXXRecordDecl *RD = Destructor->getParent();
3041
3042 if (Destructor->isVirtual()) {
3043 SourceLocation Loc;
3044
3045 if (!Destructor->isImplicit())
3046 Loc = Destructor->getLocation();
3047 else
3048 Loc = RD->getLocation();
3049
3050 // If we have a virtual destructor, look up the deallocation function
3051 FunctionDecl *OperatorDelete = 0;
3052 DeclarationName Name =
3053 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003054 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003055 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003056
3057 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003058
3059 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003060 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003061
3062 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003063}
3064
Mike Stump11289f42009-09-09 15:08:12 +00003065static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003066FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3067 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3068 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003069 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003070}
3071
Douglas Gregor831c93f2008-11-05 20:51:48 +00003072/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3073/// the well-formednes of the destructor declarator @p D with type @p
3074/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003075/// emit diagnostics and set the declarator to invalid. Even if this happens,
3076/// will be updated to reflect a well-formed type for the destructor and
3077/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003078QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003079 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003080 // C++ [class.dtor]p1:
3081 // [...] A typedef-name that names a class is a class-name
3082 // (7.1.3); however, a typedef-name that names a class shall not
3083 // be used as the identifier in the declarator for a destructor
3084 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003085 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003086 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003087 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003088 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003089
3090 // C++ [class.dtor]p2:
3091 // A destructor is used to destroy objects of its class type. A
3092 // destructor takes no parameters, and no return type can be
3093 // specified for it (not even void). The address of a destructor
3094 // shall not be taken. A destructor shall not be static. A
3095 // destructor can be invoked for a const, volatile or const
3096 // volatile object. A destructor shall not be declared const,
3097 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003098 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003099 if (!D.isInvalidType())
3100 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3101 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003102 << SourceRange(D.getIdentifierLoc())
3103 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3104
John McCall8e7d6562010-08-26 03:08:43 +00003105 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003106 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003107 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003108 // Destructors don't have return types, but the parser will
3109 // happily parse something like:
3110 //
3111 // class X {
3112 // float ~X();
3113 // };
3114 //
3115 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003116 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3117 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3118 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003119 }
Mike Stump11289f42009-09-09 15:08:12 +00003120
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003121 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003122 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003123 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003124 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3125 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003126 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003127 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3128 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003129 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003130 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3131 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003132 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003133 }
3134
3135 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003136 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003137 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3138
3139 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003140 FTI.freeArgs();
3141 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003142 }
3143
Mike Stump11289f42009-09-09 15:08:12 +00003144 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003145 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003146 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003147 D.setInvalidType();
3148 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003149
3150 // Rebuild the function type "R" without any type qualifiers or
3151 // parameters (in case any of the errors above fired) and with
3152 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003153 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003154 if (!D.isInvalidType())
3155 return R;
3156
Douglas Gregor95755162010-07-01 05:10:53 +00003157 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003158 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3159 EPI.Variadic = false;
3160 EPI.TypeQuals = 0;
3161 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003162}
3163
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003164/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3165/// well-formednes of the conversion function declarator @p D with
3166/// type @p R. If there are any errors in the declarator, this routine
3167/// will emit diagnostics and return true. Otherwise, it will return
3168/// false. Either way, the type @p R will be updated to reflect a
3169/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003170void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003171 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003172 // C++ [class.conv.fct]p1:
3173 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003174 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003175 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003176 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003177 if (!D.isInvalidType())
3178 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3179 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3180 << SourceRange(D.getIdentifierLoc());
3181 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003182 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003183 }
John McCall212fa2e2010-04-13 00:04:31 +00003184
3185 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3186
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003187 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003188 // Conversion functions don't have return types, but the parser will
3189 // happily parse something like:
3190 //
3191 // class X {
3192 // float operator bool();
3193 // };
3194 //
3195 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003196 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3197 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3198 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003199 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003200 }
3201
John McCall212fa2e2010-04-13 00:04:31 +00003202 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3203
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003204 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003205 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003206 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3207
3208 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003209 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003210 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003211 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003212 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003213 D.setInvalidType();
3214 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003215
John McCall212fa2e2010-04-13 00:04:31 +00003216 // Diagnose "&operator bool()" and other such nonsense. This
3217 // is actually a gcc extension which we don't support.
3218 if (Proto->getResultType() != ConvType) {
3219 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3220 << Proto->getResultType();
3221 D.setInvalidType();
3222 ConvType = Proto->getResultType();
3223 }
3224
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003225 // C++ [class.conv.fct]p4:
3226 // The conversion-type-id shall not represent a function type nor
3227 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003228 if (ConvType->isArrayType()) {
3229 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3230 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003231 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003232 } else if (ConvType->isFunctionType()) {
3233 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3234 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003235 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003236 }
3237
3238 // Rebuild the function type "R" without any parameters (in case any
3239 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003240 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003241 if (D.isInvalidType())
3242 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003243
Douglas Gregor5fb53972009-01-14 15:45:31 +00003244 // C++0x explicit conversion operators.
3245 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003246 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003247 diag::warn_explicit_conversion_functions)
3248 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003249}
3250
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003251/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3252/// the declaration of the given C++ conversion function. This routine
3253/// is responsible for recording the conversion function in the C++
3254/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003255Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003256 assert(Conversion && "Expected to receive a conversion function declaration");
3257
Douglas Gregor4287b372008-12-12 08:25:50 +00003258 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003259
3260 // Make sure we aren't redeclaring the conversion function.
3261 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003262
3263 // C++ [class.conv.fct]p1:
3264 // [...] A conversion function is never used to convert a
3265 // (possibly cv-qualified) object to the (possibly cv-qualified)
3266 // same object type (or a reference to it), to a (possibly
3267 // cv-qualified) base class of that type (or a reference to it),
3268 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003269 // FIXME: Suppress this warning if the conversion function ends up being a
3270 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003271 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003272 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003273 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003274 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003275 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3276 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003277 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003278 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003279 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3280 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003281 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003282 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003283 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003284 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003285 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003286 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003287 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003288 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003289 }
3290
Douglas Gregor457104e2010-09-29 04:25:11 +00003291 if (FunctionTemplateDecl *ConversionTemplate
3292 = Conversion->getDescribedFunctionTemplate())
3293 return ConversionTemplate;
3294
John McCall48871652010-08-21 09:40:31 +00003295 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003296}
3297
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003298//===----------------------------------------------------------------------===//
3299// Namespace Handling
3300//===----------------------------------------------------------------------===//
3301
John McCallb1be5232010-08-26 09:15:37 +00003302
3303
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003304/// ActOnStartNamespaceDef - This is called at the start of a namespace
3305/// definition.
John McCall48871652010-08-21 09:40:31 +00003306Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003307 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003308 SourceLocation IdentLoc,
3309 IdentifierInfo *II,
3310 SourceLocation LBrace,
3311 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003312 // anonymous namespace starts at its left brace
3313 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3314 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003315 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003316 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003317
3318 Scope *DeclRegionScope = NamespcScope->getParent();
3319
Anders Carlssona7bcade2010-02-07 01:09:23 +00003320 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3321
John McCall2faf32c2010-12-10 02:59:44 +00003322 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3323 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003324
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003325 if (II) {
3326 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003327 // The identifier in an original-namespace-definition shall not
3328 // have been previously defined in the declarative region in
3329 // which the original-namespace-definition appears. The
3330 // identifier in an original-namespace-definition is the name of
3331 // the namespace. Subsequently in that declarative region, it is
3332 // treated as an original-namespace-name.
3333 //
3334 // Since namespace names are unique in their scope, and we don't
3335 // look through using directives, just
3336 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3337 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003338
Douglas Gregor91f84212008-12-11 16:49:14 +00003339 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3340 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003341 if (Namespc->isInline() != OrigNS->isInline()) {
3342 // inline-ness must match
3343 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3344 << Namespc->isInline();
3345 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3346 Namespc->setInvalidDecl();
3347 // Recover by ignoring the new namespace's inline status.
3348 Namespc->setInline(OrigNS->isInline());
3349 }
3350
Douglas Gregor91f84212008-12-11 16:49:14 +00003351 // Attach this namespace decl to the chain of extended namespace
3352 // definitions.
3353 OrigNS->setNextNamespace(Namespc);
3354 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003355
Mike Stump11289f42009-09-09 15:08:12 +00003356 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003357 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003358 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003359 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003360 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003361 } else if (PrevDecl) {
3362 // This is an invalid name redefinition.
3363 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3364 << Namespc->getDeclName();
3365 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3366 Namespc->setInvalidDecl();
3367 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003368 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003369 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003370 // This is the first "real" definition of the namespace "std", so update
3371 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003372 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003373 // We had already defined a dummy namespace "std". Link this new
3374 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003375 StdNS->setNextNamespace(Namespc);
3376 StdNS->setLocation(IdentLoc);
3377 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003378 }
3379
3380 // Make our StdNamespace cache point at the first real definition of the
3381 // "std" namespace.
3382 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003383 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003384
3385 PushOnScopeChains(Namespc, DeclRegionScope);
3386 } else {
John McCall4fa53422009-10-01 00:25:31 +00003387 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003388 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003389
3390 // Link the anonymous namespace into its parent.
3391 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003392 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003393 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3394 PrevDecl = TU->getAnonymousNamespace();
3395 TU->setAnonymousNamespace(Namespc);
3396 } else {
3397 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3398 PrevDecl = ND->getAnonymousNamespace();
3399 ND->setAnonymousNamespace(Namespc);
3400 }
3401
3402 // Link the anonymous namespace with its previous declaration.
3403 if (PrevDecl) {
3404 assert(PrevDecl->isAnonymousNamespace());
3405 assert(!PrevDecl->getNextNamespace());
3406 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3407 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003408
3409 if (Namespc->isInline() != PrevDecl->isInline()) {
3410 // inline-ness must match
3411 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3412 << Namespc->isInline();
3413 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3414 Namespc->setInvalidDecl();
3415 // Recover by ignoring the new namespace's inline status.
3416 Namespc->setInline(PrevDecl->isInline());
3417 }
John McCall0db42252009-12-16 02:06:49 +00003418 }
John McCall4fa53422009-10-01 00:25:31 +00003419
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003420 CurContext->addDecl(Namespc);
3421
John McCall4fa53422009-10-01 00:25:31 +00003422 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3423 // behaves as if it were replaced by
3424 // namespace unique { /* empty body */ }
3425 // using namespace unique;
3426 // namespace unique { namespace-body }
3427 // where all occurrences of 'unique' in a translation unit are
3428 // replaced by the same identifier and this identifier differs
3429 // from all other identifiers in the entire program.
3430
3431 // We just create the namespace with an empty name and then add an
3432 // implicit using declaration, just like the standard suggests.
3433 //
3434 // CodeGen enforces the "universally unique" aspect by giving all
3435 // declarations semantically contained within an anonymous
3436 // namespace internal linkage.
3437
John McCall0db42252009-12-16 02:06:49 +00003438 if (!PrevDecl) {
3439 UsingDirectiveDecl* UD
3440 = UsingDirectiveDecl::Create(Context, CurContext,
3441 /* 'using' */ LBrace,
3442 /* 'namespace' */ SourceLocation(),
3443 /* qualifier */ SourceRange(),
3444 /* NNS */ NULL,
3445 /* identifier */ SourceLocation(),
3446 Namespc,
3447 /* Ancestor */ CurContext);
3448 UD->setImplicit();
3449 CurContext->addDecl(UD);
3450 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003451 }
3452
3453 // Although we could have an invalid decl (i.e. the namespace name is a
3454 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003455 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3456 // for the namespace has the declarations that showed up in that particular
3457 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003458 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003459 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003460}
3461
Sebastian Redla6602e92009-11-23 15:34:23 +00003462/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3463/// is a namespace alias, returns the namespace it points to.
3464static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3465 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3466 return AD->getNamespace();
3467 return dyn_cast_or_null<NamespaceDecl>(D);
3468}
3469
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003470/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3471/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003472void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003473 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3474 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3475 Namespc->setRBracLoc(RBrace);
3476 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003477 if (Namespc->hasAttr<VisibilityAttr>())
3478 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003479}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003480
John McCall28a0cf72010-08-25 07:42:41 +00003481CXXRecordDecl *Sema::getStdBadAlloc() const {
3482 return cast_or_null<CXXRecordDecl>(
3483 StdBadAlloc.get(Context.getExternalSource()));
3484}
3485
3486NamespaceDecl *Sema::getStdNamespace() const {
3487 return cast_or_null<NamespaceDecl>(
3488 StdNamespace.get(Context.getExternalSource()));
3489}
3490
Douglas Gregorcdf87022010-06-29 17:53:46 +00003491/// \brief Retrieve the special "std" namespace, which may require us to
3492/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003493NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003494 if (!StdNamespace) {
3495 // The "std" namespace has not yet been defined, so build one implicitly.
3496 StdNamespace = NamespaceDecl::Create(Context,
3497 Context.getTranslationUnitDecl(),
3498 SourceLocation(),
3499 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003500 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003501 }
3502
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003503 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003504}
3505
John McCall48871652010-08-21 09:40:31 +00003506Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003507 SourceLocation UsingLoc,
3508 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003509 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003510 SourceLocation IdentLoc,
3511 IdentifierInfo *NamespcName,
3512 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003513 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3514 assert(NamespcName && "Invalid NamespcName.");
3515 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003516
3517 // This can only happen along a recovery path.
3518 while (S->getFlags() & Scope::TemplateParamScope)
3519 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003520 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003521
Douglas Gregor889ceb72009-02-03 19:21:40 +00003522 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003523 NestedNameSpecifier *Qualifier = 0;
3524 if (SS.isSet())
3525 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3526
Douglas Gregor34074322009-01-14 22:20:51 +00003527 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003528 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3529 LookupParsedName(R, S, &SS);
3530 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003531 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003532
Douglas Gregorcdf87022010-06-29 17:53:46 +00003533 if (R.empty()) {
3534 // Allow "using namespace std;" or "using namespace ::std;" even if
3535 // "std" hasn't been defined yet, for GCC compatibility.
3536 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3537 NamespcName->isStr("std")) {
3538 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003539 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003540 R.resolveKind();
3541 }
3542 // Otherwise, attempt typo correction.
3543 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3544 CTC_NoKeywords, 0)) {
3545 if (R.getAsSingle<NamespaceDecl>() ||
3546 R.getAsSingle<NamespaceAliasDecl>()) {
3547 if (DeclContext *DC = computeDeclContext(SS, false))
3548 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3549 << NamespcName << DC << Corrected << SS.getRange()
3550 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3551 else
3552 Diag(IdentLoc, diag::err_using_directive_suggest)
3553 << NamespcName << Corrected
3554 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3555 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3556 << Corrected;
3557
3558 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003559 } else {
3560 R.clear();
3561 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003562 }
3563 }
3564 }
3565
John McCall9f3059a2009-10-09 21:13:30 +00003566 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003567 NamedDecl *Named = R.getFoundDecl();
3568 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3569 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003570 // C++ [namespace.udir]p1:
3571 // A using-directive specifies that the names in the nominated
3572 // namespace can be used in the scope in which the
3573 // using-directive appears after the using-directive. During
3574 // unqualified name lookup (3.4.1), the names appear as if they
3575 // were declared in the nearest enclosing namespace which
3576 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003577 // namespace. [Note: in this context, "contains" means "contains
3578 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003579
3580 // Find enclosing context containing both using-directive and
3581 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003582 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003583 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3584 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3585 CommonAncestor = CommonAncestor->getParent();
3586
Sebastian Redla6602e92009-11-23 15:34:23 +00003587 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003588 SS.getRange(),
3589 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003590 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003591 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003592 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003593 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003594 }
3595
Douglas Gregor889ceb72009-02-03 19:21:40 +00003596 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003597 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003598}
3599
3600void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3601 // If scope has associated entity, then using directive is at namespace
3602 // or translation unit scope. We add UsingDirectiveDecls, into
3603 // it's lookup structure.
3604 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003605 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003606 else
3607 // Otherwise it is block-sope. using-directives will affect lookup
3608 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003609 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003610}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003611
Douglas Gregorfec52632009-06-20 00:51:54 +00003612
John McCall48871652010-08-21 09:40:31 +00003613Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003614 AccessSpecifier AS,
3615 bool HasUsingKeyword,
3616 SourceLocation UsingLoc,
3617 CXXScopeSpec &SS,
3618 UnqualifiedId &Name,
3619 AttributeList *AttrList,
3620 bool IsTypeName,
3621 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003622 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003623
Douglas Gregor220f4272009-11-04 16:30:06 +00003624 switch (Name.getKind()) {
3625 case UnqualifiedId::IK_Identifier:
3626 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003627 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003628 case UnqualifiedId::IK_ConversionFunctionId:
3629 break;
3630
3631 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003632 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003633 // C++0x inherited constructors.
3634 if (getLangOptions().CPlusPlus0x) break;
3635
Douglas Gregor220f4272009-11-04 16:30:06 +00003636 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3637 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003638 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003639
3640 case UnqualifiedId::IK_DestructorName:
3641 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3642 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003643 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003644
3645 case UnqualifiedId::IK_TemplateId:
3646 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3647 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003648 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003649 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003650
3651 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3652 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003653 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003654 return 0;
John McCall3969e302009-12-08 07:46:18 +00003655
John McCalla0097262009-12-11 02:10:03 +00003656 // Warn about using declarations.
3657 // TODO: store that the declaration was written without 'using' and
3658 // talk about access decls instead of using decls in the
3659 // diagnostics.
3660 if (!HasUsingKeyword) {
3661 UsingLoc = Name.getSourceRange().getBegin();
3662
3663 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003664 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003665 }
3666
Douglas Gregorc4356532010-12-16 00:46:58 +00003667 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3668 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3669 return 0;
3670
John McCall3f746822009-11-17 05:59:44 +00003671 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003672 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003673 /* IsInstantiation */ false,
3674 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003675 if (UD)
3676 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003677
John McCall48871652010-08-21 09:40:31 +00003678 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003679}
3680
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003681/// \brief Determine whether a using declaration considers the given
3682/// declarations as "equivalent", e.g., if they are redeclarations of
3683/// the same entity or are both typedefs of the same type.
3684static bool
3685IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3686 bool &SuppressRedeclaration) {
3687 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3688 SuppressRedeclaration = false;
3689 return true;
3690 }
3691
3692 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3693 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3694 SuppressRedeclaration = true;
3695 return Context.hasSameType(TD1->getUnderlyingType(),
3696 TD2->getUnderlyingType());
3697 }
3698
3699 return false;
3700}
3701
3702
John McCall84d87672009-12-10 09:41:52 +00003703/// Determines whether to create a using shadow decl for a particular
3704/// decl, given the set of decls existing prior to this using lookup.
3705bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3706 const LookupResult &Previous) {
3707 // Diagnose finding a decl which is not from a base class of the
3708 // current class. We do this now because there are cases where this
3709 // function will silently decide not to build a shadow decl, which
3710 // will pre-empt further diagnostics.
3711 //
3712 // We don't need to do this in C++0x because we do the check once on
3713 // the qualifier.
3714 //
3715 // FIXME: diagnose the following if we care enough:
3716 // struct A { int foo; };
3717 // struct B : A { using A::foo; };
3718 // template <class T> struct C : A {};
3719 // template <class T> struct D : C<T> { using B::foo; } // <---
3720 // This is invalid (during instantiation) in C++03 because B::foo
3721 // resolves to the using decl in B, which is not a base class of D<T>.
3722 // We can't diagnose it immediately because C<T> is an unknown
3723 // specialization. The UsingShadowDecl in D<T> then points directly
3724 // to A::foo, which will look well-formed when we instantiate.
3725 // The right solution is to not collapse the shadow-decl chain.
3726 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3727 DeclContext *OrigDC = Orig->getDeclContext();
3728
3729 // Handle enums and anonymous structs.
3730 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3731 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3732 while (OrigRec->isAnonymousStructOrUnion())
3733 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3734
3735 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3736 if (OrigDC == CurContext) {
3737 Diag(Using->getLocation(),
3738 diag::err_using_decl_nested_name_specifier_is_current_class)
3739 << Using->getNestedNameRange();
3740 Diag(Orig->getLocation(), diag::note_using_decl_target);
3741 return true;
3742 }
3743
3744 Diag(Using->getNestedNameRange().getBegin(),
3745 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3746 << Using->getTargetNestedNameDecl()
3747 << cast<CXXRecordDecl>(CurContext)
3748 << Using->getNestedNameRange();
3749 Diag(Orig->getLocation(), diag::note_using_decl_target);
3750 return true;
3751 }
3752 }
3753
3754 if (Previous.empty()) return false;
3755
3756 NamedDecl *Target = Orig;
3757 if (isa<UsingShadowDecl>(Target))
3758 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3759
John McCalla17e83e2009-12-11 02:33:26 +00003760 // If the target happens to be one of the previous declarations, we
3761 // don't have a conflict.
3762 //
3763 // FIXME: but we might be increasing its access, in which case we
3764 // should redeclare it.
3765 NamedDecl *NonTag = 0, *Tag = 0;
3766 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3767 I != E; ++I) {
3768 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003769 bool Result;
3770 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3771 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003772
3773 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3774 }
3775
John McCall84d87672009-12-10 09:41:52 +00003776 if (Target->isFunctionOrFunctionTemplate()) {
3777 FunctionDecl *FD;
3778 if (isa<FunctionTemplateDecl>(Target))
3779 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3780 else
3781 FD = cast<FunctionDecl>(Target);
3782
3783 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003784 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003785 case Ovl_Overload:
3786 return false;
3787
3788 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003789 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003790 break;
3791
3792 // We found a decl with the exact signature.
3793 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003794 // If we're in a record, we want to hide the target, so we
3795 // return true (without a diagnostic) to tell the caller not to
3796 // build a shadow decl.
3797 if (CurContext->isRecord())
3798 return true;
3799
3800 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003801 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003802 break;
3803 }
3804
3805 Diag(Target->getLocation(), diag::note_using_decl_target);
3806 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3807 return true;
3808 }
3809
3810 // Target is not a function.
3811
John McCall84d87672009-12-10 09:41:52 +00003812 if (isa<TagDecl>(Target)) {
3813 // No conflict between a tag and a non-tag.
3814 if (!Tag) return false;
3815
John McCalle29c5cd2009-12-10 19:51:03 +00003816 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003817 Diag(Target->getLocation(), diag::note_using_decl_target);
3818 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3819 return true;
3820 }
3821
3822 // No conflict between a tag and a non-tag.
3823 if (!NonTag) return false;
3824
John McCalle29c5cd2009-12-10 19:51:03 +00003825 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003826 Diag(Target->getLocation(), diag::note_using_decl_target);
3827 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3828 return true;
3829}
3830
John McCall3f746822009-11-17 05:59:44 +00003831/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003832UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003833 UsingDecl *UD,
3834 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003835
3836 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003837 NamedDecl *Target = Orig;
3838 if (isa<UsingShadowDecl>(Target)) {
3839 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3840 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003841 }
3842
3843 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003844 = UsingShadowDecl::Create(Context, CurContext,
3845 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003846 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003847
3848 Shadow->setAccess(UD->getAccess());
3849 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3850 Shadow->setInvalidDecl();
3851
John McCall3f746822009-11-17 05:59:44 +00003852 if (S)
John McCall3969e302009-12-08 07:46:18 +00003853 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003854 else
John McCall3969e302009-12-08 07:46:18 +00003855 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003856
John McCall3969e302009-12-08 07:46:18 +00003857
John McCall84d87672009-12-10 09:41:52 +00003858 return Shadow;
3859}
John McCall3969e302009-12-08 07:46:18 +00003860
John McCall84d87672009-12-10 09:41:52 +00003861/// Hides a using shadow declaration. This is required by the current
3862/// using-decl implementation when a resolvable using declaration in a
3863/// class is followed by a declaration which would hide or override
3864/// one or more of the using decl's targets; for example:
3865///
3866/// struct Base { void foo(int); };
3867/// struct Derived : Base {
3868/// using Base::foo;
3869/// void foo(int);
3870/// };
3871///
3872/// The governing language is C++03 [namespace.udecl]p12:
3873///
3874/// When a using-declaration brings names from a base class into a
3875/// derived class scope, member functions in the derived class
3876/// override and/or hide member functions with the same name and
3877/// parameter types in a base class (rather than conflicting).
3878///
3879/// There are two ways to implement this:
3880/// (1) optimistically create shadow decls when they're not hidden
3881/// by existing declarations, or
3882/// (2) don't create any shadow decls (or at least don't make them
3883/// visible) until we've fully parsed/instantiated the class.
3884/// The problem with (1) is that we might have to retroactively remove
3885/// a shadow decl, which requires several O(n) operations because the
3886/// decl structures are (very reasonably) not designed for removal.
3887/// (2) avoids this but is very fiddly and phase-dependent.
3888void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003889 if (Shadow->getDeclName().getNameKind() ==
3890 DeclarationName::CXXConversionFunctionName)
3891 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3892
John McCall84d87672009-12-10 09:41:52 +00003893 // Remove it from the DeclContext...
3894 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003895
John McCall84d87672009-12-10 09:41:52 +00003896 // ...and the scope, if applicable...
3897 if (S) {
John McCall48871652010-08-21 09:40:31 +00003898 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003899 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003900 }
3901
John McCall84d87672009-12-10 09:41:52 +00003902 // ...and the using decl.
3903 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3904
3905 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003906 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003907}
3908
John McCalle61f2ba2009-11-18 02:36:19 +00003909/// Builds a using declaration.
3910///
3911/// \param IsInstantiation - Whether this call arises from an
3912/// instantiation of an unresolved using declaration. We treat
3913/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003914NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3915 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003916 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003917 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003918 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003919 bool IsInstantiation,
3920 bool IsTypeName,
3921 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003922 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003923 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003924 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003925
Anders Carlssonf038fc22009-08-28 05:49:21 +00003926 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00003927
Anders Carlsson59140b32009-08-28 03:16:11 +00003928 if (SS.isEmpty()) {
3929 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003930 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003931 }
Mike Stump11289f42009-09-09 15:08:12 +00003932
John McCall84d87672009-12-10 09:41:52 +00003933 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003934 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003935 ForRedeclaration);
3936 Previous.setHideTags(false);
3937 if (S) {
3938 LookupName(Previous, S);
3939
3940 // It is really dumb that we have to do this.
3941 LookupResult::Filter F = Previous.makeFilter();
3942 while (F.hasNext()) {
3943 NamedDecl *D = F.next();
3944 if (!isDeclInScope(D, CurContext, S))
3945 F.erase();
3946 }
3947 F.done();
3948 } else {
3949 assert(IsInstantiation && "no scope in non-instantiation");
3950 assert(CurContext->isRecord() && "scope not record in instantiation");
3951 LookupQualifiedName(Previous, CurContext);
3952 }
3953
Mike Stump11289f42009-09-09 15:08:12 +00003954 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003955 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3956
John McCall84d87672009-12-10 09:41:52 +00003957 // Check for invalid redeclarations.
3958 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3959 return 0;
3960
3961 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003962 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3963 return 0;
3964
John McCall84c16cf2009-11-12 03:15:40 +00003965 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003966 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003967 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003968 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003969 // FIXME: not all declaration name kinds are legal here
3970 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3971 UsingLoc, TypenameLoc,
3972 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003973 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003974 } else {
3975 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003976 UsingLoc, SS.getRange(),
3977 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003978 }
John McCallb96ec562009-12-04 22:46:56 +00003979 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003980 D = UsingDecl::Create(Context, CurContext,
3981 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003982 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003983 }
John McCallb96ec562009-12-04 22:46:56 +00003984 D->setAccess(AS);
3985 CurContext->addDecl(D);
3986
3987 if (!LookupContext) return D;
3988 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003989
John McCall0b66eb32010-05-01 00:40:08 +00003990 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003991 UD->setInvalidDecl();
3992 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003993 }
3994
John McCall3969e302009-12-08 07:46:18 +00003995 // Look up the target name.
3996
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003997 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003998
John McCall3969e302009-12-08 07:46:18 +00003999 // Unlike most lookups, we don't always want to hide tag
4000 // declarations: tag names are visible through the using declaration
4001 // even if hidden by ordinary names, *except* in a dependent context
4002 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004003 if (!IsInstantiation)
4004 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004005
John McCall27b18f82009-11-17 02:14:36 +00004006 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004007
John McCall9f3059a2009-10-09 21:13:30 +00004008 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004009 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004010 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004011 UD->setInvalidDecl();
4012 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004013 }
4014
John McCallb96ec562009-12-04 22:46:56 +00004015 if (R.isAmbiguous()) {
4016 UD->setInvalidDecl();
4017 return UD;
4018 }
Mike Stump11289f42009-09-09 15:08:12 +00004019
John McCalle61f2ba2009-11-18 02:36:19 +00004020 if (IsTypeName) {
4021 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004022 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004023 Diag(IdentLoc, diag::err_using_typename_non_type);
4024 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4025 Diag((*I)->getUnderlyingDecl()->getLocation(),
4026 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004027 UD->setInvalidDecl();
4028 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004029 }
4030 } else {
4031 // If we asked for a non-typename and we got a type, error out,
4032 // but only if this is an instantiation of an unresolved using
4033 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004034 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004035 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4036 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004037 UD->setInvalidDecl();
4038 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004039 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004040 }
4041
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004042 // C++0x N2914 [namespace.udecl]p6:
4043 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004044 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004045 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4046 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004047 UD->setInvalidDecl();
4048 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004049 }
Mike Stump11289f42009-09-09 15:08:12 +00004050
John McCall84d87672009-12-10 09:41:52 +00004051 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4052 if (!CheckUsingShadowDecl(UD, *I, Previous))
4053 BuildUsingShadowDecl(S, UD, *I);
4054 }
John McCall3f746822009-11-17 05:59:44 +00004055
4056 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004057}
4058
John McCall84d87672009-12-10 09:41:52 +00004059/// Checks that the given using declaration is not an invalid
4060/// redeclaration. Note that this is checking only for the using decl
4061/// itself, not for any ill-formedness among the UsingShadowDecls.
4062bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4063 bool isTypeName,
4064 const CXXScopeSpec &SS,
4065 SourceLocation NameLoc,
4066 const LookupResult &Prev) {
4067 // C++03 [namespace.udecl]p8:
4068 // C++0x [namespace.udecl]p10:
4069 // A using-declaration is a declaration and can therefore be used
4070 // repeatedly where (and only where) multiple declarations are
4071 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004072 //
John McCall032092f2010-11-29 18:01:58 +00004073 // That's in non-member contexts.
4074 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004075 return false;
4076
4077 NestedNameSpecifier *Qual
4078 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4079
4080 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4081 NamedDecl *D = *I;
4082
4083 bool DTypename;
4084 NestedNameSpecifier *DQual;
4085 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4086 DTypename = UD->isTypeName();
4087 DQual = UD->getTargetNestedNameDecl();
4088 } else if (UnresolvedUsingValueDecl *UD
4089 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4090 DTypename = false;
4091 DQual = UD->getTargetNestedNameSpecifier();
4092 } else if (UnresolvedUsingTypenameDecl *UD
4093 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4094 DTypename = true;
4095 DQual = UD->getTargetNestedNameSpecifier();
4096 } else continue;
4097
4098 // using decls differ if one says 'typename' and the other doesn't.
4099 // FIXME: non-dependent using decls?
4100 if (isTypeName != DTypename) continue;
4101
4102 // using decls differ if they name different scopes (but note that
4103 // template instantiation can cause this check to trigger when it
4104 // didn't before instantiation).
4105 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4106 Context.getCanonicalNestedNameSpecifier(DQual))
4107 continue;
4108
4109 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004110 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004111 return true;
4112 }
4113
4114 return false;
4115}
4116
John McCall3969e302009-12-08 07:46:18 +00004117
John McCallb96ec562009-12-04 22:46:56 +00004118/// Checks that the given nested-name qualifier used in a using decl
4119/// in the current context is appropriately related to the current
4120/// scope. If an error is found, diagnoses it and returns true.
4121bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4122 const CXXScopeSpec &SS,
4123 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004124 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004125
John McCall3969e302009-12-08 07:46:18 +00004126 if (!CurContext->isRecord()) {
4127 // C++03 [namespace.udecl]p3:
4128 // C++0x [namespace.udecl]p8:
4129 // A using-declaration for a class member shall be a member-declaration.
4130
4131 // If we weren't able to compute a valid scope, it must be a
4132 // dependent class scope.
4133 if (!NamedContext || NamedContext->isRecord()) {
4134 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4135 << SS.getRange();
4136 return true;
4137 }
4138
4139 // Otherwise, everything is known to be fine.
4140 return false;
4141 }
4142
4143 // The current scope is a record.
4144
4145 // If the named context is dependent, we can't decide much.
4146 if (!NamedContext) {
4147 // FIXME: in C++0x, we can diagnose if we can prove that the
4148 // nested-name-specifier does not refer to a base class, which is
4149 // still possible in some cases.
4150
4151 // Otherwise we have to conservatively report that things might be
4152 // okay.
4153 return false;
4154 }
4155
4156 if (!NamedContext->isRecord()) {
4157 // Ideally this would point at the last name in the specifier,
4158 // but we don't have that level of source info.
4159 Diag(SS.getRange().getBegin(),
4160 diag::err_using_decl_nested_name_specifier_is_not_class)
4161 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4162 return true;
4163 }
4164
Douglas Gregor7c842292010-12-21 07:41:49 +00004165 if (!NamedContext->isDependentContext() &&
4166 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4167 return true;
4168
John McCall3969e302009-12-08 07:46:18 +00004169 if (getLangOptions().CPlusPlus0x) {
4170 // C++0x [namespace.udecl]p3:
4171 // In a using-declaration used as a member-declaration, the
4172 // nested-name-specifier shall name a base class of the class
4173 // being defined.
4174
4175 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4176 cast<CXXRecordDecl>(NamedContext))) {
4177 if (CurContext == NamedContext) {
4178 Diag(NameLoc,
4179 diag::err_using_decl_nested_name_specifier_is_current_class)
4180 << SS.getRange();
4181 return true;
4182 }
4183
4184 Diag(SS.getRange().getBegin(),
4185 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4186 << (NestedNameSpecifier*) SS.getScopeRep()
4187 << cast<CXXRecordDecl>(CurContext)
4188 << SS.getRange();
4189 return true;
4190 }
4191
4192 return false;
4193 }
4194
4195 // C++03 [namespace.udecl]p4:
4196 // A using-declaration used as a member-declaration shall refer
4197 // to a member of a base class of the class being defined [etc.].
4198
4199 // Salient point: SS doesn't have to name a base class as long as
4200 // lookup only finds members from base classes. Therefore we can
4201 // diagnose here only if we can prove that that can't happen,
4202 // i.e. if the class hierarchies provably don't intersect.
4203
4204 // TODO: it would be nice if "definitely valid" results were cached
4205 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4206 // need to be repeated.
4207
4208 struct UserData {
4209 llvm::DenseSet<const CXXRecordDecl*> Bases;
4210
4211 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4212 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4213 Data->Bases.insert(Base);
4214 return true;
4215 }
4216
4217 bool hasDependentBases(const CXXRecordDecl *Class) {
4218 return !Class->forallBases(collect, this);
4219 }
4220
4221 /// Returns true if the base is dependent or is one of the
4222 /// accumulated base classes.
4223 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4224 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4225 return !Data->Bases.count(Base);
4226 }
4227
4228 bool mightShareBases(const CXXRecordDecl *Class) {
4229 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4230 }
4231 };
4232
4233 UserData Data;
4234
4235 // Returns false if we find a dependent base.
4236 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4237 return false;
4238
4239 // Returns false if the class has a dependent base or if it or one
4240 // of its bases is present in the base set of the current context.
4241 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4242 return false;
4243
4244 Diag(SS.getRange().getBegin(),
4245 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4246 << (NestedNameSpecifier*) SS.getScopeRep()
4247 << cast<CXXRecordDecl>(CurContext)
4248 << SS.getRange();
4249
4250 return true;
John McCallb96ec562009-12-04 22:46:56 +00004251}
4252
John McCall48871652010-08-21 09:40:31 +00004253Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004254 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004255 SourceLocation AliasLoc,
4256 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004257 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004258 SourceLocation IdentLoc,
4259 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004260
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004261 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004262 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4263 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004264
Anders Carlssondca83c42009-03-28 06:23:46 +00004265 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004266 NamedDecl *PrevDecl
4267 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4268 ForRedeclaration);
4269 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4270 PrevDecl = 0;
4271
4272 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004273 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004274 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004275 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004276 // FIXME: At some point, we'll want to create the (redundant)
4277 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004278 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004279 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004280 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004281 }
Mike Stump11289f42009-09-09 15:08:12 +00004282
Anders Carlssondca83c42009-03-28 06:23:46 +00004283 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4284 diag::err_redefinition_different_kind;
4285 Diag(AliasLoc, DiagID) << Alias;
4286 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004287 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004288 }
4289
John McCall27b18f82009-11-17 02:14:36 +00004290 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004291 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004292
John McCall9f3059a2009-10-09 21:13:30 +00004293 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004294 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4295 CTC_NoKeywords, 0)) {
4296 if (R.getAsSingle<NamespaceDecl>() ||
4297 R.getAsSingle<NamespaceAliasDecl>()) {
4298 if (DeclContext *DC = computeDeclContext(SS, false))
4299 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4300 << Ident << DC << Corrected << SS.getRange()
4301 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4302 else
4303 Diag(IdentLoc, diag::err_using_directive_suggest)
4304 << Ident << Corrected
4305 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4306
4307 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4308 << Corrected;
4309
4310 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004311 } else {
4312 R.clear();
4313 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004314 }
4315 }
4316
4317 if (R.empty()) {
4318 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004319 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004320 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004321 }
Mike Stump11289f42009-09-09 15:08:12 +00004322
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004323 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004324 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4325 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004326 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004327 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004328
John McCalld8d0d432010-02-16 06:53:13 +00004329 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004330 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004331}
4332
Douglas Gregora57478e2010-05-01 15:04:51 +00004333namespace {
4334 /// \brief Scoped object used to handle the state changes required in Sema
4335 /// to implicitly define the body of a C++ member function;
4336 class ImplicitlyDefinedFunctionScope {
4337 Sema &S;
4338 DeclContext *PreviousContext;
4339
4340 public:
4341 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4342 : S(S), PreviousContext(S.CurContext)
4343 {
4344 S.CurContext = Method;
4345 S.PushFunctionScope();
4346 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4347 }
4348
4349 ~ImplicitlyDefinedFunctionScope() {
4350 S.PopExpressionEvaluationContext();
4351 S.PopFunctionOrBlockScope();
4352 S.CurContext = PreviousContext;
4353 }
4354 };
4355}
4356
Sebastian Redlc15c3262010-09-13 22:02:47 +00004357static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4358 CXXRecordDecl *D) {
4359 ASTContext &Context = Self.Context;
4360 QualType ClassType = Context.getTypeDeclType(D);
4361 DeclarationName ConstructorName
4362 = Context.DeclarationNames.getCXXConstructorName(
4363 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4364
4365 DeclContext::lookup_const_iterator Con, ConEnd;
4366 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4367 Con != ConEnd; ++Con) {
4368 // FIXME: In C++0x, a constructor template can be a default constructor.
4369 if (isa<FunctionTemplateDecl>(*Con))
4370 continue;
4371
4372 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4373 if (Constructor->isDefaultConstructor())
4374 return Constructor;
4375 }
4376 return 0;
4377}
4378
Douglas Gregor0be31a22010-07-02 17:43:08 +00004379CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4380 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004381 // C++ [class.ctor]p5:
4382 // A default constructor for a class X is a constructor of class X
4383 // that can be called without an argument. If there is no
4384 // user-declared constructor for class X, a default constructor is
4385 // implicitly declared. An implicitly-declared default constructor
4386 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004387 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4388 "Should not build implicit default constructor!");
4389
Douglas Gregor6d880b12010-07-01 22:31:05 +00004390 // C++ [except.spec]p14:
4391 // An implicitly declared special member function (Clause 12) shall have an
4392 // exception-specification. [...]
4393 ImplicitExceptionSpecification ExceptSpec(Context);
4394
4395 // Direct base-class destructors.
4396 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4397 BEnd = ClassDecl->bases_end();
4398 B != BEnd; ++B) {
4399 if (B->isVirtual()) // Handled below.
4400 continue;
4401
Douglas Gregor9672f922010-07-03 00:47:00 +00004402 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4403 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4404 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4405 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004406 else if (CXXConstructorDecl *Constructor
4407 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004408 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004409 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004410 }
4411
4412 // Virtual base-class destructors.
4413 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4414 BEnd = ClassDecl->vbases_end();
4415 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004416 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4417 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4418 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4419 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4420 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004421 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004422 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004423 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004424 }
4425
4426 // Field destructors.
4427 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4428 FEnd = ClassDecl->field_end();
4429 F != FEnd; ++F) {
4430 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004431 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4432 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4433 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4434 ExceptSpec.CalledDecl(
4435 DeclareImplicitDefaultConstructor(FieldClassDecl));
4436 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004437 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004438 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004439 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004440 }
John McCalldb40c7f2010-12-14 08:05:40 +00004441
4442 FunctionProtoType::ExtProtoInfo EPI;
4443 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4444 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4445 EPI.NumExceptions = ExceptSpec.size();
4446 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004447
4448 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004449 CanQualType ClassType
4450 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4451 DeclarationName Name
4452 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004453 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004454 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004455 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004456 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004457 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004458 /*TInfo=*/0,
4459 /*isExplicit=*/false,
4460 /*isInline=*/true,
4461 /*isImplicitlyDeclared=*/true);
4462 DefaultCon->setAccess(AS_public);
4463 DefaultCon->setImplicit();
4464 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004465
4466 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004467 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4468
Douglas Gregor0be31a22010-07-02 17:43:08 +00004469 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004470 PushOnScopeChains(DefaultCon, S, false);
4471 ClassDecl->addDecl(DefaultCon);
4472
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004473 return DefaultCon;
4474}
4475
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004476void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4477 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004478 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004479 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004480 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004481
Anders Carlsson423f5d82010-04-23 16:04:08 +00004482 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004483 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004484
Douglas Gregora57478e2010-05-01 15:04:51 +00004485 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004486 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004487 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004488 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004489 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004490 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004491 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004492 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004493 }
Douglas Gregor73193272010-09-20 16:48:21 +00004494
4495 SourceLocation Loc = Constructor->getLocation();
4496 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4497
4498 Constructor->setUsed();
4499 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004500}
4501
Douglas Gregor0be31a22010-07-02 17:43:08 +00004502CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004503 // C++ [class.dtor]p2:
4504 // If a class has no user-declared destructor, a destructor is
4505 // declared implicitly. An implicitly-declared destructor is an
4506 // inline public member of its class.
4507
4508 // C++ [except.spec]p14:
4509 // An implicitly declared special member function (Clause 12) shall have
4510 // an exception-specification.
4511 ImplicitExceptionSpecification ExceptSpec(Context);
4512
4513 // Direct base-class destructors.
4514 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4515 BEnd = ClassDecl->bases_end();
4516 B != BEnd; ++B) {
4517 if (B->isVirtual()) // Handled below.
4518 continue;
4519
4520 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4521 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004522 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004523 }
4524
4525 // Virtual base-class destructors.
4526 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4527 BEnd = ClassDecl->vbases_end();
4528 B != BEnd; ++B) {
4529 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4530 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004531 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004532 }
4533
4534 // Field destructors.
4535 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4536 FEnd = ClassDecl->field_end();
4537 F != FEnd; ++F) {
4538 if (const RecordType *RecordTy
4539 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4540 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004541 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004542 }
4543
Douglas Gregor7454c562010-07-02 20:37:36 +00004544 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004545 FunctionProtoType::ExtProtoInfo EPI;
4546 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4547 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4548 EPI.NumExceptions = ExceptSpec.size();
4549 EPI.Exceptions = ExceptSpec.data();
4550 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004551
4552 CanQualType ClassType
4553 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4554 DeclarationName Name
4555 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004556 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004557 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004558 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004559 /*isInline=*/true,
4560 /*isImplicitlyDeclared=*/true);
4561 Destructor->setAccess(AS_public);
4562 Destructor->setImplicit();
4563 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004564
4565 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004566 ++ASTContext::NumImplicitDestructorsDeclared;
4567
4568 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004569 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004570 PushOnScopeChains(Destructor, S, false);
4571 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004572
4573 // This could be uniqued if it ever proves significant.
4574 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4575
4576 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004577
Douglas Gregorf1203042010-07-01 19:09:28 +00004578 return Destructor;
4579}
4580
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004581void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004582 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004583 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004584 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004585 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004586 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004587
Douglas Gregor54818f02010-05-12 16:39:35 +00004588 if (Destructor->isInvalidDecl())
4589 return;
4590
Douglas Gregora57478e2010-05-01 15:04:51 +00004591 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004592
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004593 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004594 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4595 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004596
Douglas Gregor54818f02010-05-12 16:39:35 +00004597 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004598 Diag(CurrentLocation, diag::note_member_synthesized_at)
4599 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4600
4601 Destructor->setInvalidDecl();
4602 return;
4603 }
4604
Douglas Gregor73193272010-09-20 16:48:21 +00004605 SourceLocation Loc = Destructor->getLocation();
4606 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4607
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004608 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004609 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004610}
4611
Douglas Gregorb139cd52010-05-01 20:49:11 +00004612/// \brief Builds a statement that copies the given entity from \p From to
4613/// \c To.
4614///
4615/// This routine is used to copy the members of a class with an
4616/// implicitly-declared copy assignment operator. When the entities being
4617/// copied are arrays, this routine builds for loops to copy them.
4618///
4619/// \param S The Sema object used for type-checking.
4620///
4621/// \param Loc The location where the implicit copy is being generated.
4622///
4623/// \param T The type of the expressions being copied. Both expressions must
4624/// have this type.
4625///
4626/// \param To The expression we are copying to.
4627///
4628/// \param From The expression we are copying from.
4629///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004630/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4631/// Otherwise, it's a non-static member subobject.
4632///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004633/// \param Depth Internal parameter recording the depth of the recursion.
4634///
4635/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004636static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004637BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004638 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004639 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004640 // C++0x [class.copy]p30:
4641 // Each subobject is assigned in the manner appropriate to its type:
4642 //
4643 // - if the subobject is of class type, the copy assignment operator
4644 // for the class is used (as if by explicit qualification; that is,
4645 // ignoring any possible virtual overriding functions in more derived
4646 // classes);
4647 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4648 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4649
4650 // Look for operator=.
4651 DeclarationName Name
4652 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4653 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4654 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4655
4656 // Filter out any result that isn't a copy-assignment operator.
4657 LookupResult::Filter F = OpLookup.makeFilter();
4658 while (F.hasNext()) {
4659 NamedDecl *D = F.next();
4660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4661 if (Method->isCopyAssignmentOperator())
4662 continue;
4663
4664 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004665 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004666 F.done();
4667
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004668 // Suppress the protected check (C++ [class.protected]) for each of the
4669 // assignment operators we found. This strange dance is required when
4670 // we're assigning via a base classes's copy-assignment operator. To
4671 // ensure that we're getting the right base class subobject (without
4672 // ambiguities), we need to cast "this" to that subobject type; to
4673 // ensure that we don't go through the virtual call mechanism, we need
4674 // to qualify the operator= name with the base class (see below). However,
4675 // this means that if the base class has a protected copy assignment
4676 // operator, the protected member access check will fail. So, we
4677 // rewrite "protected" access to "public" access in this case, since we
4678 // know by construction that we're calling from a derived class.
4679 if (CopyingBaseSubobject) {
4680 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4681 L != LEnd; ++L) {
4682 if (L.getAccess() == AS_protected)
4683 L.setAccess(AS_public);
4684 }
4685 }
4686
Douglas Gregorb139cd52010-05-01 20:49:11 +00004687 // Create the nested-name-specifier that will be used to qualify the
4688 // reference to operator=; this is required to suppress the virtual
4689 // call mechanism.
4690 CXXScopeSpec SS;
4691 SS.setRange(Loc);
4692 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4693 T.getTypePtr()));
4694
4695 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004696 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004697 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004698 /*FirstQualifierInScope=*/0, OpLookup,
4699 /*TemplateArgs=*/0,
4700 /*SuppressQualifierCheck=*/true);
4701 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004702 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004703
4704 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004705
John McCalldadc5752010-08-24 06:29:42 +00004706 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004707 OpEqualRef.takeAs<Expr>(),
4708 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004709 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004710 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004711
4712 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004713 }
John McCallab8c2732010-03-16 06:11:48 +00004714
Douglas Gregorb139cd52010-05-01 20:49:11 +00004715 // - if the subobject is of scalar type, the built-in assignment
4716 // operator is used.
4717 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4718 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004719 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004720 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004721 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004722
4723 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004724 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004725
4726 // - if the subobject is an array, each element is assigned, in the
4727 // manner appropriate to the element type;
4728
4729 // Construct a loop over the array bounds, e.g.,
4730 //
4731 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4732 //
4733 // that will copy each of the array elements.
4734 QualType SizeType = S.Context.getSizeType();
4735
4736 // Create the iteration variable.
4737 IdentifierInfo *IterationVarName = 0;
4738 {
4739 llvm::SmallString<8> Str;
4740 llvm::raw_svector_ostream OS(Str);
4741 OS << "__i" << Depth;
4742 IterationVarName = &S.Context.Idents.get(OS.str());
4743 }
4744 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4745 IterationVarName, SizeType,
4746 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004747 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004748
4749 // Initialize the iteration variable to zero.
4750 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004751 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004752
4753 // Create a reference to the iteration variable; we'll use this several
4754 // times throughout.
4755 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00004756 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004757 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4758
4759 // Create the DeclStmt that holds the iteration variable.
4760 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4761
4762 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00004763 llvm::APInt Upper
4764 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004765 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00004766 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00004767 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
4768 BO_NE, S.Context.BoolTy,
4769 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004770
4771 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004772 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00004773 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
4774 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004775
4776 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004777 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4778 IterationVarRef, Loc));
4779 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4780 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004781
4782 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00004783 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
4784 To, From, CopyingBaseSubobject,
4785 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004786 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004787 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004788
4789 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004790 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004791 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004792 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004793 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004794}
4795
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004796/// \brief Determine whether the given class has a copy assignment operator
4797/// that accepts a const-qualified argument.
4798static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4799 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4800
4801 if (!Class->hasDeclaredCopyAssignment())
4802 S.DeclareImplicitCopyAssignment(Class);
4803
4804 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4805 DeclarationName OpName
4806 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4807
4808 DeclContext::lookup_const_iterator Op, OpEnd;
4809 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4810 // C++ [class.copy]p9:
4811 // A user-declared copy assignment operator is a non-static non-template
4812 // member function of class X with exactly one parameter of type X, X&,
4813 // const X&, volatile X& or const volatile X&.
4814 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4815 if (!Method)
4816 continue;
4817
4818 if (Method->isStatic())
4819 continue;
4820 if (Method->getPrimaryTemplate())
4821 continue;
4822 const FunctionProtoType *FnType =
4823 Method->getType()->getAs<FunctionProtoType>();
4824 assert(FnType && "Overloaded operator has no prototype.");
4825 // Don't assert on this; an invalid decl might have been left in the AST.
4826 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4827 continue;
4828 bool AcceptsConst = true;
4829 QualType ArgType = FnType->getArgType(0);
4830 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4831 ArgType = Ref->getPointeeType();
4832 // Is it a non-const lvalue reference?
4833 if (!ArgType.isConstQualified())
4834 AcceptsConst = false;
4835 }
4836 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4837 continue;
4838
4839 // We have a single argument of type cv X or cv X&, i.e. we've found the
4840 // copy assignment operator. Return whether it accepts const arguments.
4841 return AcceptsConst;
4842 }
4843 assert(Class->isInvalidDecl() &&
4844 "No copy assignment operator declared in valid code.");
4845 return false;
4846}
4847
Douglas Gregor0be31a22010-07-02 17:43:08 +00004848CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004849 // Note: The following rules are largely analoguous to the copy
4850 // constructor rules. Note that virtual bases are not taken into account
4851 // for determining the argument type of the operator. Note also that
4852 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004853
4854
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004855 // C++ [class.copy]p10:
4856 // If the class definition does not explicitly declare a copy
4857 // assignment operator, one is declared implicitly.
4858 // The implicitly-defined copy assignment operator for a class X
4859 // will have the form
4860 //
4861 // X& X::operator=(const X&)
4862 //
4863 // if
4864 bool HasConstCopyAssignment = true;
4865
4866 // -- each direct base class B of X has a copy assignment operator
4867 // whose parameter is of type const B&, const volatile B& or B,
4868 // and
4869 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4870 BaseEnd = ClassDecl->bases_end();
4871 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4872 assert(!Base->getType()->isDependentType() &&
4873 "Cannot generate implicit members for class with dependent bases.");
4874 const CXXRecordDecl *BaseClassDecl
4875 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004876 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004877 }
4878
4879 // -- for all the nonstatic data members of X that are of a class
4880 // type M (or array thereof), each such class type has a copy
4881 // assignment operator whose parameter is of type const M&,
4882 // const volatile M& or M.
4883 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4884 FieldEnd = ClassDecl->field_end();
4885 HasConstCopyAssignment && Field != FieldEnd;
4886 ++Field) {
4887 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4888 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4889 const CXXRecordDecl *FieldClassDecl
4890 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004891 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004892 }
4893 }
4894
4895 // Otherwise, the implicitly declared copy assignment operator will
4896 // have the form
4897 //
4898 // X& X::operator=(X&)
4899 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4900 QualType RetType = Context.getLValueReferenceType(ArgType);
4901 if (HasConstCopyAssignment)
4902 ArgType = ArgType.withConst();
4903 ArgType = Context.getLValueReferenceType(ArgType);
4904
Douglas Gregor68e11362010-07-01 17:48:08 +00004905 // C++ [except.spec]p14:
4906 // An implicitly declared special member function (Clause 12) shall have an
4907 // exception-specification. [...]
4908 ImplicitExceptionSpecification ExceptSpec(Context);
4909 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4910 BaseEnd = ClassDecl->bases_end();
4911 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004912 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004913 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004914
4915 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4916 DeclareImplicitCopyAssignment(BaseClassDecl);
4917
Douglas Gregor68e11362010-07-01 17:48:08 +00004918 if (CXXMethodDecl *CopyAssign
4919 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4920 ExceptSpec.CalledDecl(CopyAssign);
4921 }
4922 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4923 FieldEnd = ClassDecl->field_end();
4924 Field != FieldEnd;
4925 ++Field) {
4926 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4927 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004928 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004929 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004930
4931 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4932 DeclareImplicitCopyAssignment(FieldClassDecl);
4933
Douglas Gregor68e11362010-07-01 17:48:08 +00004934 if (CXXMethodDecl *CopyAssign
4935 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4936 ExceptSpec.CalledDecl(CopyAssign);
4937 }
4938 }
4939
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004940 // An implicitly-declared copy assignment operator is an inline public
4941 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00004942 FunctionProtoType::ExtProtoInfo EPI;
4943 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4944 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4945 EPI.NumExceptions = ExceptSpec.size();
4946 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004947 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004948 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004949 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004950 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00004951 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004952 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004953 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004954 /*isInline=*/true);
4955 CopyAssignment->setAccess(AS_public);
4956 CopyAssignment->setImplicit();
4957 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004958
4959 // Add the parameter to the operator.
4960 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4961 ClassDecl->getLocation(),
4962 /*Id=*/0,
4963 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004964 SC_None,
4965 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004966 CopyAssignment->setParams(&FromParam, 1);
4967
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004968 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004969 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4970
Douglas Gregor0be31a22010-07-02 17:43:08 +00004971 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004972 PushOnScopeChains(CopyAssignment, S, false);
4973 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004974
4975 AddOverriddenMethods(ClassDecl, CopyAssignment);
4976 return CopyAssignment;
4977}
4978
Douglas Gregorb139cd52010-05-01 20:49:11 +00004979void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4980 CXXMethodDecl *CopyAssignOperator) {
4981 assert((CopyAssignOperator->isImplicit() &&
4982 CopyAssignOperator->isOverloadedOperator() &&
4983 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004984 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004985 "DefineImplicitCopyAssignment called for wrong function");
4986
4987 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4988
4989 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4990 CopyAssignOperator->setInvalidDecl();
4991 return;
4992 }
4993
4994 CopyAssignOperator->setUsed();
4995
4996 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004997 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004998
4999 // C++0x [class.copy]p30:
5000 // The implicitly-defined or explicitly-defaulted copy assignment operator
5001 // for a non-union class X performs memberwise copy assignment of its
5002 // subobjects. The direct base classes of X are assigned first, in the
5003 // order of their declaration in the base-specifier-list, and then the
5004 // immediate non-static data members of X are assigned, in the order in
5005 // which they were declared in the class definition.
5006
5007 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005008 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005009
5010 // The parameter for the "other" object, which we are copying from.
5011 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5012 Qualifiers OtherQuals = Other->getType().getQualifiers();
5013 QualType OtherRefType = Other->getType();
5014 if (const LValueReferenceType *OtherRef
5015 = OtherRefType->getAs<LValueReferenceType>()) {
5016 OtherRefType = OtherRef->getPointeeType();
5017 OtherQuals = OtherRefType.getQualifiers();
5018 }
5019
5020 // Our location for everything implicitly-generated.
5021 SourceLocation Loc = CopyAssignOperator->getLocation();
5022
5023 // Construct a reference to the "other" object. We'll be using this
5024 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005025 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005026 assert(OtherRef && "Reference to parameter cannot fail!");
5027
5028 // Construct the "this" pointer. We'll be using this throughout the generated
5029 // ASTs.
5030 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5031 assert(This && "Reference to this cannot fail!");
5032
5033 // Assign base classes.
5034 bool Invalid = false;
5035 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5036 E = ClassDecl->bases_end(); Base != E; ++Base) {
5037 // Form the assignment:
5038 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5039 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005040 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005041 Invalid = true;
5042 continue;
5043 }
5044
John McCallcf142162010-08-07 06:22:56 +00005045 CXXCastPath BasePath;
5046 BasePath.push_back(Base);
5047
Douglas Gregorb139cd52010-05-01 20:49:11 +00005048 // Construct the "from" expression, which is an implicit cast to the
5049 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005050 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005051 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005052 CK_UncheckedDerivedToBase,
5053 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005054
5055 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005056 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005057
5058 // Implicitly cast "this" to the appropriately-qualified base type.
5059 Expr *ToE = To.takeAs<Expr>();
5060 ImpCastExprToType(ToE,
5061 Context.getCVRQualifiedType(BaseType,
5062 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005063 CK_UncheckedDerivedToBase,
5064 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005065 To = Owned(ToE);
5066
5067 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005068 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005069 To.get(), From,
5070 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005071 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005072 Diag(CurrentLocation, diag::note_member_synthesized_at)
5073 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5074 CopyAssignOperator->setInvalidDecl();
5075 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005076 }
5077
5078 // Success! Record the copy.
5079 Statements.push_back(Copy.takeAs<Expr>());
5080 }
5081
5082 // \brief Reference to the __builtin_memcpy function.
5083 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005084 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005085 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005086
5087 // Assign non-static members.
5088 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5089 FieldEnd = ClassDecl->field_end();
5090 Field != FieldEnd; ++Field) {
5091 // Check for members of reference type; we can't copy those.
5092 if (Field->getType()->isReferenceType()) {
5093 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5094 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5095 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005096 Diag(CurrentLocation, diag::note_member_synthesized_at)
5097 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005098 Invalid = true;
5099 continue;
5100 }
5101
5102 // Check for members of const-qualified, non-class type.
5103 QualType BaseType = Context.getBaseElementType(Field->getType());
5104 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5105 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5106 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5107 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005108 Diag(CurrentLocation, diag::note_member_synthesized_at)
5109 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005110 Invalid = true;
5111 continue;
5112 }
5113
5114 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005115 if (FieldType->isIncompleteArrayType()) {
5116 assert(ClassDecl->hasFlexibleArrayMember() &&
5117 "Incomplete array type is not valid");
5118 continue;
5119 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005120
5121 // Build references to the field in the object we're copying from and to.
5122 CXXScopeSpec SS; // Intentionally empty
5123 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5124 LookupMemberName);
5125 MemberLookup.addDecl(*Field);
5126 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005127 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005128 Loc, /*IsArrow=*/false,
5129 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005130 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005131 Loc, /*IsArrow=*/true,
5132 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005133 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5134 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5135
5136 // If the field should be copied with __builtin_memcpy rather than via
5137 // explicit assignments, do so. This optimization only applies for arrays
5138 // of scalars and arrays of class type with trivial copy-assignment
5139 // operators.
5140 if (FieldType->isArrayType() &&
5141 (!BaseType->isRecordType() ||
5142 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5143 ->hasTrivialCopyAssignment())) {
5144 // Compute the size of the memory buffer to be copied.
5145 QualType SizeType = Context.getSizeType();
5146 llvm::APInt Size(Context.getTypeSize(SizeType),
5147 Context.getTypeSizeInChars(BaseType).getQuantity());
5148 for (const ConstantArrayType *Array
5149 = Context.getAsConstantArrayType(FieldType);
5150 Array;
5151 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005152 llvm::APInt ArraySize
5153 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005154 Size *= ArraySize;
5155 }
5156
5157 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005158 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5159 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005160
5161 bool NeedsCollectableMemCpy =
5162 (BaseType->isRecordType() &&
5163 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5164
5165 if (NeedsCollectableMemCpy) {
5166 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005167 // Create a reference to the __builtin_objc_memmove_collectable function.
5168 LookupResult R(*this,
5169 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005170 Loc, LookupOrdinaryName);
5171 LookupName(R, TUScope, true);
5172
5173 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5174 if (!CollectableMemCpy) {
5175 // Something went horribly wrong earlier, and we will have
5176 // complained about it.
5177 Invalid = true;
5178 continue;
5179 }
5180
5181 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5182 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005183 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005184 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5185 }
5186 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005187 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005188 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005189 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5190 LookupOrdinaryName);
5191 LookupName(R, TUScope, true);
5192
5193 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5194 if (!BuiltinMemCpy) {
5195 // Something went horribly wrong earlier, and we will have complained
5196 // about it.
5197 Invalid = true;
5198 continue;
5199 }
5200
5201 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5202 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005203 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005204 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5205 }
5206
John McCall37ad5512010-08-23 06:44:23 +00005207 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005208 CallArgs.push_back(To.takeAs<Expr>());
5209 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005210 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005211 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005212 if (NeedsCollectableMemCpy)
5213 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005214 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005215 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005216 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005217 else
5218 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005219 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005220 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005221 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005222
Douglas Gregorb139cd52010-05-01 20:49:11 +00005223 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5224 Statements.push_back(Call.takeAs<Expr>());
5225 continue;
5226 }
5227
5228 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005229 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005230 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005231 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005232 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005233 Diag(CurrentLocation, diag::note_member_synthesized_at)
5234 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5235 CopyAssignOperator->setInvalidDecl();
5236 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005237 }
5238
5239 // Success! Record the copy.
5240 Statements.push_back(Copy.takeAs<Stmt>());
5241 }
5242
5243 if (!Invalid) {
5244 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005245 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005246
John McCalldadc5752010-08-24 06:29:42 +00005247 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005248 if (Return.isInvalid())
5249 Invalid = true;
5250 else {
5251 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005252
5253 if (Trap.hasErrorOccurred()) {
5254 Diag(CurrentLocation, diag::note_member_synthesized_at)
5255 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5256 Invalid = true;
5257 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005258 }
5259 }
5260
5261 if (Invalid) {
5262 CopyAssignOperator->setInvalidDecl();
5263 return;
5264 }
5265
John McCalldadc5752010-08-24 06:29:42 +00005266 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005267 /*isStmtExpr=*/false);
5268 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5269 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005270}
5271
Douglas Gregor0be31a22010-07-02 17:43:08 +00005272CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5273 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005274 // C++ [class.copy]p4:
5275 // If the class definition does not explicitly declare a copy
5276 // constructor, one is declared implicitly.
5277
Douglas Gregor54be3392010-07-01 17:57:27 +00005278 // C++ [class.copy]p5:
5279 // The implicitly-declared copy constructor for a class X will
5280 // have the form
5281 //
5282 // X::X(const X&)
5283 //
5284 // if
5285 bool HasConstCopyConstructor = true;
5286
5287 // -- each direct or virtual base class B of X has a copy
5288 // constructor whose first parameter is of type const B& or
5289 // const volatile B&, and
5290 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5291 BaseEnd = ClassDecl->bases_end();
5292 HasConstCopyConstructor && Base != BaseEnd;
5293 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005294 // Virtual bases are handled below.
5295 if (Base->isVirtual())
5296 continue;
5297
Douglas Gregora6d69502010-07-02 23:41:54 +00005298 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005299 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005300 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5301 DeclareImplicitCopyConstructor(BaseClassDecl);
5302
Douglas Gregorcfe68222010-07-01 18:27:03 +00005303 HasConstCopyConstructor
5304 = BaseClassDecl->hasConstCopyConstructor(Context);
5305 }
5306
5307 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5308 BaseEnd = ClassDecl->vbases_end();
5309 HasConstCopyConstructor && Base != BaseEnd;
5310 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005311 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005312 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005313 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5314 DeclareImplicitCopyConstructor(BaseClassDecl);
5315
Douglas Gregor54be3392010-07-01 17:57:27 +00005316 HasConstCopyConstructor
5317 = BaseClassDecl->hasConstCopyConstructor(Context);
5318 }
5319
5320 // -- for all the nonstatic data members of X that are of a
5321 // class type M (or array thereof), each such class type
5322 // has a copy constructor whose first parameter is of type
5323 // const M& or const volatile M&.
5324 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5325 FieldEnd = ClassDecl->field_end();
5326 HasConstCopyConstructor && Field != FieldEnd;
5327 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005328 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005329 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005330 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005331 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005332 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5333 DeclareImplicitCopyConstructor(FieldClassDecl);
5334
Douglas Gregor54be3392010-07-01 17:57:27 +00005335 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005336 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005337 }
5338 }
5339
5340 // Otherwise, the implicitly declared copy constructor will have
5341 // the form
5342 //
5343 // X::X(X&)
5344 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5345 QualType ArgType = ClassType;
5346 if (HasConstCopyConstructor)
5347 ArgType = ArgType.withConst();
5348 ArgType = Context.getLValueReferenceType(ArgType);
5349
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005350 // C++ [except.spec]p14:
5351 // An implicitly declared special member function (Clause 12) shall have an
5352 // exception-specification. [...]
5353 ImplicitExceptionSpecification ExceptSpec(Context);
5354 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5355 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5356 BaseEnd = ClassDecl->bases_end();
5357 Base != BaseEnd;
5358 ++Base) {
5359 // Virtual bases are handled below.
5360 if (Base->isVirtual())
5361 continue;
5362
Douglas Gregora6d69502010-07-02 23:41:54 +00005363 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005364 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005365 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5366 DeclareImplicitCopyConstructor(BaseClassDecl);
5367
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005368 if (CXXConstructorDecl *CopyConstructor
5369 = BaseClassDecl->getCopyConstructor(Context, Quals))
5370 ExceptSpec.CalledDecl(CopyConstructor);
5371 }
5372 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5373 BaseEnd = ClassDecl->vbases_end();
5374 Base != BaseEnd;
5375 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005376 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005377 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005378 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5379 DeclareImplicitCopyConstructor(BaseClassDecl);
5380
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005381 if (CXXConstructorDecl *CopyConstructor
5382 = BaseClassDecl->getCopyConstructor(Context, Quals))
5383 ExceptSpec.CalledDecl(CopyConstructor);
5384 }
5385 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5386 FieldEnd = ClassDecl->field_end();
5387 Field != FieldEnd;
5388 ++Field) {
5389 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5390 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005391 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005392 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005393 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5394 DeclareImplicitCopyConstructor(FieldClassDecl);
5395
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005396 if (CXXConstructorDecl *CopyConstructor
5397 = FieldClassDecl->getCopyConstructor(Context, Quals))
5398 ExceptSpec.CalledDecl(CopyConstructor);
5399 }
5400 }
5401
Douglas Gregor54be3392010-07-01 17:57:27 +00005402 // An implicitly-declared copy constructor is an inline public
5403 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005404 FunctionProtoType::ExtProtoInfo EPI;
5405 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5406 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5407 EPI.NumExceptions = ExceptSpec.size();
5408 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005409 DeclarationName Name
5410 = Context.DeclarationNames.getCXXConstructorName(
5411 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005412 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005413 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005414 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005415 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005416 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005417 /*TInfo=*/0,
5418 /*isExplicit=*/false,
5419 /*isInline=*/true,
5420 /*isImplicitlyDeclared=*/true);
5421 CopyConstructor->setAccess(AS_public);
5422 CopyConstructor->setImplicit();
5423 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5424
Douglas Gregora6d69502010-07-02 23:41:54 +00005425 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005426 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5427
Douglas Gregor54be3392010-07-01 17:57:27 +00005428 // Add the parameter to the constructor.
5429 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5430 ClassDecl->getLocation(),
5431 /*IdentifierInfo=*/0,
5432 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005433 SC_None,
5434 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005435 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005436 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005437 PushOnScopeChains(CopyConstructor, S, false);
5438 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005439
5440 return CopyConstructor;
5441}
5442
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005443void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5444 CXXConstructorDecl *CopyConstructor,
5445 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005446 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005447 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005448 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005449 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005450
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005451 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005452 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005453
Douglas Gregora57478e2010-05-01 15:04:51 +00005454 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005455 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005456
Alexis Hunt1d792652011-01-08 20:30:50 +00005457 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005458 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005459 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005460 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005461 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005462 } else {
5463 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5464 CopyConstructor->getLocation(),
5465 MultiStmtArg(*this, 0, 0),
5466 /*isStmtExpr=*/false)
5467 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005468 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005469
5470 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005471}
5472
John McCalldadc5752010-08-24 06:29:42 +00005473ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005474Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005475 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005476 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005477 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005478 unsigned ConstructKind,
5479 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005480 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005481
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005482 // C++0x [class.copy]p34:
5483 // When certain criteria are met, an implementation is allowed to
5484 // omit the copy/move construction of a class object, even if the
5485 // copy/move constructor and/or destructor for the object have
5486 // side effects. [...]
5487 // - when a temporary class object that has not been bound to a
5488 // reference (12.2) would be copied/moved to a class object
5489 // with the same cv-unqualified type, the copy/move operation
5490 // can be omitted by constructing the temporary object
5491 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005492 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5493 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005494 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005495 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005496 }
Mike Stump11289f42009-09-09 15:08:12 +00005497
5498 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005499 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005500 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005501}
5502
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005503/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5504/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005505ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005506Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5507 CXXConstructorDecl *Constructor, bool Elidable,
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 Carlsson5995a3e2009-09-07 22:23:31 +00005512 unsigned NumExprs = ExprArgs.size();
5513 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005514
Douglas Gregor27381f32009-11-23 12:27:39 +00005515 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005516 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005517 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005518 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005519 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5520 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005521}
5522
Mike Stump11289f42009-09-09 15:08:12 +00005523bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005524 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005525 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005526 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005527 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005528 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005529 move(Exprs), false, CXXConstructExpr::CK_Complete,
5530 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005531 if (TempResult.isInvalid())
5532 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005533
Anders Carlsson6eb55572009-08-25 05:12:04 +00005534 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005535 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005536 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005537 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005538 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005539
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005540 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005541}
5542
John McCall03c48482010-02-02 09:10:11 +00005543void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005545 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005546 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005547 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005548 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005549 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005550 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005551 << VD->getDeclName()
5552 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005553
John McCall386dfc72010-09-18 05:25:11 +00005554 // TODO: this should be re-enabled for static locals by !CXAAtExit
5555 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005556 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005557 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005558}
5559
Mike Stump11289f42009-09-09 15:08:12 +00005560/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005561/// ActOnDeclarator, when a C++ direct initializer is present.
5562/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005563void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005564 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005565 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005566 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005567 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005568
5569 // If there is no declaration, there was an error parsing it. Just ignore
5570 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005571 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005572 return;
Mike Stump11289f42009-09-09 15:08:12 +00005573
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005574 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5575 if (!VDecl) {
5576 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5577 RealDecl->setInvalidDecl();
5578 return;
5579 }
5580
Douglas Gregor402250f2009-08-26 21:14:46 +00005581 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005582 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005583 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5584 //
5585 // Clients that want to distinguish between the two forms, can check for
5586 // direct initializer using VarDecl::hasCXXDirectInitializer().
5587 // A major benefit is that clients that don't particularly care about which
5588 // exactly form was it (like the CodeGen) can handle both cases without
5589 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005590
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005591 // C++ 8.5p11:
5592 // The form of initialization (using parentheses or '=') is generally
5593 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005594 // class type.
5595
Douglas Gregor50dc2192010-02-11 22:55:30 +00005596 if (!VDecl->getType()->isDependentType() &&
5597 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005598 diag::err_typecheck_decl_incomplete_type)) {
5599 VDecl->setInvalidDecl();
5600 return;
5601 }
5602
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005603 // The variable can not have an abstract class type.
5604 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5605 diag::err_abstract_type_in_decl,
5606 AbstractVariableType))
5607 VDecl->setInvalidDecl();
5608
Sebastian Redl5ca79842010-02-01 20:16:42 +00005609 const VarDecl *Def;
5610 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005611 Diag(VDecl->getLocation(), diag::err_redefinition)
5612 << VDecl->getDeclName();
5613 Diag(Def->getLocation(), diag::note_previous_definition);
5614 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005615 return;
5616 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005617
Douglas Gregorf0f83692010-08-24 05:27:49 +00005618 // C++ [class.static.data]p4
5619 // If a static data member is of const integral or const
5620 // enumeration type, its declaration in the class definition can
5621 // specify a constant-initializer which shall be an integral
5622 // constant expression (5.19). In that case, the member can appear
5623 // in integral constant expressions. The member shall still be
5624 // defined in a namespace scope if it is used in the program and the
5625 // namespace scope definition shall not contain an initializer.
5626 //
5627 // We already performed a redefinition check above, but for static
5628 // data members we also need to check whether there was an in-class
5629 // declaration with an initializer.
5630 const VarDecl* PrevInit = 0;
5631 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5632 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5633 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5634 return;
5635 }
5636
Douglas Gregor71f39c92010-12-16 01:31:22 +00005637 bool IsDependent = false;
5638 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
5639 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
5640 VDecl->setInvalidDecl();
5641 return;
5642 }
5643
5644 if (Exprs.get()[I]->isTypeDependent())
5645 IsDependent = true;
5646 }
5647
Douglas Gregor50dc2192010-02-11 22:55:30 +00005648 // If either the declaration has a dependent type or if any of the
5649 // expressions is type-dependent, we represent the initialization
5650 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00005651 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00005652 // Let clients know that initialization was done with a direct initializer.
5653 VDecl->setCXXDirectInitializer(true);
5654
5655 // Store the initialization expressions as a ParenListExpr.
5656 unsigned NumExprs = Exprs.size();
5657 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5658 (Expr **)Exprs.release(),
5659 NumExprs, RParenLoc));
5660 return;
5661 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005662
5663 // Capture the variable that is being initialized and the style of
5664 // initialization.
5665 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5666
5667 // FIXME: Poor source location information.
5668 InitializationKind Kind
5669 = InitializationKind::CreateDirect(VDecl->getLocation(),
5670 LParenLoc, RParenLoc);
5671
5672 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005673 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005674 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005675 if (Result.isInvalid()) {
5676 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005677 return;
5678 }
John McCallacf0ee52010-10-08 02:01:28 +00005679
5680 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005681
Douglas Gregora40433a2010-12-07 00:41:46 +00005682 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00005683 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005684 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005685
John McCall8b7fd8f12011-01-19 11:48:09 +00005686 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005687}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005688
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005689/// \brief Given a constructor and the set of arguments provided for the
5690/// constructor, convert the arguments and add any required default arguments
5691/// to form a proper call to this constructor.
5692///
5693/// \returns true if an error occurred, false otherwise.
5694bool
5695Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5696 MultiExprArg ArgsPtr,
5697 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005698 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005699 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5700 unsigned NumArgs = ArgsPtr.size();
5701 Expr **Args = (Expr **)ArgsPtr.get();
5702
5703 const FunctionProtoType *Proto
5704 = Constructor->getType()->getAs<FunctionProtoType>();
5705 assert(Proto && "Constructor without a prototype?");
5706 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005707
5708 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005709 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005710 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005711 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005712 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005713
5714 VariadicCallType CallType =
5715 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5716 llvm::SmallVector<Expr *, 8> AllArgs;
5717 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5718 Proto, 0, Args, NumArgs, AllArgs,
5719 CallType);
5720 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5721 ConvertedArgs.push_back(AllArgs[i]);
5722 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005723}
5724
Anders Carlssone363c8e2009-12-12 00:32:00 +00005725static inline bool
5726CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5727 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005728 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005729 if (isa<NamespaceDecl>(DC)) {
5730 return SemaRef.Diag(FnDecl->getLocation(),
5731 diag::err_operator_new_delete_declared_in_namespace)
5732 << FnDecl->getDeclName();
5733 }
5734
5735 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005736 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005737 return SemaRef.Diag(FnDecl->getLocation(),
5738 diag::err_operator_new_delete_declared_static)
5739 << FnDecl->getDeclName();
5740 }
5741
Anders Carlsson60659a82009-12-12 02:43:16 +00005742 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005743}
5744
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005745static inline bool
5746CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5747 CanQualType ExpectedResultType,
5748 CanQualType ExpectedFirstParamType,
5749 unsigned DependentParamTypeDiag,
5750 unsigned InvalidParamTypeDiag) {
5751 QualType ResultType =
5752 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5753
5754 // Check that the result type is not dependent.
5755 if (ResultType->isDependentType())
5756 return SemaRef.Diag(FnDecl->getLocation(),
5757 diag::err_operator_new_delete_dependent_result_type)
5758 << FnDecl->getDeclName() << ExpectedResultType;
5759
5760 // Check that the result type is what we expect.
5761 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5762 return SemaRef.Diag(FnDecl->getLocation(),
5763 diag::err_operator_new_delete_invalid_result_type)
5764 << FnDecl->getDeclName() << ExpectedResultType;
5765
5766 // A function template must have at least 2 parameters.
5767 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5768 return SemaRef.Diag(FnDecl->getLocation(),
5769 diag::err_operator_new_delete_template_too_few_parameters)
5770 << FnDecl->getDeclName();
5771
5772 // The function decl must have at least 1 parameter.
5773 if (FnDecl->getNumParams() == 0)
5774 return SemaRef.Diag(FnDecl->getLocation(),
5775 diag::err_operator_new_delete_too_few_parameters)
5776 << FnDecl->getDeclName();
5777
5778 // Check the the first parameter type is not dependent.
5779 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5780 if (FirstParamType->isDependentType())
5781 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5782 << FnDecl->getDeclName() << ExpectedFirstParamType;
5783
5784 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005785 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005786 ExpectedFirstParamType)
5787 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5788 << FnDecl->getDeclName() << ExpectedFirstParamType;
5789
5790 return false;
5791}
5792
Anders Carlsson12308f42009-12-11 23:23:22 +00005793static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005794CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005795 // C++ [basic.stc.dynamic.allocation]p1:
5796 // A program is ill-formed if an allocation function is declared in a
5797 // namespace scope other than global scope or declared static in global
5798 // scope.
5799 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5800 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005801
5802 CanQualType SizeTy =
5803 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5804
5805 // C++ [basic.stc.dynamic.allocation]p1:
5806 // The return type shall be void*. The first parameter shall have type
5807 // std::size_t.
5808 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5809 SizeTy,
5810 diag::err_operator_new_dependent_param_type,
5811 diag::err_operator_new_param_type))
5812 return true;
5813
5814 // C++ [basic.stc.dynamic.allocation]p1:
5815 // The first parameter shall not have an associated default argument.
5816 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005817 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005818 diag::err_operator_new_default_arg)
5819 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5820
5821 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005822}
5823
5824static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005825CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5826 // C++ [basic.stc.dynamic.deallocation]p1:
5827 // A program is ill-formed if deallocation functions are declared in a
5828 // namespace scope other than global scope or declared static in global
5829 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005830 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5831 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005832
5833 // C++ [basic.stc.dynamic.deallocation]p2:
5834 // Each deallocation function shall return void and its first parameter
5835 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005836 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5837 SemaRef.Context.VoidPtrTy,
5838 diag::err_operator_delete_dependent_param_type,
5839 diag::err_operator_delete_param_type))
5840 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005841
Anders Carlsson12308f42009-12-11 23:23:22 +00005842 return false;
5843}
5844
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005845/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5846/// of this overloaded operator is well-formed. If so, returns false;
5847/// otherwise, emits appropriate diagnostics and returns true.
5848bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005849 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005850 "Expected an overloaded operator declaration");
5851
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005852 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5853
Mike Stump11289f42009-09-09 15:08:12 +00005854 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005855 // The allocation and deallocation functions, operator new,
5856 // operator new[], operator delete and operator delete[], are
5857 // described completely in 3.7.3. The attributes and restrictions
5858 // found in the rest of this subclause do not apply to them unless
5859 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005860 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005861 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005862
Anders Carlsson22f443f2009-12-12 00:26:23 +00005863 if (Op == OO_New || Op == OO_Array_New)
5864 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005865
5866 // C++ [over.oper]p6:
5867 // An operator function shall either be a non-static member
5868 // function or be a non-member function and have at least one
5869 // parameter whose type is a class, a reference to a class, an
5870 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005871 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5872 if (MethodDecl->isStatic())
5873 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005874 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005875 } else {
5876 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005877 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5878 ParamEnd = FnDecl->param_end();
5879 Param != ParamEnd; ++Param) {
5880 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005881 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5882 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005883 ClassOrEnumParam = true;
5884 break;
5885 }
5886 }
5887
Douglas Gregord69246b2008-11-17 16:14:12 +00005888 if (!ClassOrEnumParam)
5889 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005890 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005891 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005892 }
5893
5894 // C++ [over.oper]p8:
5895 // An operator function cannot have default arguments (8.3.6),
5896 // except where explicitly stated below.
5897 //
Mike Stump11289f42009-09-09 15:08:12 +00005898 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005899 // (C++ [over.call]p1).
5900 if (Op != OO_Call) {
5901 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5902 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005903 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005904 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005905 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005906 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005907 }
5908 }
5909
Douglas Gregor6cf08062008-11-10 13:38:07 +00005910 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5911 { false, false, false }
5912#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5913 , { Unary, Binary, MemberOnly }
5914#include "clang/Basic/OperatorKinds.def"
5915 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005916
Douglas Gregor6cf08062008-11-10 13:38:07 +00005917 bool CanBeUnaryOperator = OperatorUses[Op][0];
5918 bool CanBeBinaryOperator = OperatorUses[Op][1];
5919 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005920
5921 // C++ [over.oper]p8:
5922 // [...] Operator functions cannot have more or fewer parameters
5923 // than the number required for the corresponding operator, as
5924 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005925 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005926 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005927 if (Op != OO_Call &&
5928 ((NumParams == 1 && !CanBeUnaryOperator) ||
5929 (NumParams == 2 && !CanBeBinaryOperator) ||
5930 (NumParams < 1) || (NumParams > 2))) {
5931 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005932 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005933 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005934 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005935 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005936 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005937 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005938 assert(CanBeBinaryOperator &&
5939 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005940 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005941 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005942
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005943 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005944 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005945 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005946
Douglas Gregord69246b2008-11-17 16:14:12 +00005947 // Overloaded operators other than operator() cannot be variadic.
5948 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005949 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005950 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005951 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005952 }
5953
5954 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005955 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5956 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005957 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005958 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005959 }
5960
5961 // C++ [over.inc]p1:
5962 // The user-defined function called operator++ implements the
5963 // prefix and postfix ++ operator. If this function is a member
5964 // function with no parameters, or a non-member function with one
5965 // parameter of class or enumeration type, it defines the prefix
5966 // increment operator ++ for objects of that type. If the function
5967 // is a member function with one parameter (which shall be of type
5968 // int) or a non-member function with two parameters (the second
5969 // of which shall be of type int), it defines the postfix
5970 // increment operator ++ for objects of that type.
5971 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5972 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5973 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005974 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005975 ParamIsInt = BT->getKind() == BuiltinType::Int;
5976
Chris Lattner2b786902008-11-21 07:50:02 +00005977 if (!ParamIsInt)
5978 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005979 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005980 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005981 }
5982
Douglas Gregord69246b2008-11-17 16:14:12 +00005983 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005984}
Chris Lattner3b024a32008-12-17 07:09:26 +00005985
Alexis Huntc88db062010-01-13 09:01:02 +00005986/// CheckLiteralOperatorDeclaration - Check whether the declaration
5987/// of this literal operator function is well-formed. If so, returns
5988/// false; otherwise, emits appropriate diagnostics and returns true.
5989bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5990 DeclContext *DC = FnDecl->getDeclContext();
5991 Decl::Kind Kind = DC->getDeclKind();
5992 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5993 Kind != Decl::LinkageSpec) {
5994 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5995 << FnDecl->getDeclName();
5996 return true;
5997 }
5998
5999 bool Valid = false;
6000
Alexis Hunt7dd26172010-04-07 23:11:06 +00006001 // template <char...> type operator "" name() is the only valid template
6002 // signature, and the only valid signature with no parameters.
6003 if (FnDecl->param_size() == 0) {
6004 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6005 // Must have only one template parameter
6006 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6007 if (Params->size() == 1) {
6008 NonTypeTemplateParmDecl *PmDecl =
6009 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006010
Alexis Hunt7dd26172010-04-07 23:11:06 +00006011 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006012 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6013 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6014 Valid = true;
6015 }
6016 }
6017 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006018 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006019 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6020
Alexis Huntc88db062010-01-13 09:01:02 +00006021 QualType T = (*Param)->getType();
6022
Alexis Hunt079a6f72010-04-07 22:57:35 +00006023 // unsigned long long int, long double, and any character type are allowed
6024 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006025 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6026 Context.hasSameType(T, Context.LongDoubleTy) ||
6027 Context.hasSameType(T, Context.CharTy) ||
6028 Context.hasSameType(T, Context.WCharTy) ||
6029 Context.hasSameType(T, Context.Char16Ty) ||
6030 Context.hasSameType(T, Context.Char32Ty)) {
6031 if (++Param == FnDecl->param_end())
6032 Valid = true;
6033 goto FinishedParams;
6034 }
6035
Alexis Hunt079a6f72010-04-07 22:57:35 +00006036 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006037 const PointerType *PT = T->getAs<PointerType>();
6038 if (!PT)
6039 goto FinishedParams;
6040 T = PT->getPointeeType();
6041 if (!T.isConstQualified())
6042 goto FinishedParams;
6043 T = T.getUnqualifiedType();
6044
6045 // Move on to the second parameter;
6046 ++Param;
6047
6048 // If there is no second parameter, the first must be a const char *
6049 if (Param == FnDecl->param_end()) {
6050 if (Context.hasSameType(T, Context.CharTy))
6051 Valid = true;
6052 goto FinishedParams;
6053 }
6054
6055 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6056 // are allowed as the first parameter to a two-parameter function
6057 if (!(Context.hasSameType(T, Context.CharTy) ||
6058 Context.hasSameType(T, Context.WCharTy) ||
6059 Context.hasSameType(T, Context.Char16Ty) ||
6060 Context.hasSameType(T, Context.Char32Ty)))
6061 goto FinishedParams;
6062
6063 // The second and final parameter must be an std::size_t
6064 T = (*Param)->getType().getUnqualifiedType();
6065 if (Context.hasSameType(T, Context.getSizeType()) &&
6066 ++Param == FnDecl->param_end())
6067 Valid = true;
6068 }
6069
6070 // FIXME: This diagnostic is absolutely terrible.
6071FinishedParams:
6072 if (!Valid) {
6073 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6074 << FnDecl->getDeclName();
6075 return true;
6076 }
6077
6078 return false;
6079}
6080
Douglas Gregor07665a62009-01-05 19:45:36 +00006081/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6082/// linkage specification, including the language and (if present)
6083/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6084/// the location of the language string literal, which is provided
6085/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6086/// the '{' brace. Otherwise, this linkage specification does not
6087/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006088Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6089 SourceLocation LangLoc,
6090 llvm::StringRef Lang,
6091 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006092 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006093 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006094 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006095 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006096 Language = LinkageSpecDecl::lang_cxx;
6097 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006098 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006099 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006100 }
Mike Stump11289f42009-09-09 15:08:12 +00006101
Chris Lattner438e5012008-12-17 07:13:27 +00006102 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006103
Douglas Gregor07665a62009-01-05 19:45:36 +00006104 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006105 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006106 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006107 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006108 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006109 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006110}
6111
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006112/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006113/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6114/// valid, it's the position of the closing '}' brace in a linkage
6115/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006116Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6117 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006118 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006119 if (LinkageSpec)
6120 PopDeclContext();
6121 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006122}
6123
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006124/// \brief Perform semantic analysis for the variable declaration that
6125/// occurs within a C++ catch clause, returning the newly-created
6126/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006127VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006128 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006129 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006130 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006131 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006132 QualType ExDeclType = TInfo->getType();
6133
Sebastian Redl54c04d42008-12-22 19:15:10 +00006134 // Arrays and functions decay.
6135 if (ExDeclType->isArrayType())
6136 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6137 else if (ExDeclType->isFunctionType())
6138 ExDeclType = Context.getPointerType(ExDeclType);
6139
6140 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6141 // The exception-declaration shall not denote a pointer or reference to an
6142 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006143 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006144 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006145 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006146 Invalid = true;
6147 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006148
Douglas Gregor104ee002010-03-08 01:47:36 +00006149 // GCC allows catching pointers and references to incomplete types
6150 // as an extension; so do we, but we warn by default.
6151
Sebastian Redl54c04d42008-12-22 19:15:10 +00006152 QualType BaseType = ExDeclType;
6153 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006154 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006155 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006156 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006157 BaseType = Ptr->getPointeeType();
6158 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006159 DK = diag::ext_catch_incomplete_ptr;
6160 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006161 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006162 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006163 BaseType = Ref->getPointeeType();
6164 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006165 DK = diag::ext_catch_incomplete_ref;
6166 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006167 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006168 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006169 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6170 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006171 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006172
Mike Stump11289f42009-09-09 15:08:12 +00006173 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006174 RequireNonAbstractType(Loc, ExDeclType,
6175 diag::err_abstract_type_in_decl,
6176 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006177 Invalid = true;
6178
John McCall2ca705e2010-07-24 00:37:23 +00006179 // Only the non-fragile NeXT runtime currently supports C++ catches
6180 // of ObjC types, and no runtime supports catching ObjC types by value.
6181 if (!Invalid && getLangOptions().ObjC1) {
6182 QualType T = ExDeclType;
6183 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6184 T = RT->getPointeeType();
6185
6186 if (T->isObjCObjectType()) {
6187 Diag(Loc, diag::err_objc_object_catch);
6188 Invalid = true;
6189 } else if (T->isObjCObjectPointerType()) {
6190 if (!getLangOptions().NeXTRuntime) {
6191 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6192 Invalid = true;
6193 } else if (!getLangOptions().ObjCNonFragileABI) {
6194 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6195 Invalid = true;
6196 }
6197 }
6198 }
6199
Mike Stump11289f42009-09-09 15:08:12 +00006200 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006201 Name, ExDeclType, TInfo, SC_None,
6202 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006203 ExDecl->setExceptionVariable(true);
6204
Douglas Gregor6de584c2010-03-05 23:38:39 +00006205 if (!Invalid) {
6206 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6207 // C++ [except.handle]p16:
6208 // The object declared in an exception-declaration or, if the
6209 // exception-declaration does not specify a name, a temporary (12.2) is
6210 // copy-initialized (8.5) from the exception object. [...]
6211 // The object is destroyed when the handler exits, after the destruction
6212 // of any automatic objects initialized within the handler.
6213 //
6214 // We just pretend to initialize the object with itself, then make sure
6215 // it can be destroyed later.
6216 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6217 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
John McCall7decc9e2010-11-18 06:31:45 +00006218 Loc, ExDeclType, VK_LValue, 0);
Douglas Gregor6de584c2010-03-05 23:38:39 +00006219 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6220 SourceLocation());
6221 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006222 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006223 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006224 if (Result.isInvalid())
6225 Invalid = true;
6226 else
6227 FinalizeVarWithDestructor(ExDecl, RecordTy);
6228 }
6229 }
6230
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006231 if (Invalid)
6232 ExDecl->setInvalidDecl();
6233
6234 return ExDecl;
6235}
6236
6237/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6238/// handler.
John McCall48871652010-08-21 09:40:31 +00006239Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006240 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006241 bool Invalid = D.isInvalidType();
6242
6243 // Check for unexpanded parameter packs.
6244 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6245 UPPC_ExceptionType)) {
6246 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6247 D.getIdentifierLoc());
6248 Invalid = true;
6249 }
6250
Sebastian Redl54c04d42008-12-22 19:15:10 +00006251 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006252 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006253 LookupOrdinaryName,
6254 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006255 // The scope should be freshly made just for us. There is just no way
6256 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006257 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006258 if (PrevDecl->isTemplateParameter()) {
6259 // Maybe we will complain about the shadowed template parameter.
6260 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006261 }
6262 }
6263
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006264 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006265 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6266 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006267 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006268 }
6269
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006270 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006271 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006272 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006273
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006274 if (Invalid)
6275 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006276
Sebastian Redl54c04d42008-12-22 19:15:10 +00006277 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006278 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006279 PushOnScopeChains(ExDecl, S);
6280 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006281 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006282
Douglas Gregor758a8692009-06-17 21:51:59 +00006283 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006284 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006285}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006286
John McCall48871652010-08-21 09:40:31 +00006287Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006288 Expr *AssertExpr,
6289 Expr *AssertMessageExpr_) {
6290 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006291
Anders Carlsson54b26982009-03-14 00:33:21 +00006292 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6293 llvm::APSInt Value(32);
6294 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6295 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6296 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006297 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006298 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006299
Anders Carlsson54b26982009-03-14 00:33:21 +00006300 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006301 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006302 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006303 }
6304 }
Mike Stump11289f42009-09-09 15:08:12 +00006305
Douglas Gregoref68fee2010-12-15 23:55:21 +00006306 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6307 return 0;
6308
Mike Stump11289f42009-09-09 15:08:12 +00006309 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006310 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006311
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006312 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006313 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006314}
Sebastian Redlf769df52009-03-24 22:27:57 +00006315
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006316/// \brief Perform semantic analysis of the given friend type declaration.
6317///
6318/// \returns A friend declaration that.
6319FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6320 TypeSourceInfo *TSInfo) {
6321 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6322
6323 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006324 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006325
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006326 if (!getLangOptions().CPlusPlus0x) {
6327 // C++03 [class.friend]p2:
6328 // An elaborated-type-specifier shall be used in a friend declaration
6329 // for a class.*
6330 //
6331 // * The class-key of the elaborated-type-specifier is required.
6332 if (!ActiveTemplateInstantiations.empty()) {
6333 // Do not complain about the form of friend template types during
6334 // template instantiation; we will already have complained when the
6335 // template was declared.
6336 } else if (!T->isElaboratedTypeSpecifier()) {
6337 // If we evaluated the type to a record type, suggest putting
6338 // a tag in front.
6339 if (const RecordType *RT = T->getAs<RecordType>()) {
6340 RecordDecl *RD = RT->getDecl();
6341
6342 std::string InsertionText = std::string(" ") + RD->getKindName();
6343
6344 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6345 << (unsigned) RD->getTagKind()
6346 << T
6347 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6348 InsertionText);
6349 } else {
6350 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6351 << T
6352 << SourceRange(FriendLoc, TypeRange.getEnd());
6353 }
6354 } else if (T->getAs<EnumType>()) {
6355 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006356 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006357 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006358 }
6359 }
6360
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006361 // C++0x [class.friend]p3:
6362 // If the type specifier in a friend declaration designates a (possibly
6363 // cv-qualified) class type, that class is declared as a friend; otherwise,
6364 // the friend declaration is ignored.
6365
6366 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6367 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006368
6369 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6370}
6371
John McCallace48cd2010-10-19 01:40:49 +00006372/// Handle a friend tag declaration where the scope specifier was
6373/// templated.
6374Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6375 unsigned TagSpec, SourceLocation TagLoc,
6376 CXXScopeSpec &SS,
6377 IdentifierInfo *Name, SourceLocation NameLoc,
6378 AttributeList *Attr,
6379 MultiTemplateParamsArg TempParamLists) {
6380 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6381
6382 bool isExplicitSpecialization = false;
6383 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6384 bool Invalid = false;
6385
6386 if (TemplateParameterList *TemplateParams
6387 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6388 TempParamLists.get(),
6389 TempParamLists.size(),
6390 /*friend*/ true,
6391 isExplicitSpecialization,
6392 Invalid)) {
6393 --NumMatchedTemplateParamLists;
6394
6395 if (TemplateParams->size() > 0) {
6396 // This is a declaration of a class template.
6397 if (Invalid)
6398 return 0;
6399
6400 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6401 SS, Name, NameLoc, Attr,
6402 TemplateParams, AS_public).take();
6403 } else {
6404 // The "template<>" header is extraneous.
6405 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6406 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6407 isExplicitSpecialization = true;
6408 }
6409 }
6410
6411 if (Invalid) return 0;
6412
6413 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6414
6415 bool isAllExplicitSpecializations = true;
6416 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6417 if (TempParamLists.get()[I]->size()) {
6418 isAllExplicitSpecializations = false;
6419 break;
6420 }
6421 }
6422
6423 // FIXME: don't ignore attributes.
6424
6425 // If it's explicit specializations all the way down, just forget
6426 // about the template header and build an appropriate non-templated
6427 // friend. TODO: for source fidelity, remember the headers.
6428 if (isAllExplicitSpecializations) {
6429 ElaboratedTypeKeyword Keyword
6430 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6431 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6432 TagLoc, SS.getRange(), NameLoc);
6433 if (T.isNull())
6434 return 0;
6435
6436 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6437 if (isa<DependentNameType>(T)) {
6438 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6439 TL.setKeywordLoc(TagLoc);
6440 TL.setQualifierRange(SS.getRange());
6441 TL.setNameLoc(NameLoc);
6442 } else {
6443 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6444 TL.setKeywordLoc(TagLoc);
6445 TL.setQualifierRange(SS.getRange());
6446 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6447 }
6448
6449 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6450 TSI, FriendLoc);
6451 Friend->setAccess(AS_public);
6452 CurContext->addDecl(Friend);
6453 return Friend;
6454 }
6455
6456 // Handle the case of a templated-scope friend class. e.g.
6457 // template <class T> class A<T>::B;
6458 // FIXME: we don't support these right now.
6459 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6460 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6461 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6462 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6463 TL.setKeywordLoc(TagLoc);
6464 TL.setQualifierRange(SS.getRange());
6465 TL.setNameLoc(NameLoc);
6466
6467 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6468 TSI, FriendLoc);
6469 Friend->setAccess(AS_public);
6470 Friend->setUnsupportedFriend(true);
6471 CurContext->addDecl(Friend);
6472 return Friend;
6473}
6474
6475
John McCall11083da2009-09-16 22:47:08 +00006476/// Handle a friend type declaration. This works in tandem with
6477/// ActOnTag.
6478///
6479/// Notes on friend class templates:
6480///
6481/// We generally treat friend class declarations as if they were
6482/// declaring a class. So, for example, the elaborated type specifier
6483/// in a friend declaration is required to obey the restrictions of a
6484/// class-head (i.e. no typedefs in the scope chain), template
6485/// parameters are required to match up with simple template-ids, &c.
6486/// However, unlike when declaring a template specialization, it's
6487/// okay to refer to a template specialization without an empty
6488/// template parameter declaration, e.g.
6489/// friend class A<T>::B<unsigned>;
6490/// We permit this as a special case; if there are any template
6491/// parameters present at all, require proper matching, i.e.
6492/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006493Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006494 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006495 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006496
6497 assert(DS.isFriendSpecified());
6498 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6499
John McCall11083da2009-09-16 22:47:08 +00006500 // Try to convert the decl specifier to a type. This works for
6501 // friend templates because ActOnTag never produces a ClassTemplateDecl
6502 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006503 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006504 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6505 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006506 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006507 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006508
Douglas Gregor6c110f32010-12-16 01:14:37 +00006509 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6510 return 0;
6511
John McCall11083da2009-09-16 22:47:08 +00006512 // This is definitely an error in C++98. It's probably meant to
6513 // be forbidden in C++0x, too, but the specification is just
6514 // poorly written.
6515 //
6516 // The problem is with declarations like the following:
6517 // template <T> friend A<T>::foo;
6518 // where deciding whether a class C is a friend or not now hinges
6519 // on whether there exists an instantiation of A that causes
6520 // 'foo' to equal C. There are restrictions on class-heads
6521 // (which we declare (by fiat) elaborated friend declarations to
6522 // be) that makes this tractable.
6523 //
6524 // FIXME: handle "template <> friend class A<T>;", which
6525 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006526 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006527 Diag(Loc, diag::err_tagless_friend_type_template)
6528 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006529 return 0;
John McCall11083da2009-09-16 22:47:08 +00006530 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006531
John McCallaa74a0c2009-08-28 07:59:38 +00006532 // C++98 [class.friend]p1: A friend of a class is a function
6533 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006534 // This is fixed in DR77, which just barely didn't make the C++03
6535 // deadline. It's also a very silly restriction that seriously
6536 // affects inner classes and which nobody else seems to implement;
6537 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006538 //
6539 // But note that we could warn about it: it's always useless to
6540 // friend one of your own members (it's not, however, worthless to
6541 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006542
John McCall11083da2009-09-16 22:47:08 +00006543 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006544 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006545 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006546 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006547 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006548 TSI,
John McCall11083da2009-09-16 22:47:08 +00006549 DS.getFriendSpecLoc());
6550 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006551 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6552
6553 if (!D)
John McCall48871652010-08-21 09:40:31 +00006554 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006555
John McCall11083da2009-09-16 22:47:08 +00006556 D->setAccess(AS_public);
6557 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006558
John McCall48871652010-08-21 09:40:31 +00006559 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006560}
6561
John McCallde3fd222010-10-12 23:13:28 +00006562Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6563 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006564 const DeclSpec &DS = D.getDeclSpec();
6565
6566 assert(DS.isFriendSpecified());
6567 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6568
6569 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006570 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6571 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006572
6573 // C++ [class.friend]p1
6574 // A friend of a class is a function or class....
6575 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006576 // It *doesn't* see through dependent types, which is correct
6577 // according to [temp.arg.type]p3:
6578 // If a declaration acquires a function type through a
6579 // type dependent on a template-parameter and this causes
6580 // a declaration that does not use the syntactic form of a
6581 // function declarator to have a function type, the program
6582 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006583 if (!T->isFunctionType()) {
6584 Diag(Loc, diag::err_unexpected_friend);
6585
6586 // It might be worthwhile to try to recover by creating an
6587 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006588 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006589 }
6590
6591 // C++ [namespace.memdef]p3
6592 // - If a friend declaration in a non-local class first declares a
6593 // class or function, the friend class or function is a member
6594 // of the innermost enclosing namespace.
6595 // - The name of the friend is not found by simple name lookup
6596 // until a matching declaration is provided in that namespace
6597 // scope (either before or after the class declaration granting
6598 // friendship).
6599 // - If a friend function is called, its name may be found by the
6600 // name lookup that considers functions from namespaces and
6601 // classes associated with the types of the function arguments.
6602 // - When looking for a prior declaration of a class or a function
6603 // declared as a friend, scopes outside the innermost enclosing
6604 // namespace scope are not considered.
6605
John McCallde3fd222010-10-12 23:13:28 +00006606 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006607 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6608 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006609 assert(Name);
6610
Douglas Gregor6c110f32010-12-16 01:14:37 +00006611 // Check for unexpanded parameter packs.
6612 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
6613 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
6614 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
6615 return 0;
6616
John McCall07e91c02009-08-06 02:15:43 +00006617 // The context we found the declaration in, or in which we should
6618 // create the declaration.
6619 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00006620 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006621 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006622 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006623
John McCallde3fd222010-10-12 23:13:28 +00006624 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00006625
John McCallde3fd222010-10-12 23:13:28 +00006626 // There are four cases here.
6627 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00006628 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00006629 // there as appropriate.
6630 // Recover from invalid scope qualifiers as if they just weren't there.
6631 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00006632 // C++0x [namespace.memdef]p3:
6633 // If the name in a friend declaration is neither qualified nor
6634 // a template-id and the declaration is a function or an
6635 // elaborated-type-specifier, the lookup to determine whether
6636 // the entity has been previously declared shall not consider
6637 // any scopes outside the innermost enclosing namespace.
6638 // C++0x [class.friend]p11:
6639 // If a friend declaration appears in a local class and the name
6640 // specified is an unqualified name, a prior declaration is
6641 // looked up without considering scopes that are outside the
6642 // innermost enclosing non-class scope. For a friend function
6643 // declaration, if there is no prior declaration, the program is
6644 // ill-formed.
6645 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00006646 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00006647
John McCallf7cfb222010-10-13 05:45:15 +00006648 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00006649 DC = CurContext;
6650 while (true) {
6651 // Skip class contexts. If someone can cite chapter and verse
6652 // for this behavior, that would be nice --- it's what GCC and
6653 // EDG do, and it seems like a reasonable intent, but the spec
6654 // really only says that checks for unqualified existing
6655 // declarations should stop at the nearest enclosing namespace,
6656 // not that they should only consider the nearest enclosing
6657 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006658 while (DC->isRecord())
6659 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006660
John McCall1f82f242009-11-18 22:49:29 +00006661 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006662
6663 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00006664 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006665 break;
John McCallf7cfb222010-10-13 05:45:15 +00006666
John McCallf4776592010-10-14 22:22:28 +00006667 if (isTemplateId) {
6668 if (isa<TranslationUnitDecl>(DC)) break;
6669 } else {
6670 if (DC->isFileContext()) break;
6671 }
John McCall07e91c02009-08-06 02:15:43 +00006672 DC = DC->getParent();
6673 }
6674
6675 // C++ [class.friend]p1: A friend of a class is a function or
6676 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006677 // C++0x changes this for both friend types and functions.
6678 // Most C++ 98 compilers do seem to give an error here, so
6679 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006680 if (!Previous.empty() && DC->Equals(CurContext)
6681 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006682 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00006683
John McCallccbc0322010-10-13 06:22:15 +00006684 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00006685
John McCallde3fd222010-10-12 23:13:28 +00006686 // - There's a non-dependent scope specifier, in which case we
6687 // compute it and do a previous lookup there for a function
6688 // or function template.
6689 } else if (!SS.getScopeRep()->isDependent()) {
6690 DC = computeDeclContext(SS);
6691 if (!DC) return 0;
6692
6693 if (RequireCompleteDeclContext(SS, DC)) return 0;
6694
6695 LookupQualifiedName(Previous, DC);
6696
6697 // Ignore things found implicitly in the wrong scope.
6698 // TODO: better diagnostics for this case. Suggesting the right
6699 // qualified scope would be nice...
6700 LookupResult::Filter F = Previous.makeFilter();
6701 while (F.hasNext()) {
6702 NamedDecl *D = F.next();
6703 if (!DC->InEnclosingNamespaceSetOf(
6704 D->getDeclContext()->getRedeclContext()))
6705 F.erase();
6706 }
6707 F.done();
6708
6709 if (Previous.empty()) {
6710 D.setInvalidType();
6711 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6712 return 0;
6713 }
6714
6715 // C++ [class.friend]p1: A friend of a class is a function or
6716 // class that is not a member of the class . . .
6717 if (DC->Equals(CurContext))
6718 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6719
6720 // - There's a scope specifier that does not match any template
6721 // parameter lists, in which case we use some arbitrary context,
6722 // create a method or method template, and wait for instantiation.
6723 // - There's a scope specifier that does match some template
6724 // parameter lists, which we don't handle right now.
6725 } else {
6726 DC = CurContext;
6727 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00006728 }
6729
John McCallf7cfb222010-10-13 05:45:15 +00006730 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00006731 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006732 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6733 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6734 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006735 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006736 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6737 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006738 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006739 }
John McCall07e91c02009-08-06 02:15:43 +00006740 }
6741
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006742 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00006743 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006744 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006745 IsDefinition,
6746 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006747 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006748
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006749 assert(ND->getDeclContext() == DC);
6750 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006751
John McCall759e32b2009-08-31 22:39:49 +00006752 // Add the function declaration to the appropriate lookup tables,
6753 // adjusting the redeclarations list as necessary. We don't
6754 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006755 //
John McCall759e32b2009-08-31 22:39:49 +00006756 // Also update the scope-based lookup if the target context's
6757 // lookup context is in lexical scope.
6758 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006759 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006760 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006761 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006762 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006763 }
John McCallaa74a0c2009-08-28 07:59:38 +00006764
6765 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006766 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006767 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006768 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006769 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006770
John McCallde3fd222010-10-12 23:13:28 +00006771 if (ND->isInvalidDecl())
6772 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00006773 else {
6774 FunctionDecl *FD;
6775 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
6776 FD = FTD->getTemplatedDecl();
6777 else
6778 FD = cast<FunctionDecl>(ND);
6779
6780 // Mark templated-scope function declarations as unsupported.
6781 if (FD->getNumTemplateParameterLists())
6782 FrD->setUnsupportedFriend(true);
6783 }
John McCallde3fd222010-10-12 23:13:28 +00006784
John McCall48871652010-08-21 09:40:31 +00006785 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006786}
6787
John McCall48871652010-08-21 09:40:31 +00006788void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6789 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006790
Sebastian Redlf769df52009-03-24 22:27:57 +00006791 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6792 if (!Fn) {
6793 Diag(DelLoc, diag::err_deleted_non_function);
6794 return;
6795 }
6796 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6797 Diag(DelLoc, diag::err_deleted_decl_not_first);
6798 Diag(Prev->getLocation(), diag::note_previous_declaration);
6799 // If the declaration wasn't the first, we delete the function anyway for
6800 // recovery.
6801 }
6802 Fn->setDeleted();
6803}
Sebastian Redl4c018662009-04-27 21:33:24 +00006804
6805static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6806 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6807 ++CI) {
6808 Stmt *SubStmt = *CI;
6809 if (!SubStmt)
6810 continue;
6811 if (isa<ReturnStmt>(SubStmt))
6812 Self.Diag(SubStmt->getSourceRange().getBegin(),
6813 diag::err_return_in_constructor_handler);
6814 if (!isa<Expr>(SubStmt))
6815 SearchForReturnInStmt(Self, SubStmt);
6816 }
6817}
6818
6819void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6820 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6821 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6822 SearchForReturnInStmt(*this, Handler);
6823 }
6824}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006825
Mike Stump11289f42009-09-09 15:08:12 +00006826bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006827 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006828 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6829 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006830
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006831 if (Context.hasSameType(NewTy, OldTy) ||
6832 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006833 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006834
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006835 // Check if the return types are covariant
6836 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006837
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006838 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006839 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6840 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006841 NewClassTy = NewPT->getPointeeType();
6842 OldClassTy = OldPT->getPointeeType();
6843 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006844 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6845 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6846 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6847 NewClassTy = NewRT->getPointeeType();
6848 OldClassTy = OldRT->getPointeeType();
6849 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006850 }
6851 }
Mike Stump11289f42009-09-09 15:08:12 +00006852
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006853 // The return types aren't either both pointers or references to a class type.
6854 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006855 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006856 diag::err_different_return_type_for_overriding_virtual_function)
6857 << New->getDeclName() << NewTy << OldTy;
6858 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006859
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006860 return true;
6861 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006862
Anders Carlssone60365b2009-12-31 18:34:24 +00006863 // C++ [class.virtual]p6:
6864 // If the return type of D::f differs from the return type of B::f, the
6865 // class type in the return type of D::f shall be complete at the point of
6866 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006867 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6868 if (!RT->isBeingDefined() &&
6869 RequireCompleteType(New->getLocation(), NewClassTy,
6870 PDiag(diag::err_covariant_return_incomplete)
6871 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006872 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006873 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006874
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006875 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006876 // Check if the new class derives from the old class.
6877 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6878 Diag(New->getLocation(),
6879 diag::err_covariant_return_not_derived)
6880 << New->getDeclName() << NewTy << OldTy;
6881 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6882 return true;
6883 }
Mike Stump11289f42009-09-09 15:08:12 +00006884
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006885 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006886 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006887 diag::err_covariant_return_inaccessible_base,
6888 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6889 // FIXME: Should this point to the return type?
6890 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006891 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6892 return true;
6893 }
6894 }
Mike Stump11289f42009-09-09 15:08:12 +00006895
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006896 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006897 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006898 Diag(New->getLocation(),
6899 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006900 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006901 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6902 return true;
6903 };
Mike Stump11289f42009-09-09 15:08:12 +00006904
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006905
6906 // The new class type must have the same or less qualifiers as the old type.
6907 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6908 Diag(New->getLocation(),
6909 diag::err_covariant_return_type_class_type_more_qualified)
6910 << New->getDeclName() << NewTy << OldTy;
6911 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6912 return true;
6913 };
Mike Stump11289f42009-09-09 15:08:12 +00006914
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006915 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006916}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006917
Alexis Hunt96d5c762009-11-21 08:43:09 +00006918bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6919 const CXXMethodDecl *Old)
6920{
6921 if (Old->hasAttr<FinalAttr>()) {
6922 Diag(New->getLocation(), diag::err_final_function_overridden)
6923 << New->getDeclName();
6924 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6925 return true;
6926 }
6927
6928 return false;
6929}
6930
Douglas Gregor21920e372009-12-01 17:24:26 +00006931/// \brief Mark the given method pure.
6932///
6933/// \param Method the method to be marked pure.
6934///
6935/// \param InitRange the source range that covers the "0" initializer.
6936bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6937 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6938 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006939 return false;
6940 }
6941
6942 if (!Method->isInvalidDecl())
6943 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6944 << Method->getDeclName() << InitRange;
6945 return true;
6946}
6947
John McCall1f4ee7b2009-12-19 09:28:58 +00006948/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6949/// an initializer for the out-of-line declaration 'Dcl'. The scope
6950/// is a fresh scope pushed for just this purpose.
6951///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006952/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6953/// static data member of class X, names should be looked up in the scope of
6954/// class X.
John McCall48871652010-08-21 09:40:31 +00006955void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006956 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006957 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006958
John McCall1f4ee7b2009-12-19 09:28:58 +00006959 // We should only get called for declarations with scope specifiers, like:
6960 // int foo::bar;
6961 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006962 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006963}
6964
6965/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006966/// initializer for the out-of-line declaration 'D'.
6967void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006968 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006969 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006970
John McCall1f4ee7b2009-12-19 09:28:58 +00006971 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006972 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006973}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006974
6975/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6976/// C++ if/switch/while/for statement.
6977/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006978DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006979 // C++ 6.4p2:
6980 // The declarator shall not specify a function or an array.
6981 // The type-specifier-seq shall not contain typedef and shall not declare a
6982 // new class or enumeration.
6983 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6984 "Parser allowed 'typedef' as storage class of condition decl.");
6985
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006986 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006987 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6988 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006989
6990 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6991 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6992 // would be created and CXXConditionDeclExpr wants a VarDecl.
6993 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6994 << D.getSourceRange();
6995 return DeclResult();
6996 } else if (OwnedTag && OwnedTag->isDefinition()) {
6997 // The type-specifier-seq shall not declare a new class or enumeration.
6998 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6999 }
7000
John McCall48871652010-08-21 09:40:31 +00007001 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007002 if (!Dcl)
7003 return DeclResult();
7004
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007005 return Dcl;
7006}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007007
Douglas Gregor88d292c2010-05-13 16:44:06 +00007008void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7009 bool DefinitionRequired) {
7010 // Ignore any vtable uses in unevaluated operands or for classes that do
7011 // not have a vtable.
7012 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7013 CurContext->isDependentContext() ||
7014 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007015 return;
7016
Douglas Gregor88d292c2010-05-13 16:44:06 +00007017 // Try to insert this class into the map.
7018 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7019 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7020 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7021 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007022 // If we already had an entry, check to see if we are promoting this vtable
7023 // to required a definition. If so, we need to reappend to the VTableUses
7024 // list, since we may have already processed the first entry.
7025 if (DefinitionRequired && !Pos.first->second) {
7026 Pos.first->second = true;
7027 } else {
7028 // Otherwise, we can early exit.
7029 return;
7030 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007031 }
7032
7033 // Local classes need to have their virtual members marked
7034 // immediately. For all other classes, we mark their virtual members
7035 // at the end of the translation unit.
7036 if (Class->isLocalClass())
7037 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007038 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007039 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007040}
7041
Douglas Gregor88d292c2010-05-13 16:44:06 +00007042bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007043 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007044 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007045
Douglas Gregor88d292c2010-05-13 16:44:06 +00007046 // Note: The VTableUses vector could grow as a result of marking
7047 // the members of a class as "used", so we check the size each
7048 // time through the loop and prefer indices (with are stable) to
7049 // iterators (which are not).
7050 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007051 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007052 if (!Class)
7053 continue;
7054
7055 SourceLocation Loc = VTableUses[I].second;
7056
7057 // If this class has a key function, but that key function is
7058 // defined in another translation unit, we don't need to emit the
7059 // vtable even though we're using it.
7060 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007061 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007062 switch (KeyFunction->getTemplateSpecializationKind()) {
7063 case TSK_Undeclared:
7064 case TSK_ExplicitSpecialization:
7065 case TSK_ExplicitInstantiationDeclaration:
7066 // The key function is in another translation unit.
7067 continue;
7068
7069 case TSK_ExplicitInstantiationDefinition:
7070 case TSK_ImplicitInstantiation:
7071 // We will be instantiating the key function.
7072 break;
7073 }
7074 } else if (!KeyFunction) {
7075 // If we have a class with no key function that is the subject
7076 // of an explicit instantiation declaration, suppress the
7077 // vtable; it will live with the explicit instantiation
7078 // definition.
7079 bool IsExplicitInstantiationDeclaration
7080 = Class->getTemplateSpecializationKind()
7081 == TSK_ExplicitInstantiationDeclaration;
7082 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7083 REnd = Class->redecls_end();
7084 R != REnd; ++R) {
7085 TemplateSpecializationKind TSK
7086 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7087 if (TSK == TSK_ExplicitInstantiationDeclaration)
7088 IsExplicitInstantiationDeclaration = true;
7089 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7090 IsExplicitInstantiationDeclaration = false;
7091 break;
7092 }
7093 }
7094
7095 if (IsExplicitInstantiationDeclaration)
7096 continue;
7097 }
7098
7099 // Mark all of the virtual members of this class as referenced, so
7100 // that we can build a vtable. Then, tell the AST consumer that a
7101 // vtable for this class is required.
7102 MarkVirtualMembersReferenced(Loc, Class);
7103 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7104 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7105
7106 // Optionally warn if we're emitting a weak vtable.
7107 if (Class->getLinkage() == ExternalLinkage &&
7108 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007109 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007110 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7111 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007112 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007113 VTableUses.clear();
7114
Anders Carlsson82fccd02009-12-07 08:24:59 +00007115 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007116}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007117
Rafael Espindola5b334082010-03-26 00:36:59 +00007118void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7119 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007120 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7121 e = RD->method_end(); i != e; ++i) {
7122 CXXMethodDecl *MD = *i;
7123
7124 // C++ [basic.def.odr]p2:
7125 // [...] A virtual member function is used if it is not pure. [...]
7126 if (MD->isVirtual() && !MD->isPure())
7127 MarkDeclarationReferenced(Loc, MD);
7128 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007129
7130 // Only classes that have virtual bases need a VTT.
7131 if (RD->getNumVBases() == 0)
7132 return;
7133
7134 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7135 e = RD->bases_end(); i != e; ++i) {
7136 const CXXRecordDecl *Base =
7137 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007138 if (Base->getNumVBases() == 0)
7139 continue;
7140 MarkVirtualMembersReferenced(Loc, Base);
7141 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007142}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007143
7144/// SetIvarInitializers - This routine builds initialization ASTs for the
7145/// Objective-C implementation whose ivars need be initialized.
7146void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7147 if (!getLangOptions().CPlusPlus)
7148 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007149 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007150 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7151 CollectIvarsToConstructOrDestruct(OID, ivars);
7152 if (ivars.empty())
7153 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007154 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007155 for (unsigned i = 0; i < ivars.size(); i++) {
7156 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007157 if (Field->isInvalidDecl())
7158 continue;
7159
Alexis Hunt1d792652011-01-08 20:30:50 +00007160 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007161 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7162 InitializationKind InitKind =
7163 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7164
7165 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007166 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007167 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007168 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007169 // Note, MemberInit could actually come back empty if no initialization
7170 // is required (e.g., because it would call a trivial default constructor)
7171 if (!MemberInit.get() || MemberInit.isInvalid())
7172 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007173
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007174 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007175 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7176 SourceLocation(),
7177 MemberInit.takeAs<Expr>(),
7178 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007179 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007180
7181 // Be sure that the destructor is accessible and is marked as referenced.
7182 if (const RecordType *RecordTy
7183 = Context.getBaseElementType(Field->getType())
7184 ->getAs<RecordType>()) {
7185 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007186 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007187 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7188 CheckDestructorAccess(Field->getLocation(), Destructor,
7189 PDiag(diag::err_access_dtor_ivar)
7190 << Context.getBaseElementType(Field->getType()));
7191 }
7192 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007193 }
7194 ObjCImplementation->setIvarInitializers(Context,
7195 AllToInit.data(), AllToInit.size());
7196 }
7197}