blob: 3a87cfd9665ce5576724965e0b13f1611050b507 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000031#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000033#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000035#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000036#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000037
38using namespace clang;
39
Chris Lattner58258242008-04-10 02:22:51 +000040//===----------------------------------------------------------------------===//
41// CheckDefaultArgumentVisitor
42//===----------------------------------------------------------------------===//
43
Chris Lattnerb0d38442008-04-12 23:52:44 +000044namespace {
45 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
46 /// the default argument of a parameter to determine whether it
47 /// contains any ill-formed subexpressions. For example, this will
48 /// diagnose the use of local variables or parameters within the
49 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000050 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000051 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 Expr *DefaultArg;
53 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 public:
Mike Stump11289f42009-09-09 15:08:12 +000056 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 bool VisitExpr(Expr *Node);
60 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000061 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 };
Chris Lattner58258242008-04-10 02:22:51 +000063
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 /// VisitExpr - Visit all of the children of this expression.
65 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
66 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000067 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000068 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000291
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000292 unsigned DiagDefaultParamID =
293 diag::err_param_default_argument_redefinition;
294
295 // MSVC accepts that default parameters be redefined for member functions
296 // of template class. The new default parameter's value is ignored.
297 Invalid = true;
298 if (getLangOptions().Microsoft) {
299 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
300 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000301 // Merge the old default argument into the new parameter.
302 NewParam->setHasInheritedDefaultArg();
303 if (OldParam->hasUninstantiatedDefaultArg())
304 NewParam->setUninstantiatedDefaultArg(
305 OldParam->getUninstantiatedDefaultArg());
306 else
307 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000308 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000309 Invalid = false;
310 }
311 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000312
Francois Pichet8cb243a2011-04-10 04:58:30 +0000313 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
314 // hint here. Alternatively, we could walk the type-source information
315 // for NewParam to find the last source location in the type... but it
316 // isn't worth the effort right now. This is the kind of test case that
317 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000318 // int f(int);
319 // void g(int (*fp)(int) = f);
320 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000321 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000322 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000323
324 // Look for the function declaration where the default argument was
325 // actually written, which may be a declaration prior to Old.
326 for (FunctionDecl *Older = Old->getPreviousDeclaration();
327 Older; Older = Older->getPreviousDeclaration()) {
328 if (!Older->getParamDecl(p)->hasDefaultArg())
329 break;
330
331 OldParam = Older->getParamDecl(p);
332 }
333
334 Diag(OldParam->getLocation(), diag::note_previous_definition)
335 << OldParam->getDefaultArgRange();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000336 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000337 // Merge the old default argument into the new parameter.
338 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000339 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000340 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000341 if (OldParam->hasUninstantiatedDefaultArg())
342 NewParam->setUninstantiatedDefaultArg(
343 OldParam->getUninstantiatedDefaultArg());
344 else
John McCalle61b02b2010-05-04 01:53:42 +0000345 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000346 } else if (NewParam->hasDefaultArg()) {
347 if (New->getDescribedFunctionTemplate()) {
348 // Paragraph 4, quoted above, only applies to non-template functions.
349 Diag(NewParam->getLocation(),
350 diag::err_param_default_argument_template_redecl)
351 << NewParam->getDefaultArgRange();
352 Diag(Old->getLocation(), diag::note_template_prev_declaration)
353 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000354 } else if (New->getTemplateSpecializationKind()
355 != TSK_ImplicitInstantiation &&
356 New->getTemplateSpecializationKind() != TSK_Undeclared) {
357 // C++ [temp.expr.spec]p21:
358 // Default function arguments shall not be specified in a declaration
359 // or a definition for one of the following explicit specializations:
360 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000361 // - the explicit specialization of a member function template;
362 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000363 // template where the class template specialization to which the
364 // member function specialization belongs is implicitly
365 // instantiated.
366 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
367 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
368 << New->getDeclName()
369 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000370 } else if (New->getDeclContext()->isDependentContext()) {
371 // C++ [dcl.fct.default]p6 (DR217):
372 // Default arguments for a member function of a class template shall
373 // be specified on the initial declaration of the member function
374 // within the class template.
375 //
376 // Reading the tea leaves a bit in DR217 and its reference to DR205
377 // leads me to the conclusion that one cannot add default function
378 // arguments for an out-of-line definition of a member function of a
379 // dependent type.
380 int WhichKind = 2;
381 if (CXXRecordDecl *Record
382 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
383 if (Record->getDescribedClassTemplate())
384 WhichKind = 0;
385 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
386 WhichKind = 1;
387 else
388 WhichKind = 2;
389 }
390
391 Diag(NewParam->getLocation(),
392 diag::err_param_default_argument_member_template_redecl)
393 << WhichKind
394 << NewParam->getDefaultArgRange();
395 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000396 }
397 }
398
Douglas Gregorf40863c2010-02-12 07:32:17 +0000399 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000400 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000401
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000402 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000403}
404
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000405/// \brief Merge the exception specifications of two variable declarations.
406///
407/// This is called when there's a redeclaration of a VarDecl. The function
408/// checks if the redeclaration might have an exception specification and
409/// validates compatibility and merges the specs if necessary.
410void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
411 // Shortcut if exceptions are disabled.
412 if (!getLangOptions().CXXExceptions)
413 return;
414
415 assert(Context.hasSameType(New->getType(), Old->getType()) &&
416 "Should only be called if types are otherwise the same.");
417
418 QualType NewType = New->getType();
419 QualType OldType = Old->getType();
420
421 // We're only interested in pointers and references to functions, as well
422 // as pointers to member functions.
423 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
424 NewType = R->getPointeeType();
425 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
426 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
427 NewType = P->getPointeeType();
428 OldType = OldType->getAs<PointerType>()->getPointeeType();
429 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
430 NewType = M->getPointeeType();
431 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
432 }
433
434 if (!NewType->isFunctionProtoType())
435 return;
436
437 // There's lots of special cases for functions. For function pointers, system
438 // libraries are hopefully not as broken so that we don't need these
439 // workarounds.
440 if (CheckEquivalentExceptionSpec(
441 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
442 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
443 New->setInvalidDecl();
444 }
445}
446
Chris Lattner199abbc2008-04-08 05:04:30 +0000447/// CheckCXXDefaultArguments - Verify that the default arguments for a
448/// function declaration are well-formed according to C++
449/// [dcl.fct.default].
450void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
451 unsigned NumParams = FD->getNumParams();
452 unsigned p;
453
454 // Find first parameter with a default argument
455 for (p = 0; p < NumParams; ++p) {
456 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000457 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000458 break;
459 }
460
461 // C++ [dcl.fct.default]p4:
462 // In a given function declaration, all parameters
463 // subsequent to a parameter with a default argument shall
464 // have default arguments supplied in this or previous
465 // declarations. A default argument shall not be redefined
466 // by a later declaration (not even to the same value).
467 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000468 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000469 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000470 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000471 if (Param->isInvalidDecl())
472 /* We already complained about this parameter. */;
473 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000474 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000475 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000476 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000477 else
Mike Stump11289f42009-09-09 15:08:12 +0000478 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner199abbc2008-04-08 05:04:30 +0000481 LastMissingDefaultArg = p;
482 }
483 }
484
485 if (LastMissingDefaultArg > 0) {
486 // Some default arguments were missing. Clear out all of the
487 // default arguments up to (and including) the last missing
488 // default argument, so that we leave the function parameters
489 // in a semantically valid state.
490 for (p = 0; p <= LastMissingDefaultArg; ++p) {
491 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000492 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000493 Param->setDefaultArg(0);
494 }
495 }
496 }
497}
Douglas Gregor556877c2008-04-13 21:30:24 +0000498
Douglas Gregor61956c42008-10-31 09:07:45 +0000499/// isCurrentClassName - Determine whether the identifier II is the
500/// name of the class type currently being defined. In the case of
501/// nested classes, this will only return true if II is the name of
502/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000503bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
504 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000505 assert(getLangOptions().CPlusPlus && "No class names in C!");
506
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000507 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000508 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000509 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000510 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
511 } else
512 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
513
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000514 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000515 return &II == CurDecl->getIdentifier();
516 else
517 return false;
518}
519
Mike Stump11289f42009-09-09 15:08:12 +0000520/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000521///
522/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
523/// and returns NULL otherwise.
524CXXBaseSpecifier *
525Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
526 SourceRange SpecifierRange,
527 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000528 TypeSourceInfo *TInfo,
529 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000530 QualType BaseType = TInfo->getType();
531
Douglas Gregor463421d2009-03-03 04:44:36 +0000532 // C++ [class.union]p1:
533 // A union shall not have base classes.
534 if (Class->isUnion()) {
535 Diag(Class->getLocation(), diag::err_base_clause_on_union)
536 << SpecifierRange;
537 return 0;
538 }
539
Douglas Gregor752a5952011-01-03 22:36:02 +0000540 if (EllipsisLoc.isValid() &&
541 !TInfo->getType()->containsUnexpandedParameterPack()) {
542 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
543 << TInfo->getTypeLoc().getSourceRange();
544 EllipsisLoc = SourceLocation();
545 }
546
Douglas Gregor463421d2009-03-03 04:44:36 +0000547 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000548 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000549 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000550 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000551
552 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000553
554 // Base specifiers must be record types.
555 if (!BaseType->isRecordType()) {
556 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
557 return 0;
558 }
559
560 // C++ [class.union]p1:
561 // A union shall not be used as a base class.
562 if (BaseType->isUnionType()) {
563 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
564 return 0;
565 }
566
567 // C++ [class.derived]p2:
568 // The class-name in a base-specifier shall not be an incompletely
569 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000570 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000571 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000572 << SpecifierRange)) {
573 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000574 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000575 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000576
Eli Friedmanc96d4962009-08-15 21:55:26 +0000577 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000578 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000579 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000580 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000581 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000582 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
583 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000584
Anders Carlsson65c76d32011-03-25 14:55:14 +0000585 // C++ [class]p3:
586 // If a class is marked final and it appears as a base-type-specifier in
587 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000588 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000589 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
590 << CXXBaseDecl->getDeclName();
591 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
592 << CXXBaseDecl->getDeclName();
593 return 0;
594 }
595
John McCall3696dcb2010-08-17 07:23:57 +0000596 if (BaseDecl->isInvalidDecl())
597 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000598
599 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000600 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000601 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000602 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000603}
604
Douglas Gregor556877c2008-04-13 21:30:24 +0000605/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
606/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000607/// example:
608/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000609/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000610BaseResult
John McCall48871652010-08-21 09:40:31 +0000611Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000612 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000613 ParsedType basetype, SourceLocation BaseLoc,
614 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000615 if (!classdecl)
616 return true;
617
Douglas Gregorc40290e2009-03-09 23:48:35 +0000618 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000619 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000620 if (!Class)
621 return true;
622
Nick Lewycky19b9f952010-07-26 16:56:01 +0000623 TypeSourceInfo *TInfo = 0;
624 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000625
Douglas Gregor752a5952011-01-03 22:36:02 +0000626 if (EllipsisLoc.isInvalid() &&
627 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000628 UPPC_BaseType))
629 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000630
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000632 Virtual, Access, TInfo,
633 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000634 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000635
Douglas Gregor463421d2009-03-03 04:44:36 +0000636 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000637}
Douglas Gregor556877c2008-04-13 21:30:24 +0000638
Douglas Gregor463421d2009-03-03 04:44:36 +0000639/// \brief Performs the actual work of attaching the given base class
640/// specifiers to a C++ class.
641bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
642 unsigned NumBases) {
643 if (NumBases == 0)
644 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000645
646 // Used to keep track of which base types we have already seen, so
647 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000648 // that the key is always the unqualified canonical type of the base
649 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000650 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
651
652 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000653 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000654 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000655 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000656 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000658 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000659 if (!Class->hasObjectMember()) {
660 if (const RecordType *FDTTy =
661 NewBaseType.getTypePtr()->getAs<RecordType>())
662 if (FDTTy->getDecl()->hasObjectMember())
663 Class->setHasObjectMember(true);
664 }
665
Douglas Gregor29a92472008-10-22 17:49:05 +0000666 if (KnownBaseTypes[NewBaseType]) {
667 // C++ [class.mi]p3:
668 // A class shall not be specified as a direct base class of a
669 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000670 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000671 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000672 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000673 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000674
675 // Delete the duplicate base class specifier; we're going to
676 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000677 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000678
679 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000680 } else {
681 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000682 KnownBaseTypes[NewBaseType] = Bases[idx];
683 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000684 }
685 }
686
687 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000688 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000689
690 // Delete the remaining (good) base class specifiers, since their
691 // data has been copied into the CXXRecordDecl.
692 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000693 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000694
695 return Invalid;
696}
697
698/// ActOnBaseSpecifiers - Attach the given base specifiers to the
699/// class, after checking whether there are any duplicate base
700/// classes.
John McCall48871652010-08-21 09:40:31 +0000701void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000702 unsigned NumBases) {
703 if (!ClassDecl || !Bases || !NumBases)
704 return;
705
706 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000707 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000708 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000709}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000710
John McCalle78aac42010-03-10 03:28:59 +0000711static CXXRecordDecl *GetClassForType(QualType T) {
712 if (const RecordType *RT = T->getAs<RecordType>())
713 return cast<CXXRecordDecl>(RT->getDecl());
714 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
715 return ICT->getDecl();
716 else
717 return 0;
718}
719
Douglas Gregor36d1b142009-10-06 17:59:45 +0000720/// \brief Determine whether the type \p Derived is a C++ class that is
721/// derived from the type \p Base.
722bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
723 if (!getLangOptions().CPlusPlus)
724 return false;
John McCalle78aac42010-03-10 03:28:59 +0000725
726 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
727 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000728 return false;
729
John McCalle78aac42010-03-10 03:28:59 +0000730 CXXRecordDecl *BaseRD = GetClassForType(Base);
731 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000732 return false;
733
John McCall67da35c2010-02-04 22:26:26 +0000734 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
735 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000736}
737
738/// \brief Determine whether the type \p Derived is a C++ class that is
739/// derived from the type \p Base.
740bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
741 if (!getLangOptions().CPlusPlus)
742 return false;
743
John McCalle78aac42010-03-10 03:28:59 +0000744 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
745 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000746 return false;
747
John McCalle78aac42010-03-10 03:28:59 +0000748 CXXRecordDecl *BaseRD = GetClassForType(Base);
749 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000750 return false;
751
Douglas Gregor36d1b142009-10-06 17:59:45 +0000752 return DerivedRD->isDerivedFrom(BaseRD, Paths);
753}
754
Anders Carlssona70cff62010-04-24 19:06:50 +0000755void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000756 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000757 assert(BasePathArray.empty() && "Base path array must be empty!");
758 assert(Paths.isRecordingPaths() && "Must record paths!");
759
760 const CXXBasePath &Path = Paths.front();
761
762 // We first go backward and check if we have a virtual base.
763 // FIXME: It would be better if CXXBasePath had the base specifier for
764 // the nearest virtual base.
765 unsigned Start = 0;
766 for (unsigned I = Path.size(); I != 0; --I) {
767 if (Path[I - 1].Base->isVirtual()) {
768 Start = I - 1;
769 break;
770 }
771 }
772
773 // Now add all bases.
774 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000775 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000776}
777
Douglas Gregor88d292c2010-05-13 16:44:06 +0000778/// \brief Determine whether the given base path includes a virtual
779/// base class.
John McCallcf142162010-08-07 06:22:56 +0000780bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
781 for (CXXCastPath::const_iterator B = BasePath.begin(),
782 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000783 B != BEnd; ++B)
784 if ((*B)->isVirtual())
785 return true;
786
787 return false;
788}
789
Douglas Gregor36d1b142009-10-06 17:59:45 +0000790/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
791/// conversion (where Derived and Base are class types) is
792/// well-formed, meaning that the conversion is unambiguous (and
793/// that all of the base classes are accessible). Returns true
794/// and emits a diagnostic if the code is ill-formed, returns false
795/// otherwise. Loc is the location where this routine should point to
796/// if there is an error, and Range is the source range to highlight
797/// if there is an error.
798bool
799Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000800 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000801 unsigned AmbigiousBaseConvID,
802 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000803 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000804 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000805 // First, determine whether the path from Derived to Base is
806 // ambiguous. This is slightly more expensive than checking whether
807 // the Derived to Base conversion exists, because here we need to
808 // explore multiple paths to determine if there is an ambiguity.
809 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
810 /*DetectVirtual=*/false);
811 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
812 assert(DerivationOkay &&
813 "Can only be used with a derived-to-base conversion");
814 (void)DerivationOkay;
815
816 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000817 if (InaccessibleBaseID) {
818 // Check that the base class can be accessed.
819 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
820 InaccessibleBaseID)) {
821 case AR_inaccessible:
822 return true;
823 case AR_accessible:
824 case AR_dependent:
825 case AR_delayed:
826 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000827 }
John McCall5b0829a2010-02-10 09:31:12 +0000828 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000829
830 // Build a base path if necessary.
831 if (BasePath)
832 BuildBasePathArray(Paths, *BasePath);
833 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000834 }
835
836 // We know that the derived-to-base conversion is ambiguous, and
837 // we're going to produce a diagnostic. Perform the derived-to-base
838 // search just one more time to compute all of the possible paths so
839 // that we can print them out. This is more expensive than any of
840 // the previous derived-to-base checks we've done, but at this point
841 // performance isn't as much of an issue.
842 Paths.clear();
843 Paths.setRecordingPaths(true);
844 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
845 assert(StillOkay && "Can only be used with a derived-to-base conversion");
846 (void)StillOkay;
847
848 // Build up a textual representation of the ambiguous paths, e.g.,
849 // D -> B -> A, that will be used to illustrate the ambiguous
850 // conversions in the diagnostic. We only print one of the paths
851 // to each base class subobject.
852 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
853
854 Diag(Loc, AmbigiousBaseConvID)
855 << Derived << Base << PathDisplayStr << Range << Name;
856 return true;
857}
858
859bool
860Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000861 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000862 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000863 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000864 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000865 IgnoreAccess ? 0
866 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000867 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000868 Loc, Range, DeclarationName(),
869 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000870}
871
872
873/// @brief Builds a string representing ambiguous paths from a
874/// specific derived class to different subobjects of the same base
875/// class.
876///
877/// This function builds a string that can be used in error messages
878/// to show the different paths that one can take through the
879/// inheritance hierarchy to go from the derived class to different
880/// subobjects of a base class. The result looks something like this:
881/// @code
882/// struct D -> struct B -> struct A
883/// struct D -> struct C -> struct A
884/// @endcode
885std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
886 std::string PathDisplayStr;
887 std::set<unsigned> DisplayedPaths;
888 for (CXXBasePaths::paths_iterator Path = Paths.begin();
889 Path != Paths.end(); ++Path) {
890 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
891 // We haven't displayed a path to this particular base
892 // class subobject yet.
893 PathDisplayStr += "\n ";
894 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
895 for (CXXBasePath::const_iterator Element = Path->begin();
896 Element != Path->end(); ++Element)
897 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
898 }
899 }
900
901 return PathDisplayStr;
902}
903
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000904//===----------------------------------------------------------------------===//
905// C++ class member Handling
906//===----------------------------------------------------------------------===//
907
Abramo Bagnarad7340582010-06-05 05:09:32 +0000908/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000909Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
910 SourceLocation ASLoc,
911 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000912 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000913 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000914 ASLoc, ColonLoc);
915 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000916 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000917}
918
Anders Carlssonfd835532011-01-20 05:57:14 +0000919/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000920void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000921 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
922 if (!MD || !MD->isVirtual())
923 return;
924
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000925 if (MD->isDependentContext())
926 return;
927
Anders Carlssonfd835532011-01-20 05:57:14 +0000928 // C++0x [class.virtual]p3:
929 // If a virtual function is marked with the virt-specifier override and does
930 // not override a member function of a base class,
931 // the program is ill-formed.
932 bool HasOverriddenMethods =
933 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +0000934 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000935 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000936 diag::err_function_marked_override_not_overriding)
937 << MD->getDeclName();
938 return;
939 }
940}
941
Anders Carlsson3f610c72011-01-20 16:25:36 +0000942/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
943/// function overrides a virtual member function marked 'final', according to
944/// C++0x [class.virtual]p3.
945bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
946 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +0000947 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +0000948 return false;
949
950 Diag(New->getLocation(), diag::err_final_function_overridden)
951 << New->getDeclName();
952 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
953 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +0000954}
955
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000956/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
957/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
958/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000959/// any.
John McCall48871652010-08-21 09:40:31 +0000960Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000961Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000962 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000963 ExprTy *BW, const VirtSpecifiers &VS,
964 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000965 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000966 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000967 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
968 DeclarationName Name = NameInfo.getName();
969 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000970
971 // For anonymous bitfields, the location should point to the type.
972 if (Loc.isInvalid())
973 Loc = D.getSourceRange().getBegin();
974
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000975 Expr *BitWidth = static_cast<Expr*>(BW);
976 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000977
John McCallb1cd7da2010-06-04 08:34:12 +0000978 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000979 assert(!DS.isFriendSpecified());
980
John McCallb1cd7da2010-06-04 08:34:12 +0000981 bool isFunc = false;
982 if (D.isFunctionDeclarator())
983 isFunc = true;
984 else if (D.getNumTypeObjects() == 0 &&
985 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000986 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000987 isFunc = TDType->isFunctionType();
988 }
989
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000990 // C++ 9.2p6: A member shall not be declared to have automatic storage
991 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000992 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
993 // data members and cannot be applied to names declared const or static,
994 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000995 switch (DS.getStorageClassSpec()) {
996 case DeclSpec::SCS_unspecified:
997 case DeclSpec::SCS_typedef:
998 case DeclSpec::SCS_static:
999 // FALL THROUGH.
1000 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001001 case DeclSpec::SCS_mutable:
1002 if (isFunc) {
1003 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001004 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001005 else
Chris Lattner3b054132008-11-19 05:08:23 +00001006 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001007
Sebastian Redl8071edb2008-11-17 23:24:37 +00001008 // FIXME: It would be nicer if the keyword was ignored only for this
1009 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001010 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001011 }
1012 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001013 default:
1014 if (DS.getStorageClassSpecLoc().isValid())
1015 Diag(DS.getStorageClassSpecLoc(),
1016 diag::err_storageclass_invalid_for_member);
1017 else
1018 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1019 D.getMutableDeclSpec().ClearStorageClassSpecs();
1020 }
1021
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001022 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1023 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001024 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001025
1026 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001027 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001028 CXXScopeSpec &SS = D.getCXXScopeSpec();
1029
1030
1031 if (SS.isSet() && !SS.isInvalid()) {
1032 // The user provided a superfluous scope specifier inside a class
1033 // definition:
1034 //
1035 // class X {
1036 // int X::member;
1037 // };
1038 DeclContext *DC = 0;
1039 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1040 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1041 << Name << FixItHint::CreateRemoval(SS.getRange());
1042 else
1043 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1044 << Name << SS.getRange();
1045
1046 SS.clear();
1047 }
1048
Douglas Gregor3447e762009-08-20 22:52:58 +00001049 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001050 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001051 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1052 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001053 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001054 } else {
John McCall48871652010-08-21 09:40:31 +00001055 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001056 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001057 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001058 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001059
1060 // Non-instance-fields can't have a bitfield.
1061 if (BitWidth) {
1062 if (Member->isInvalidDecl()) {
1063 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001064 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001065 // C++ 9.6p3: A bit-field shall not be a static member.
1066 // "static member 'A' cannot be a bit-field"
1067 Diag(Loc, diag::err_static_not_bitfield)
1068 << Name << BitWidth->getSourceRange();
1069 } else if (isa<TypedefDecl>(Member)) {
1070 // "typedef member 'x' cannot be a bit-field"
1071 Diag(Loc, diag::err_typedef_not_bitfield)
1072 << Name << BitWidth->getSourceRange();
1073 } else {
1074 // A function typedef ("typedef int f(); f a;").
1075 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1076 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001077 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001078 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattnerd26760a2009-03-05 23:01:03 +00001081 BitWidth = 0;
1082 Member->setInvalidDecl();
1083 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001084
1085 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Douglas Gregor3447e762009-08-20 22:52:58 +00001087 // If we have declared a member function template, set the access of the
1088 // templated declaration as well.
1089 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1090 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001091 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001092
Anders Carlsson13a69102011-01-20 04:34:22 +00001093 if (VS.isOverrideSpecified()) {
1094 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1095 if (!MD || !MD->isVirtual()) {
1096 Diag(Member->getLocStart(),
1097 diag::override_keyword_only_allowed_on_virtual_member_functions)
1098 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001099 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001100 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001101 }
1102 if (VS.isFinalSpecified()) {
1103 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1104 if (!MD || !MD->isVirtual()) {
1105 Diag(Member->getLocStart(),
1106 diag::override_keyword_only_allowed_on_virtual_member_functions)
1107 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001108 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001109 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001110 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001111
Douglas Gregorf2f08062011-03-08 17:10:18 +00001112 if (VS.getLastLocation().isValid()) {
1113 // Update the end location of a method that has a virt-specifiers.
1114 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1115 MD->setRangeEnd(VS.getLastLocation());
1116 }
1117
Anders Carlssonc87f8612011-01-20 06:29:02 +00001118 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001119
Douglas Gregor92751d42008-11-17 22:58:34 +00001120 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001121
Douglas Gregor0c880302009-03-11 23:00:04 +00001122 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001123 AddInitializerToDecl(Member, Init, false,
1124 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001125 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001126 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001127
Richard Smithb2bc2e62011-02-21 20:05:19 +00001128 FinalizeDeclaration(Member);
1129
John McCall25849ca2011-02-15 07:12:36 +00001130 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001131 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001132 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001133}
1134
Douglas Gregor15e77a22009-12-31 09:10:24 +00001135/// \brief Find the direct and/or virtual base specifiers that
1136/// correspond to the given base type, for use in base initialization
1137/// within a constructor.
1138static bool FindBaseInitializer(Sema &SemaRef,
1139 CXXRecordDecl *ClassDecl,
1140 QualType BaseType,
1141 const CXXBaseSpecifier *&DirectBaseSpec,
1142 const CXXBaseSpecifier *&VirtualBaseSpec) {
1143 // First, check for a direct base class.
1144 DirectBaseSpec = 0;
1145 for (CXXRecordDecl::base_class_const_iterator Base
1146 = ClassDecl->bases_begin();
1147 Base != ClassDecl->bases_end(); ++Base) {
1148 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1149 // We found a direct base of this type. That's what we're
1150 // initializing.
1151 DirectBaseSpec = &*Base;
1152 break;
1153 }
1154 }
1155
1156 // Check for a virtual base class.
1157 // FIXME: We might be able to short-circuit this if we know in advance that
1158 // there are no virtual bases.
1159 VirtualBaseSpec = 0;
1160 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1161 // We haven't found a base yet; search the class hierarchy for a
1162 // virtual base class.
1163 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1164 /*DetectVirtual=*/false);
1165 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1166 BaseType, Paths)) {
1167 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1168 Path != Paths.end(); ++Path) {
1169 if (Path->back().Base->isVirtual()) {
1170 VirtualBaseSpec = Path->back().Base;
1171 break;
1172 }
1173 }
1174 }
1175 }
1176
1177 return DirectBaseSpec || VirtualBaseSpec;
1178}
1179
Douglas Gregore8381c02008-11-05 04:29:56 +00001180/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001181MemInitResult
John McCall48871652010-08-21 09:40:31 +00001182Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001183 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001184 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001185 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001186 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001187 SourceLocation IdLoc,
1188 SourceLocation LParenLoc,
1189 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001190 SourceLocation RParenLoc,
1191 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001192 if (!ConstructorD)
1193 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001194
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001195 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001196
1197 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001198 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001199 if (!Constructor) {
1200 // The user wrote a constructor initializer on a function that is
1201 // not a C++ constructor. Ignore the error for now, because we may
1202 // have more member initializers coming; we'll diagnose it just
1203 // once in ActOnMemInitializers.
1204 return true;
1205 }
1206
1207 CXXRecordDecl *ClassDecl = Constructor->getParent();
1208
1209 // C++ [class.base.init]p2:
1210 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001211 // constructor's class and, if not found in that scope, are looked
1212 // up in the scope containing the constructor's definition.
1213 // [Note: if the constructor's class contains a member with the
1214 // same name as a direct or virtual base class of the class, a
1215 // mem-initializer-id naming the member or base class and composed
1216 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001217 // mem-initializer-id for the hidden base class may be specified
1218 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001219 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001220 // Look for a member, first.
1221 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001222 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001223 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001224 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001225 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001226
Douglas Gregor44e7df62011-01-04 00:32:56 +00001227 if (Member) {
1228 if (EllipsisLoc.isValid())
1229 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1230 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1231
Francois Pichetd583da02010-12-04 09:14:42 +00001232 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001233 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001234 }
1235
Francois Pichetd583da02010-12-04 09:14:42 +00001236 // Handle anonymous union case.
1237 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001238 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1239 if (EllipsisLoc.isValid())
1240 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1241 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1242
Francois Pichetd583da02010-12-04 09:14:42 +00001243 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1244 NumArgs, IdLoc,
1245 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001246 }
Francois Pichetd583da02010-12-04 09:14:42 +00001247 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001248 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001249 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001250 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001251 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001252
1253 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001254 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001255 } else {
1256 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1257 LookupParsedName(R, S, &SS);
1258
1259 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1260 if (!TyD) {
1261 if (R.isAmbiguous()) return true;
1262
John McCallda6841b2010-04-09 19:01:14 +00001263 // We don't want access-control diagnostics here.
1264 R.suppressDiagnostics();
1265
Douglas Gregora3b624a2010-01-19 06:46:48 +00001266 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1267 bool NotUnknownSpecialization = false;
1268 DeclContext *DC = computeDeclContext(SS, false);
1269 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1270 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1271
1272 if (!NotUnknownSpecialization) {
1273 // When the scope specifier can refer to a member of an unknown
1274 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001275 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1276 SS.getWithLocInContext(Context),
1277 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001278 if (BaseType.isNull())
1279 return true;
1280
Douglas Gregora3b624a2010-01-19 06:46:48 +00001281 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001282 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001283 }
1284 }
1285
Douglas Gregor15e77a22009-12-31 09:10:24 +00001286 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001287 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001288 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1289 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001290 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001291 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001292 // We have found a non-static data member with a similar
1293 // name to what was typed; complain and initialize that
1294 // member.
1295 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1296 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001297 << FixItHint::CreateReplacement(R.getNameLoc(),
1298 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001299 Diag(Member->getLocation(), diag::note_previous_decl)
1300 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001301
1302 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1303 LParenLoc, RParenLoc);
1304 }
1305 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1306 const CXXBaseSpecifier *DirectBaseSpec;
1307 const CXXBaseSpecifier *VirtualBaseSpec;
1308 if (FindBaseInitializer(*this, ClassDecl,
1309 Context.getTypeDeclType(Type),
1310 DirectBaseSpec, VirtualBaseSpec)) {
1311 // We have found a direct or virtual base class with a
1312 // similar name to what was typed; complain and initialize
1313 // that base class.
1314 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1315 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001316 << FixItHint::CreateReplacement(R.getNameLoc(),
1317 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001318
1319 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1320 : VirtualBaseSpec;
1321 Diag(BaseSpec->getSourceRange().getBegin(),
1322 diag::note_base_class_specified_here)
1323 << BaseSpec->getType()
1324 << BaseSpec->getSourceRange();
1325
Douglas Gregor15e77a22009-12-31 09:10:24 +00001326 TyD = Type;
1327 }
1328 }
1329 }
1330
Douglas Gregora3b624a2010-01-19 06:46:48 +00001331 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001332 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1333 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1334 return true;
1335 }
John McCallb5a0d312009-12-21 10:41:20 +00001336 }
1337
Douglas Gregora3b624a2010-01-19 06:46:48 +00001338 if (BaseType.isNull()) {
1339 BaseType = Context.getTypeDeclType(TyD);
1340 if (SS.isSet()) {
1341 NestedNameSpecifier *Qualifier =
1342 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001343
Douglas Gregora3b624a2010-01-19 06:46:48 +00001344 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001345 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001346 }
John McCallb5a0d312009-12-21 10:41:20 +00001347 }
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
John McCallbcd03502009-12-07 02:54:59 +00001350 if (!TInfo)
1351 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001352
John McCallbcd03502009-12-07 02:54:59 +00001353 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001354 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001355}
1356
John McCalle22a04a2009-11-04 23:02:40 +00001357/// Checks an initializer expression for use of uninitialized fields, such as
1358/// containing the field that is being initialized. Returns true if there is an
1359/// uninitialized field was used an updates the SourceLocation parameter; false
1360/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001361static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001362 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001363 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001364 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1365
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001366 if (isa<CallExpr>(S)) {
1367 // Do not descend into function calls or constructors, as the use
1368 // of an uninitialized field may be valid. One would have to inspect
1369 // the contents of the function/ctor to determine if it is safe or not.
1370 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1371 // may be safe, depending on what the function/ctor does.
1372 return false;
1373 }
1374 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1375 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001376
1377 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1378 // The member expression points to a static data member.
1379 assert(VD->isStaticDataMember() &&
1380 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001381 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001382 return false;
1383 }
1384
1385 if (isa<EnumConstantDecl>(RhsField)) {
1386 // The member expression points to an enum.
1387 return false;
1388 }
1389
John McCalle22a04a2009-11-04 23:02:40 +00001390 if (RhsField == LhsField) {
1391 // Initializing a field with itself. Throw a warning.
1392 // But wait; there are exceptions!
1393 // Exception #1: The field may not belong to this record.
1394 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001395 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001396 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1397 // Even though the field matches, it does not belong to this record.
1398 return false;
1399 }
1400 // None of the exceptions triggered; return true to indicate an
1401 // uninitialized field was used.
1402 *L = ME->getMemberLoc();
1403 return true;
1404 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001405 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001406 // sizeof/alignof doesn't reference contents, do not warn.
1407 return false;
1408 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1409 // address-of doesn't reference contents (the pointer may be dereferenced
1410 // in the same expression but it would be rare; and weird).
1411 if (UOE->getOpcode() == UO_AddrOf)
1412 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001413 }
John McCall8322c3a2011-02-13 04:07:26 +00001414 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001415 if (!*it) {
1416 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001417 continue;
1418 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001419 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1420 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001421 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001422 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001423}
1424
John McCallfaf5fb42010-08-26 23:41:50 +00001425MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001426Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001427 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001428 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001429 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001430 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1431 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1432 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001433 "Member must be a FieldDecl or IndirectFieldDecl");
1434
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001435 if (Member->isInvalidDecl())
1436 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001437
John McCalle22a04a2009-11-04 23:02:40 +00001438 // Diagnose value-uses of fields to initialize themselves, e.g.
1439 // foo(foo)
1440 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001441 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001442 for (unsigned i = 0; i < NumArgs; ++i) {
1443 SourceLocation L;
1444 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1445 // FIXME: Return true in the case when other fields are used before being
1446 // uninitialized. For example, let this field be the i'th field. When
1447 // initializing the i'th field, throw a warning if any of the >= i'th
1448 // fields are used, as they are not yet initialized.
1449 // Right now we are only handling the case where the i'th field uses
1450 // itself in its initializer.
1451 Diag(L, diag::warn_field_is_uninit);
1452 }
1453 }
1454
Eli Friedman8e1433b2009-07-29 19:44:27 +00001455 bool HasDependentArg = false;
1456 for (unsigned i = 0; i < NumArgs; i++)
1457 HasDependentArg |= Args[i]->isTypeDependent();
1458
Chandler Carruthd44c3102010-12-06 09:23:57 +00001459 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001460 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001461 // Can't check initialization for a member of dependent type or when
1462 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001463 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1464 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001465
1466 // Erase any temporaries within this evaluation context; we're not
1467 // going to track them in the AST, since we'll be rebuilding the
1468 // ASTs during template instantiation.
1469 ExprTemporaries.erase(
1470 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1471 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001472 } else {
1473 // Initialize the member.
1474 InitializedEntity MemberEntity =
1475 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1476 : InitializedEntity::InitializeMember(IndirectMember, 0);
1477 InitializationKind Kind =
1478 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001479
Chandler Carruthd44c3102010-12-06 09:23:57 +00001480 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1481
1482 ExprResult MemberInit =
1483 InitSeq.Perform(*this, MemberEntity, Kind,
1484 MultiExprArg(*this, Args, NumArgs), 0);
1485 if (MemberInit.isInvalid())
1486 return true;
1487
1488 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1489
1490 // C++0x [class.base.init]p7:
1491 // The initialization of each base and member constitutes a
1492 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001493 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001494 if (MemberInit.isInvalid())
1495 return true;
1496
1497 // If we are in a dependent context, template instantiation will
1498 // perform this type-checking again. Just save the arguments that we
1499 // received in a ParenListExpr.
1500 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1501 // of the information that we have about the member
1502 // initializer. However, deconstructing the ASTs is a dicey process,
1503 // and this approach is far more likely to get the corner cases right.
1504 if (CurContext->isDependentContext())
1505 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1506 RParenLoc);
1507 else
1508 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001509 }
1510
Chandler Carruthd44c3102010-12-06 09:23:57 +00001511 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001512 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001513 IdLoc, LParenLoc, Init,
1514 RParenLoc);
1515 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001516 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001517 IdLoc, LParenLoc, Init,
1518 RParenLoc);
1519 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001520}
1521
John McCallfaf5fb42010-08-26 23:41:50 +00001522MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001523Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1524 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001525 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001526 SourceLocation LParenLoc,
1527 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001528 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001529 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1530 if (!LangOpts.CPlusPlus0x)
1531 return Diag(Loc, diag::err_delegation_0x_only)
1532 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001533
Alexis Huntc5575cc2011-02-26 19:13:13 +00001534 // Initialize the object.
1535 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1536 QualType(ClassDecl->getTypeForDecl(), 0));
1537 InitializationKind Kind =
1538 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1539
1540 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1541
1542 ExprResult DelegationInit =
1543 InitSeq.Perform(*this, DelegationEntity, Kind,
1544 MultiExprArg(*this, Args, NumArgs), 0);
1545 if (DelegationInit.isInvalid())
1546 return true;
1547
1548 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1549 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1550 assert(Constructor && "Delegating constructor with no target?");
1551
1552 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1553
1554 // C++0x [class.base.init]p7:
1555 // The initialization of each base and member constitutes a
1556 // full-expression.
1557 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1558 if (DelegationInit.isInvalid())
1559 return true;
1560
1561 // If we are in a dependent context, template instantiation will
1562 // perform this type-checking again. Just save the arguments that we
1563 // received in a ParenListExpr.
1564 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1565 // of the information that we have about the base
1566 // initializer. However, deconstructing the ASTs is a dicey process,
1567 // and this approach is far more likely to get the corner cases right.
1568 if (CurContext->isDependentContext()) {
1569 ExprResult Init
1570 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1571 NumArgs, RParenLoc));
1572 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1573 Constructor, Init.takeAs<Expr>(),
1574 RParenLoc);
1575 }
1576
1577 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1578 DelegationInit.takeAs<Expr>(),
1579 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001580}
1581
1582MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001583Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001584 Expr **Args, unsigned NumArgs,
1585 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001586 CXXRecordDecl *ClassDecl,
1587 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001588 bool HasDependentArg = false;
1589 for (unsigned i = 0; i < NumArgs; i++)
1590 HasDependentArg |= Args[i]->isTypeDependent();
1591
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001592 SourceLocation BaseLoc
1593 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1594
1595 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1596 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1597 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1598
1599 // C++ [class.base.init]p2:
1600 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001601 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001602 // of that class, the mem-initializer is ill-formed. A
1603 // mem-initializer-list can initialize a base class using any
1604 // name that denotes that base class type.
1605 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1606
Douglas Gregor44e7df62011-01-04 00:32:56 +00001607 if (EllipsisLoc.isValid()) {
1608 // This is a pack expansion.
1609 if (!BaseType->containsUnexpandedParameterPack()) {
1610 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1611 << SourceRange(BaseLoc, RParenLoc);
1612
1613 EllipsisLoc = SourceLocation();
1614 }
1615 } else {
1616 // Check for any unexpanded parameter packs.
1617 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1618 return true;
1619
1620 for (unsigned I = 0; I != NumArgs; ++I)
1621 if (DiagnoseUnexpandedParameterPack(Args[I]))
1622 return true;
1623 }
1624
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001625 // Check for direct and virtual base classes.
1626 const CXXBaseSpecifier *DirectBaseSpec = 0;
1627 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1628 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001629 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1630 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001631 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1632 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001633
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001634 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1635 VirtualBaseSpec);
1636
1637 // C++ [base.class.init]p2:
1638 // Unless the mem-initializer-id names a nonstatic data member of the
1639 // constructor's class or a direct or virtual base of that class, the
1640 // mem-initializer is ill-formed.
1641 if (!DirectBaseSpec && !VirtualBaseSpec) {
1642 // If the class has any dependent bases, then it's possible that
1643 // one of those types will resolve to the same type as
1644 // BaseType. Therefore, just treat this as a dependent base
1645 // class initialization. FIXME: Should we try to check the
1646 // initialization anyway? It seems odd.
1647 if (ClassDecl->hasAnyDependentBases())
1648 Dependent = true;
1649 else
1650 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1651 << BaseType << Context.getTypeDeclType(ClassDecl)
1652 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1653 }
1654 }
1655
1656 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001657 // Can't check initialization for a base of dependent type or when
1658 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001659 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001660 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1661 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001662
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001663 // Erase any temporaries within this evaluation context; we're not
1664 // going to track them in the AST, since we'll be rebuilding the
1665 // ASTs during template instantiation.
1666 ExprTemporaries.erase(
1667 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1668 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001669
Alexis Hunt1d792652011-01-08 20:30:50 +00001670 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001671 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001672 LParenLoc,
1673 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001674 RParenLoc,
1675 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001676 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001677
1678 // C++ [base.class.init]p2:
1679 // If a mem-initializer-id is ambiguous because it designates both
1680 // a direct non-virtual base class and an inherited virtual base
1681 // class, the mem-initializer is ill-formed.
1682 if (DirectBaseSpec && VirtualBaseSpec)
1683 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001684 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001685
1686 CXXBaseSpecifier *BaseSpec
1687 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1688 if (!BaseSpec)
1689 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1690
1691 // Initialize the base.
1692 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001693 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001694 InitializationKind Kind =
1695 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1696
1697 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1698
John McCalldadc5752010-08-24 06:29:42 +00001699 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001700 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001701 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001702 if (BaseInit.isInvalid())
1703 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001704
1705 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001706
1707 // C++0x [class.base.init]p7:
1708 // The initialization of each base and member constitutes a
1709 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001710 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001711 if (BaseInit.isInvalid())
1712 return true;
1713
1714 // If we are in a dependent context, template instantiation will
1715 // perform this type-checking again. Just save the arguments that we
1716 // received in a ParenListExpr.
1717 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1718 // of the information that we have about the base
1719 // initializer. However, deconstructing the ASTs is a dicey process,
1720 // and this approach is far more likely to get the corner cases right.
1721 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001722 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001723 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1724 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001725 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001726 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001727 LParenLoc,
1728 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001729 RParenLoc,
1730 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001731 }
1732
Alexis Hunt1d792652011-01-08 20:30:50 +00001733 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001734 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001735 LParenLoc,
1736 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001737 RParenLoc,
1738 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001739}
1740
Anders Carlsson1b00e242010-04-23 03:10:23 +00001741/// ImplicitInitializerKind - How an implicit base or member initializer should
1742/// initialize its base or member.
1743enum ImplicitInitializerKind {
1744 IIK_Default,
1745 IIK_Copy,
1746 IIK_Move
1747};
1748
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001749static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001750BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001751 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001752 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001753 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001754 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001755 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001756 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1757 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001758
John McCalldadc5752010-08-24 06:29:42 +00001759 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001760
1761 switch (ImplicitInitKind) {
1762 case IIK_Default: {
1763 InitializationKind InitKind
1764 = InitializationKind::CreateDefault(Constructor->getLocation());
1765 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1766 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001767 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001768 break;
1769 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001770
Anders Carlsson1b00e242010-04-23 03:10:23 +00001771 case IIK_Copy: {
1772 ParmVarDecl *Param = Constructor->getParamDecl(0);
1773 QualType ParamType = Param->getType().getNonReferenceType();
1774
1775 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001776 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001777 Constructor->getLocation(), ParamType,
1778 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001779
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001780 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001781 QualType ArgTy =
1782 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1783 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001784
1785 CXXCastPath BasePath;
1786 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001787 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1788 CK_UncheckedDerivedToBase,
1789 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001790
Anders Carlsson1b00e242010-04-23 03:10:23 +00001791 InitializationKind InitKind
1792 = InitializationKind::CreateDirect(Constructor->getLocation(),
1793 SourceLocation(), SourceLocation());
1794 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1795 &CopyCtorArg, 1);
1796 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001797 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001798 break;
1799 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001800
Anders Carlsson1b00e242010-04-23 03:10:23 +00001801 case IIK_Move:
1802 assert(false && "Unhandled initializer kind!");
1803 }
John McCallb268a282010-08-23 23:25:46 +00001804
Douglas Gregora40433a2010-12-07 00:41:46 +00001805 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001806 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001807 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001808
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001809 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001810 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001811 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1812 SourceLocation()),
1813 BaseSpec->isVirtual(),
1814 SourceLocation(),
1815 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001816 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001817 SourceLocation());
1818
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001819 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001820}
1821
Anders Carlsson3c1db572010-04-23 02:15:47 +00001822static bool
1823BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001824 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001825 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001826 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001827 if (Field->isInvalidDecl())
1828 return true;
1829
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001830 SourceLocation Loc = Constructor->getLocation();
1831
Anders Carlsson423f5d82010-04-23 16:04:08 +00001832 if (ImplicitInitKind == IIK_Copy) {
1833 ParmVarDecl *Param = Constructor->getParamDecl(0);
1834 QualType ParamType = Param->getType().getNonReferenceType();
1835
1836 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001837 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001838 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001839
1840 // Build a reference to this field within the parameter.
1841 CXXScopeSpec SS;
1842 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1843 Sema::LookupMemberName);
1844 MemberLookup.addDecl(Field, AS_public);
1845 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001846 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001847 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001848 ParamType, Loc,
1849 /*IsArrow=*/false,
1850 SS,
1851 /*FirstQualifierInScope=*/0,
1852 MemberLookup,
1853 /*TemplateArgs=*/0);
1854 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001855 return true;
1856
Douglas Gregor94f9a482010-05-05 05:51:00 +00001857 // When the field we are copying is an array, create index variables for
1858 // each dimension of the array. We use these index variables to subscript
1859 // the source array, and other clients (e.g., CodeGen) will perform the
1860 // necessary iteration with these index variables.
1861 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1862 QualType BaseType = Field->getType();
1863 QualType SizeType = SemaRef.Context.getSizeType();
1864 while (const ConstantArrayType *Array
1865 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1866 // Create the iteration variable for this array index.
1867 IdentifierInfo *IterationVarName = 0;
1868 {
1869 llvm::SmallString<8> Str;
1870 llvm::raw_svector_ostream OS(Str);
1871 OS << "__i" << IndexVariables.size();
1872 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1873 }
1874 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00001875 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001876 IterationVarName, SizeType,
1877 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001878 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001879 IndexVariables.push_back(IterationVar);
1880
1881 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001882 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001883 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001884 assert(!IterationVarRef.isInvalid() &&
1885 "Reference to invented variable cannot fail!");
1886
1887 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001888 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001889 Loc,
John McCallb268a282010-08-23 23:25:46 +00001890 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001891 Loc);
1892 if (CopyCtorArg.isInvalid())
1893 return true;
1894
1895 BaseType = Array->getElementType();
1896 }
1897
1898 // Construct the entity that we will be initializing. For an array, this
1899 // will be first element in the array, which may require several levels
1900 // of array-subscript entities.
1901 llvm::SmallVector<InitializedEntity, 4> Entities;
1902 Entities.reserve(1 + IndexVariables.size());
1903 Entities.push_back(InitializedEntity::InitializeMember(Field));
1904 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1905 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1906 0,
1907 Entities.back()));
1908
1909 // Direct-initialize to use the copy constructor.
1910 InitializationKind InitKind =
1911 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1912
1913 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1914 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1915 &CopyCtorArgE, 1);
1916
John McCalldadc5752010-08-24 06:29:42 +00001917 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001918 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001919 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001920 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001921 if (MemberInit.isInvalid())
1922 return true;
1923
1924 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001925 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001926 MemberInit.takeAs<Expr>(), Loc,
1927 IndexVariables.data(),
1928 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001929 return false;
1930 }
1931
Anders Carlsson423f5d82010-04-23 16:04:08 +00001932 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1933
Anders Carlsson3c1db572010-04-23 02:15:47 +00001934 QualType FieldBaseElementType =
1935 SemaRef.Context.getBaseElementType(Field->getType());
1936
Anders Carlsson3c1db572010-04-23 02:15:47 +00001937 if (FieldBaseElementType->isRecordType()) {
1938 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001939 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001940 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001941
1942 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001943 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001944 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001945
Douglas Gregora40433a2010-12-07 00:41:46 +00001946 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001947 if (MemberInit.isInvalid())
1948 return true;
1949
1950 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001951 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001952 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001953 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001954 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001955 return false;
1956 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001957
1958 if (FieldBaseElementType->isReferenceType()) {
1959 SemaRef.Diag(Constructor->getLocation(),
1960 diag::err_uninitialized_member_in_ctor)
1961 << (int)Constructor->isImplicit()
1962 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1963 << 0 << Field->getDeclName();
1964 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1965 return true;
1966 }
1967
1968 if (FieldBaseElementType.isConstQualified()) {
1969 SemaRef.Diag(Constructor->getLocation(),
1970 diag::err_uninitialized_member_in_ctor)
1971 << (int)Constructor->isImplicit()
1972 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1973 << 1 << Field->getDeclName();
1974 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1975 return true;
1976 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001977
1978 // Nothing to initialize.
1979 CXXMemberInit = 0;
1980 return false;
1981}
John McCallbc83b3f2010-05-20 23:23:51 +00001982
1983namespace {
1984struct BaseAndFieldInfo {
1985 Sema &S;
1986 CXXConstructorDecl *Ctor;
1987 bool AnyErrorsInInits;
1988 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001989 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1990 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001991
1992 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1993 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1994 // FIXME: Handle implicit move constructors.
1995 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1996 IIK = IIK_Copy;
1997 else
1998 IIK = IIK_Default;
1999 }
2000};
2001}
2002
2003static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2004 FieldDecl *Top, FieldDecl *Field) {
2005
Chandler Carruth139e9622010-06-30 02:59:29 +00002006 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002007 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002008 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002009 return false;
2010 }
2011
2012 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2013 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2014 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002015 CXXRecordDecl *FieldClassDecl
2016 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002017
2018 // Even though union members never have non-trivial default
2019 // constructions in C++03, we still build member initializers for aggregate
2020 // record types which can be union members, and C++0x allows non-trivial
2021 // default constructors for union members, so we ensure that only one
2022 // member is initialized for these.
2023 if (FieldClassDecl->isUnion()) {
2024 // First check for an explicit initializer for one field.
2025 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2026 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002027 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002028 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002029
2030 // Once we've initialized a field of an anonymous union, the union
2031 // field in the class is also initialized, so exit immediately.
2032 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002033 } else if ((*FA)->isAnonymousStructOrUnion()) {
2034 if (CollectFieldInitializer(Info, Top, *FA))
2035 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002036 }
2037 }
2038
2039 // Fallthrough and construct a default initializer for the union as
2040 // a whole, which can call its default constructor if such a thing exists
2041 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2042 // behavior going forward with C++0x, when anonymous unions there are
2043 // finalized, we should revisit this.
2044 } else {
2045 // For structs, we simply descend through to initialize all members where
2046 // necessary.
2047 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2048 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2049 if (CollectFieldInitializer(Info, Top, *FA))
2050 return true;
2051 }
2052 }
John McCallbc83b3f2010-05-20 23:23:51 +00002053 }
2054
2055 // Don't try to build an implicit initializer if there were semantic
2056 // errors in any of the initializers (and therefore we might be
2057 // missing some that the user actually wrote).
2058 if (Info.AnyErrorsInInits)
2059 return false;
2060
Alexis Hunt1d792652011-01-08 20:30:50 +00002061 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002062 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2063 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002064
Francois Pichetd583da02010-12-04 09:14:42 +00002065 if (Init)
2066 Info.AllToInit.push_back(Init);
2067
John McCallbc83b3f2010-05-20 23:23:51 +00002068 return false;
2069}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002070
Eli Friedman9cf6b592009-11-09 19:20:36 +00002071bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002072Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2073 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002074 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002075 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002076 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002077 // Just store the initializers as written, they will be checked during
2078 // instantiation.
2079 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002080 Constructor->setNumCtorInitializers(NumInitializers);
2081 CXXCtorInitializer **baseOrMemberInitializers =
2082 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002083 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002084 NumInitializers * sizeof(CXXCtorInitializer*));
2085 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002086 }
2087
2088 return false;
2089 }
2090
John McCallbc83b3f2010-05-20 23:23:51 +00002091 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002092
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002093 // We need to build the initializer AST according to order of construction
2094 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002095 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002096 if (!ClassDecl)
2097 return true;
2098
Eli Friedman9cf6b592009-11-09 19:20:36 +00002099 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002100
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002101 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002102 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002103
2104 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002105 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002106 else
Francois Pichetd583da02010-12-04 09:14:42 +00002107 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002108 }
2109
Anders Carlsson43c64af2010-04-21 19:52:01 +00002110 // Keep track of the direct virtual bases.
2111 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2112 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2113 E = ClassDecl->bases_end(); I != E; ++I) {
2114 if (I->isVirtual())
2115 DirectVBases.insert(I);
2116 }
2117
Anders Carlssondb0a9652010-04-02 06:26:44 +00002118 // Push virtual bases before others.
2119 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2120 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2121
Alexis Hunt1d792652011-01-08 20:30:50 +00002122 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002123 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2124 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002125 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002126 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002127 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002128 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002129 VBase, IsInheritedVirtualBase,
2130 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002131 HadError = true;
2132 continue;
2133 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002134
John McCallbc83b3f2010-05-20 23:23:51 +00002135 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002136 }
2137 }
Mike Stump11289f42009-09-09 15:08:12 +00002138
John McCallbc83b3f2010-05-20 23:23:51 +00002139 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002140 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2141 E = ClassDecl->bases_end(); Base != E; ++Base) {
2142 // Virtuals are in the virtual base list and already constructed.
2143 if (Base->isVirtual())
2144 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002145
Alexis Hunt1d792652011-01-08 20:30:50 +00002146 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002147 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2148 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002149 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002150 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002151 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002152 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002153 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002154 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002155 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002156 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002157
John McCallbc83b3f2010-05-20 23:23:51 +00002158 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002159 }
2160 }
Mike Stump11289f42009-09-09 15:08:12 +00002161
John McCallbc83b3f2010-05-20 23:23:51 +00002162 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002163 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002164 E = ClassDecl->field_end(); Field != E; ++Field) {
2165 if ((*Field)->getType()->isIncompleteArrayType()) {
2166 assert(ClassDecl->hasFlexibleArrayMember() &&
2167 "Incomplete array type is not valid");
2168 continue;
2169 }
John McCallbc83b3f2010-05-20 23:23:51 +00002170 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002171 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
John McCallbc83b3f2010-05-20 23:23:51 +00002174 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002175 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002176 Constructor->setNumCtorInitializers(NumInitializers);
2177 CXXCtorInitializer **baseOrMemberInitializers =
2178 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002179 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002180 NumInitializers * sizeof(CXXCtorInitializer*));
2181 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002182
John McCalla6309952010-03-16 21:39:52 +00002183 // Constructors implicitly reference the base and member
2184 // destructors.
2185 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2186 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002187 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002188
2189 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002190}
2191
Eli Friedman952c15d2009-07-21 19:28:10 +00002192static void *GetKeyForTopLevelField(FieldDecl *Field) {
2193 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002194 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002195 if (RT->getDecl()->isAnonymousStructOrUnion())
2196 return static_cast<void *>(RT->getDecl());
2197 }
2198 return static_cast<void *>(Field);
2199}
2200
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002201static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002202 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002203}
2204
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002205static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002206 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002207 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002208 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002209
Eli Friedman952c15d2009-07-21 19:28:10 +00002210 // For fields injected into the class via declaration of an anonymous union,
2211 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002212 FieldDecl *Field = Member->getAnyMember();
2213
John McCall23eebd92010-04-10 09:28:51 +00002214 // If the field is a member of an anonymous struct or union, our key
2215 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002216 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002217 if (RD->isAnonymousStructOrUnion()) {
2218 while (true) {
2219 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2220 if (Parent->isAnonymousStructOrUnion())
2221 RD = Parent;
2222 else
2223 break;
2224 }
2225
Anders Carlsson83ac3122010-03-30 16:19:37 +00002226 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002227 }
Mike Stump11289f42009-09-09 15:08:12 +00002228
Anders Carlssona942dcd2010-03-30 15:39:27 +00002229 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002230}
2231
Anders Carlssone857b292010-04-02 03:37:03 +00002232static void
2233DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002234 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002235 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002236 unsigned NumInits) {
2237 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002238 return;
Mike Stump11289f42009-09-09 15:08:12 +00002239
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002240 // Don't check initializers order unless the warning is enabled at the
2241 // location of at least one initializer.
2242 bool ShouldCheckOrder = false;
2243 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002244 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002245 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2246 Init->getSourceLocation())
2247 != Diagnostic::Ignored) {
2248 ShouldCheckOrder = true;
2249 break;
2250 }
2251 }
2252 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002253 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002254
John McCallbb7b6582010-04-10 07:37:23 +00002255 // Build the list of bases and members in the order that they'll
2256 // actually be initialized. The explicit initializers should be in
2257 // this same order but may be missing things.
2258 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002259
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002260 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2261
John McCallbb7b6582010-04-10 07:37:23 +00002262 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002263 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002264 ClassDecl->vbases_begin(),
2265 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002266 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002267
John McCallbb7b6582010-04-10 07:37:23 +00002268 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002269 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002270 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002271 if (Base->isVirtual())
2272 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002273 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
John McCallbb7b6582010-04-10 07:37:23 +00002276 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002277 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2278 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002279 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002280
John McCallbb7b6582010-04-10 07:37:23 +00002281 unsigned NumIdealInits = IdealInitKeys.size();
2282 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002283
Alexis Hunt1d792652011-01-08 20:30:50 +00002284 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002285 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002286 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002287 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002288
2289 // Scan forward to try to find this initializer in the idealized
2290 // initializers list.
2291 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2292 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002293 break;
John McCallbb7b6582010-04-10 07:37:23 +00002294
2295 // If we didn't find this initializer, it must be because we
2296 // scanned past it on a previous iteration. That can only
2297 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002298 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002299 Sema::SemaDiagnosticBuilder D =
2300 SemaRef.Diag(PrevInit->getSourceLocation(),
2301 diag::warn_initializer_out_of_order);
2302
Francois Pichetd583da02010-12-04 09:14:42 +00002303 if (PrevInit->isAnyMemberInitializer())
2304 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002305 else
2306 D << 1 << PrevInit->getBaseClassInfo()->getType();
2307
Francois Pichetd583da02010-12-04 09:14:42 +00002308 if (Init->isAnyMemberInitializer())
2309 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002310 else
2311 D << 1 << Init->getBaseClassInfo()->getType();
2312
2313 // Move back to the initializer's location in the ideal list.
2314 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2315 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002316 break;
John McCallbb7b6582010-04-10 07:37:23 +00002317
2318 assert(IdealIndex != NumIdealInits &&
2319 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002320 }
John McCallbb7b6582010-04-10 07:37:23 +00002321
2322 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002323 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002324}
2325
John McCall23eebd92010-04-10 09:28:51 +00002326namespace {
2327bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002328 CXXCtorInitializer *Init,
2329 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002330 if (!PrevInit) {
2331 PrevInit = Init;
2332 return false;
2333 }
2334
2335 if (FieldDecl *Field = Init->getMember())
2336 S.Diag(Init->getSourceLocation(),
2337 diag::err_multiple_mem_initialization)
2338 << Field->getDeclName()
2339 << Init->getSourceRange();
2340 else {
John McCall424cec92011-01-19 06:33:43 +00002341 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002342 assert(BaseClass && "neither field nor base");
2343 S.Diag(Init->getSourceLocation(),
2344 diag::err_multiple_base_initialization)
2345 << QualType(BaseClass, 0)
2346 << Init->getSourceRange();
2347 }
2348 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2349 << 0 << PrevInit->getSourceRange();
2350
2351 return true;
2352}
2353
Alexis Hunt1d792652011-01-08 20:30:50 +00002354typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002355typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2356
2357bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002358 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002359 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002360 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002361 RecordDecl *Parent = Field->getParent();
2362 if (!Parent->isAnonymousStructOrUnion())
2363 return false;
2364
2365 NamedDecl *Child = Field;
2366 do {
2367 if (Parent->isUnion()) {
2368 UnionEntry &En = Unions[Parent];
2369 if (En.first && En.first != Child) {
2370 S.Diag(Init->getSourceLocation(),
2371 diag::err_multiple_mem_union_initialization)
2372 << Field->getDeclName()
2373 << Init->getSourceRange();
2374 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2375 << 0 << En.second->getSourceRange();
2376 return true;
2377 } else if (!En.first) {
2378 En.first = Child;
2379 En.second = Init;
2380 }
2381 }
2382
2383 Child = Parent;
2384 Parent = cast<RecordDecl>(Parent->getDeclContext());
2385 } while (Parent->isAnonymousStructOrUnion());
2386
2387 return false;
2388}
2389}
2390
Anders Carlssone857b292010-04-02 03:37:03 +00002391/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002392void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002393 SourceLocation ColonLoc,
2394 MemInitTy **meminits, unsigned NumMemInits,
2395 bool AnyErrors) {
2396 if (!ConstructorDecl)
2397 return;
2398
2399 AdjustDeclIfTemplate(ConstructorDecl);
2400
2401 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002402 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002403
2404 if (!Constructor) {
2405 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2406 return;
2407 }
2408
Alexis Hunt1d792652011-01-08 20:30:50 +00002409 CXXCtorInitializer **MemInits =
2410 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002411
2412 // Mapping for the duplicate initializers check.
2413 // For member initializers, this is keyed with a FieldDecl*.
2414 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002415 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002416
2417 // Mapping for the inconsistent anonymous-union initializers check.
2418 RedundantUnionMap MemberUnions;
2419
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002420 bool HadError = false;
2421 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002422 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002423
Abramo Bagnara341d7832010-05-26 18:09:23 +00002424 // Set the source order index.
2425 Init->setSourceOrder(i);
2426
Francois Pichetd583da02010-12-04 09:14:42 +00002427 if (Init->isAnyMemberInitializer()) {
2428 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002429 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2430 CheckRedundantUnionInit(*this, Init, MemberUnions))
2431 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002432 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002433 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2434 if (CheckRedundantInit(*this, Init, Members[Key]))
2435 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002436 } else {
2437 assert(Init->isDelegatingInitializer());
2438 // This must be the only initializer
2439 if (i != 0 || NumMemInits > 1) {
2440 Diag(MemInits[0]->getSourceLocation(),
2441 diag::err_delegating_initializer_alone)
2442 << MemInits[0]->getSourceRange();
2443 HadError = true;
2444 }
Anders Carlssone857b292010-04-02 03:37:03 +00002445 }
Anders Carlssone857b292010-04-02 03:37:03 +00002446 }
2447
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002448 if (HadError)
2449 return;
2450
Anders Carlssone857b292010-04-02 03:37:03 +00002451 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002452
Alexis Hunt1d792652011-01-08 20:30:50 +00002453 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002454}
2455
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002456void
John McCalla6309952010-03-16 21:39:52 +00002457Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2458 CXXRecordDecl *ClassDecl) {
2459 // Ignore dependent contexts.
2460 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002461 return;
John McCall1064d7e2010-03-16 05:22:47 +00002462
2463 // FIXME: all the access-control diagnostics are positioned on the
2464 // field/base declaration. That's probably good; that said, the
2465 // user might reasonably want to know why the destructor is being
2466 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002467
Anders Carlssondee9a302009-11-17 04:44:12 +00002468 // Non-static data members.
2469 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2470 E = ClassDecl->field_end(); I != E; ++I) {
2471 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002472 if (Field->isInvalidDecl())
2473 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002474 QualType FieldType = Context.getBaseElementType(Field->getType());
2475
2476 const RecordType* RT = FieldType->getAs<RecordType>();
2477 if (!RT)
2478 continue;
2479
2480 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002481 if (FieldClassDecl->isInvalidDecl())
2482 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002483 if (FieldClassDecl->hasTrivialDestructor())
2484 continue;
2485
Douglas Gregore71edda2010-07-01 22:47:18 +00002486 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002487 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002488 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002489 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002490 << Field->getDeclName()
2491 << FieldType);
2492
John McCalla6309952010-03-16 21:39:52 +00002493 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002494 }
2495
John McCall1064d7e2010-03-16 05:22:47 +00002496 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2497
Anders Carlssondee9a302009-11-17 04:44:12 +00002498 // Bases.
2499 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2500 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002501 // Bases are always records in a well-formed non-dependent class.
2502 const RecordType *RT = Base->getType()->getAs<RecordType>();
2503
2504 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002505 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002506 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002507
John McCall1064d7e2010-03-16 05:22:47 +00002508 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002509 // If our base class is invalid, we probably can't get its dtor anyway.
2510 if (BaseClassDecl->isInvalidDecl())
2511 continue;
2512 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002513 if (BaseClassDecl->hasTrivialDestructor())
2514 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002515
Douglas Gregore71edda2010-07-01 22:47:18 +00002516 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002517 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002518
2519 // FIXME: caret should be on the start of the class name
2520 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002521 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002522 << Base->getType()
2523 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002524
John McCalla6309952010-03-16 21:39:52 +00002525 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002526 }
2527
2528 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002529 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2530 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002531
2532 // Bases are always records in a well-formed non-dependent class.
2533 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2534
2535 // Ignore direct virtual bases.
2536 if (DirectVirtualBases.count(RT))
2537 continue;
2538
John McCall1064d7e2010-03-16 05:22:47 +00002539 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002540 // If our base class is invalid, we probably can't get its dtor anyway.
2541 if (BaseClassDecl->isInvalidDecl())
2542 continue;
2543 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002544 if (BaseClassDecl->hasTrivialDestructor())
2545 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002546
Douglas Gregore71edda2010-07-01 22:47:18 +00002547 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002548 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002549 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002550 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002551 << VBase->getType());
2552
John McCalla6309952010-03-16 21:39:52 +00002553 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002554 }
2555}
2556
John McCall48871652010-08-21 09:40:31 +00002557void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002558 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002559 return;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Mike Stump11289f42009-09-09 15:08:12 +00002561 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002562 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002563 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002564}
2565
Mike Stump11289f42009-09-09 15:08:12 +00002566bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002567 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002568 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002569 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002570 else
John McCall02db245d2010-08-18 09:41:07 +00002571 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002572}
2573
Anders Carlssoneabf7702009-08-27 00:13:57 +00002574bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002575 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002576 if (!getLangOptions().CPlusPlus)
2577 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002578
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002579 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002580 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002581
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002582 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002583 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002584 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002585 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002587 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002588 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002589 }
Mike Stump11289f42009-09-09 15:08:12 +00002590
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002591 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002592 if (!RT)
2593 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002594
John McCall67da35c2010-02-04 22:26:26 +00002595 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002596
John McCall02db245d2010-08-18 09:41:07 +00002597 // We can't answer whether something is abstract until it has a
2598 // definition. If it's currently being defined, we'll walk back
2599 // over all the declarations when we have a full definition.
2600 const CXXRecordDecl *Def = RD->getDefinition();
2601 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002602 return false;
2603
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002604 if (!RD->isAbstract())
2605 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002606
Anders Carlssoneabf7702009-08-27 00:13:57 +00002607 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002608 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002609
John McCall02db245d2010-08-18 09:41:07 +00002610 return true;
2611}
2612
2613void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2614 // Check if we've already emitted the list of pure virtual functions
2615 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002616 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002617 return;
Mike Stump11289f42009-09-09 15:08:12 +00002618
Douglas Gregor4165bd62010-03-23 23:47:56 +00002619 CXXFinalOverriderMap FinalOverriders;
2620 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002621
Anders Carlssona2f74f32010-06-03 01:00:02 +00002622 // Keep a set of seen pure methods so we won't diagnose the same method
2623 // more than once.
2624 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2625
Douglas Gregor4165bd62010-03-23 23:47:56 +00002626 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2627 MEnd = FinalOverriders.end();
2628 M != MEnd;
2629 ++M) {
2630 for (OverridingMethods::iterator SO = M->second.begin(),
2631 SOEnd = M->second.end();
2632 SO != SOEnd; ++SO) {
2633 // C++ [class.abstract]p4:
2634 // A class is abstract if it contains or inherits at least one
2635 // pure virtual function for which the final overrider is pure
2636 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002637
Douglas Gregor4165bd62010-03-23 23:47:56 +00002638 //
2639 if (SO->second.size() != 1)
2640 continue;
2641
2642 if (!SO->second.front().Method->isPure())
2643 continue;
2644
Anders Carlssona2f74f32010-06-03 01:00:02 +00002645 if (!SeenPureMethods.insert(SO->second.front().Method))
2646 continue;
2647
Douglas Gregor4165bd62010-03-23 23:47:56 +00002648 Diag(SO->second.front().Method->getLocation(),
2649 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002650 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002651 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002652 }
2653
2654 if (!PureVirtualClassDiagSet)
2655 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2656 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002657}
2658
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002659namespace {
John McCall02db245d2010-08-18 09:41:07 +00002660struct AbstractUsageInfo {
2661 Sema &S;
2662 CXXRecordDecl *Record;
2663 CanQualType AbstractType;
2664 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002665
John McCall02db245d2010-08-18 09:41:07 +00002666 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2667 : S(S), Record(Record),
2668 AbstractType(S.Context.getCanonicalType(
2669 S.Context.getTypeDeclType(Record))),
2670 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002671
John McCall02db245d2010-08-18 09:41:07 +00002672 void DiagnoseAbstractType() {
2673 if (Invalid) return;
2674 S.DiagnoseAbstractType(Record);
2675 Invalid = true;
2676 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002677
John McCall02db245d2010-08-18 09:41:07 +00002678 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2679};
2680
2681struct CheckAbstractUsage {
2682 AbstractUsageInfo &Info;
2683 const NamedDecl *Ctx;
2684
2685 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2686 : Info(Info), Ctx(Ctx) {}
2687
2688 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2689 switch (TL.getTypeLocClass()) {
2690#define ABSTRACT_TYPELOC(CLASS, PARENT)
2691#define TYPELOC(CLASS, PARENT) \
2692 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2693#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002694 }
John McCall02db245d2010-08-18 09:41:07 +00002695 }
Mike Stump11289f42009-09-09 15:08:12 +00002696
John McCall02db245d2010-08-18 09:41:07 +00002697 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2698 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2699 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002700 if (!TL.getArg(I))
2701 continue;
2702
John McCall02db245d2010-08-18 09:41:07 +00002703 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2704 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002705 }
John McCall02db245d2010-08-18 09:41:07 +00002706 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002707
John McCall02db245d2010-08-18 09:41:07 +00002708 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2709 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2710 }
Mike Stump11289f42009-09-09 15:08:12 +00002711
John McCall02db245d2010-08-18 09:41:07 +00002712 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2713 // Visit the type parameters from a permissive context.
2714 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2715 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2716 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2717 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2718 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2719 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002720 }
John McCall02db245d2010-08-18 09:41:07 +00002721 }
Mike Stump11289f42009-09-09 15:08:12 +00002722
John McCall02db245d2010-08-18 09:41:07 +00002723 // Visit pointee types from a permissive context.
2724#define CheckPolymorphic(Type) \
2725 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2726 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2727 }
2728 CheckPolymorphic(PointerTypeLoc)
2729 CheckPolymorphic(ReferenceTypeLoc)
2730 CheckPolymorphic(MemberPointerTypeLoc)
2731 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002732
John McCall02db245d2010-08-18 09:41:07 +00002733 /// Handle all the types we haven't given a more specific
2734 /// implementation for above.
2735 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2736 // Every other kind of type that we haven't called out already
2737 // that has an inner type is either (1) sugar or (2) contains that
2738 // inner type in some way as a subobject.
2739 if (TypeLoc Next = TL.getNextTypeLoc())
2740 return Visit(Next, Sel);
2741
2742 // If there's no inner type and we're in a permissive context,
2743 // don't diagnose.
2744 if (Sel == Sema::AbstractNone) return;
2745
2746 // Check whether the type matches the abstract type.
2747 QualType T = TL.getType();
2748 if (T->isArrayType()) {
2749 Sel = Sema::AbstractArrayType;
2750 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002751 }
John McCall02db245d2010-08-18 09:41:07 +00002752 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2753 if (CT != Info.AbstractType) return;
2754
2755 // It matched; do some magic.
2756 if (Sel == Sema::AbstractArrayType) {
2757 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2758 << T << TL.getSourceRange();
2759 } else {
2760 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2761 << Sel << T << TL.getSourceRange();
2762 }
2763 Info.DiagnoseAbstractType();
2764 }
2765};
2766
2767void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2768 Sema::AbstractDiagSelID Sel) {
2769 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2770}
2771
2772}
2773
2774/// Check for invalid uses of an abstract type in a method declaration.
2775static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2776 CXXMethodDecl *MD) {
2777 // No need to do the check on definitions, which require that
2778 // the return/param types be complete.
2779 if (MD->isThisDeclarationADefinition())
2780 return;
2781
2782 // For safety's sake, just ignore it if we don't have type source
2783 // information. This should never happen for non-implicit methods,
2784 // but...
2785 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2786 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2787}
2788
2789/// Check for invalid uses of an abstract type within a class definition.
2790static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2791 CXXRecordDecl *RD) {
2792 for (CXXRecordDecl::decl_iterator
2793 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2794 Decl *D = *I;
2795 if (D->isImplicit()) continue;
2796
2797 // Methods and method templates.
2798 if (isa<CXXMethodDecl>(D)) {
2799 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2800 } else if (isa<FunctionTemplateDecl>(D)) {
2801 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2802 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2803
2804 // Fields and static variables.
2805 } else if (isa<FieldDecl>(D)) {
2806 FieldDecl *FD = cast<FieldDecl>(D);
2807 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2808 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2809 } else if (isa<VarDecl>(D)) {
2810 VarDecl *VD = cast<VarDecl>(D);
2811 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2812 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2813
2814 // Nested classes and class templates.
2815 } else if (isa<CXXRecordDecl>(D)) {
2816 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2817 } else if (isa<ClassTemplateDecl>(D)) {
2818 CheckAbstractClassUsage(Info,
2819 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2820 }
2821 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002822}
2823
Douglas Gregorc99f1552009-12-03 18:33:45 +00002824/// \brief Perform semantic checks on a class definition that has been
2825/// completing, introducing implicitly-declared members, checking for
2826/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002827void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002828 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002829 return;
2830
John McCall02db245d2010-08-18 09:41:07 +00002831 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2832 AbstractUsageInfo Info(*this, Record);
2833 CheckAbstractClassUsage(Info, Record);
2834 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002835
2836 // If this is not an aggregate type and has no user-declared constructor,
2837 // complain about any non-static data members of reference or const scalar
2838 // type, since they will never get initializers.
2839 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2840 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2841 bool Complained = false;
2842 for (RecordDecl::field_iterator F = Record->field_begin(),
2843 FEnd = Record->field_end();
2844 F != FEnd; ++F) {
2845 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002846 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002847 if (!Complained) {
2848 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2849 << Record->getTagKind() << Record;
2850 Complained = true;
2851 }
2852
2853 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2854 << F->getType()->isReferenceType()
2855 << F->getDeclName();
2856 }
2857 }
2858 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002859
Anders Carlssone771e762011-01-25 18:08:22 +00002860 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002861 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002862
2863 if (Record->getIdentifier()) {
2864 // C++ [class.mem]p13:
2865 // If T is the name of a class, then each of the following shall have a
2866 // name different from T:
2867 // - every member of every anonymous union that is a member of class T.
2868 //
2869 // C++ [class.mem]p14:
2870 // In addition, if class T has a user-declared constructor (12.1), every
2871 // non-static data member of class T shall have a name different from T.
2872 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002873 R.first != R.second; ++R.first) {
2874 NamedDecl *D = *R.first;
2875 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2876 isa<IndirectFieldDecl>(D)) {
2877 Diag(D->getLocation(), diag::err_member_name_of_class)
2878 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002879 break;
2880 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002881 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002882 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002883
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002884 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002885 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002886 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002887 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002888 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2889 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2890 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002891
2892 // See if a method overloads virtual methods in a base
2893 /// class without overriding any.
2894 if (!Record->isDependentType()) {
2895 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2896 MEnd = Record->method_end();
2897 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00002898 if (!(*M)->isStatic())
2899 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002900 }
2901 }
Sebastian Redl08905022011-02-05 19:23:19 +00002902
2903 // Declare inherited constructors. We do this eagerly here because:
2904 // - The standard requires an eager diagnostic for conflicting inherited
2905 // constructors from different classes.
2906 // - The lazy declaration of the other implicit constructors is so as to not
2907 // waste space and performance on classes that are not meant to be
2908 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2909 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00002910 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002911}
2912
2913/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00002914namespace {
2915 struct FindHiddenVirtualMethodData {
2916 Sema *S;
2917 CXXMethodDecl *Method;
2918 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2919 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2920 };
2921}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002922
2923/// \brief Member lookup function that determines whether a given C++
2924/// method overloads virtual methods in a base class without overriding any,
2925/// to be used with CXXRecordDecl::lookupInBases().
2926static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2927 CXXBasePath &Path,
2928 void *UserData) {
2929 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2930
2931 FindHiddenVirtualMethodData &Data
2932 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2933
2934 DeclarationName Name = Data.Method->getDeclName();
2935 assert(Name.getNameKind() == DeclarationName::Identifier);
2936
2937 bool foundSameNameMethod = false;
2938 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2939 for (Path.Decls = BaseRecord->lookup(Name);
2940 Path.Decls.first != Path.Decls.second;
2941 ++Path.Decls.first) {
2942 NamedDecl *D = *Path.Decls.first;
2943 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002944 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002945 foundSameNameMethod = true;
2946 // Interested only in hidden virtual methods.
2947 if (!MD->isVirtual())
2948 continue;
2949 // If the method we are checking overrides a method from its base
2950 // don't warn about the other overloaded methods.
2951 if (!Data.S->IsOverload(Data.Method, MD, false))
2952 return true;
2953 // Collect the overload only if its hidden.
2954 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2955 overloadedMethods.push_back(MD);
2956 }
2957 }
2958
2959 if (foundSameNameMethod)
2960 Data.OverloadedMethods.append(overloadedMethods.begin(),
2961 overloadedMethods.end());
2962 return foundSameNameMethod;
2963}
2964
2965/// \brief See if a method overloads virtual methods in a base class without
2966/// overriding any.
2967void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2968 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2969 MD->getLocation()) == Diagnostic::Ignored)
2970 return;
2971 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2972 return;
2973
2974 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2975 /*bool RecordPaths=*/false,
2976 /*bool DetectVirtual=*/false);
2977 FindHiddenVirtualMethodData Data;
2978 Data.Method = MD;
2979 Data.S = this;
2980
2981 // Keep the base methods that were overriden or introduced in the subclass
2982 // by 'using' in a set. A base method not in this set is hidden.
2983 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2984 res.first != res.second; ++res.first) {
2985 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2986 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2987 E = MD->end_overridden_methods();
2988 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002989 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002990 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2991 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002992 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002993 }
2994
2995 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2996 !Data.OverloadedMethods.empty()) {
2997 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2998 << MD << (Data.OverloadedMethods.size() > 1);
2999
3000 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3001 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3002 Diag(overloadedMD->getLocation(),
3003 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3004 }
3005 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00003006}
3007
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003008void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00003009 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003010 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003011 SourceLocation RBrac,
3012 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003013 if (!TagDecl)
3014 return;
Mike Stump11289f42009-09-09 15:08:12 +00003015
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003016 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00003017
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003018 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00003019 // strict aliasing violation!
3020 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003021 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00003022
Douglas Gregor0be31a22010-07-02 17:43:08 +00003023 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00003024 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003025}
3026
Douglas Gregor95755162010-07-01 05:10:53 +00003027namespace {
3028 /// \brief Helper class that collects exception specifications for
3029 /// implicitly-declared special member functions.
3030 class ImplicitExceptionSpecification {
3031 ASTContext &Context;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003032 // We order exception specifications thus:
3033 // noexcept is the most restrictive, but is only used in C++0x.
3034 // throw() comes next.
3035 // Then a throw(collected exceptions)
3036 // Finally no specification.
3037 // throw(...) is used instead if any called function uses it.
3038 ExceptionSpecificationType ComputedEST;
Douglas Gregor95755162010-07-01 05:10:53 +00003039 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3040 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003041
3042 void ClearExceptions() {
3043 ExceptionsSeen.clear();
3044 Exceptions.clear();
3045 }
3046
Douglas Gregor95755162010-07-01 05:10:53 +00003047 public:
3048 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003049 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3050 if (!Context.getLangOptions().CPlusPlus0x)
3051 ComputedEST = EST_DynamicNone;
Douglas Gregor95755162010-07-01 05:10:53 +00003052 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003053
3054 /// \brief Get the computed exception specification type.
3055 ExceptionSpecificationType getExceptionSpecType() const {
3056 assert(ComputedEST != EST_ComputedNoexcept &&
3057 "noexcept(expr) should not be a possible result");
3058 return ComputedEST;
Douglas Gregor95755162010-07-01 05:10:53 +00003059 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003060
Douglas Gregor95755162010-07-01 05:10:53 +00003061 /// \brief The number of exceptions in the exception specification.
3062 unsigned size() const { return Exceptions.size(); }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003063
Douglas Gregor95755162010-07-01 05:10:53 +00003064 /// \brief The set of exceptions in the exception specification.
3065 const QualType *data() const { return Exceptions.data(); }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003066
3067 /// \brief Integrate another called method into the collected data.
Douglas Gregor95755162010-07-01 05:10:53 +00003068 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003069 // If we have an MSAny spec already, don't bother.
3070 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregor95755162010-07-01 05:10:53 +00003071 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003072
Douglas Gregor95755162010-07-01 05:10:53 +00003073 const FunctionProtoType *Proto
3074 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003075
3076 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3077
Douglas Gregor95755162010-07-01 05:10:53 +00003078 // If this function can throw any exceptions, make a note of that.
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003079 if (EST == EST_MSAny || EST == EST_None) {
3080 ClearExceptions();
3081 ComputedEST = EST;
Douglas Gregor95755162010-07-01 05:10:53 +00003082 return;
3083 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003084
3085 // If this function has a basic noexcept, it doesn't affect the outcome.
3086 if (EST == EST_BasicNoexcept)
3087 return;
3088
3089 // If we have a throw-all spec at this point, ignore the function.
3090 if (ComputedEST == EST_None)
3091 return;
3092
3093 // If we're still at noexcept(true) and there's a nothrow() callee,
3094 // change to that specification.
3095 if (EST == EST_DynamicNone) {
3096 if (ComputedEST == EST_BasicNoexcept)
3097 ComputedEST = EST_DynamicNone;
3098 return;
3099 }
3100
3101 // Check out noexcept specs.
3102 if (EST == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003103 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003104 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3105 "Must have noexcept result for EST_ComputedNoexcept.");
3106 assert(NR != FunctionProtoType::NR_Dependent &&
3107 "Should not generate implicit declarations for dependent cases, "
3108 "and don't know how to handle them anyway.");
3109
3110 // noexcept(false) -> no spec on the new function
3111 if (NR == FunctionProtoType::NR_Throw) {
3112 ClearExceptions();
3113 ComputedEST = EST_None;
3114 }
3115 // noexcept(true) won't change anything either.
3116 return;
3117 }
3118
3119 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3120 assert(ComputedEST != EST_None &&
3121 "Shouldn't collect exceptions when throw-all is guaranteed.");
3122 ComputedEST = EST_Dynamic;
Douglas Gregor95755162010-07-01 05:10:53 +00003123 // Record the exceptions in this function's exception specification.
3124 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3125 EEnd = Proto->exception_end();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003126 E != EEnd; ++E)
Douglas Gregor95755162010-07-01 05:10:53 +00003127 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3128 Exceptions.push_back(*E);
3129 }
3130 };
3131}
3132
3133
Douglas Gregor05379422008-11-03 17:51:48 +00003134/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3135/// special functions, such as the default constructor, copy
3136/// constructor, or destructor, to the given C++ class (C++
3137/// [special]p1). This routine can only be executed just before the
3138/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003139void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00003140 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003141 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003142
Douglas Gregor54be3392010-07-01 17:57:27 +00003143 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00003144 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003145
Douglas Gregor330b9cf2010-07-02 21:50:04 +00003146 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3147 ++ASTContext::NumImplicitCopyAssignmentOperators;
3148
3149 // If we have a dynamic class, then the copy assignment operator may be
3150 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3151 // it shows up in the right place in the vtable and that we diagnose
3152 // problems with the implicit exception specification.
3153 if (ClassDecl->isDynamicClass())
3154 DeclareImplicitCopyAssignment(ClassDecl);
3155 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003156
Douglas Gregor7454c562010-07-02 20:37:36 +00003157 if (!ClassDecl->hasUserDeclaredDestructor()) {
3158 ++ASTContext::NumImplicitDestructors;
3159
3160 // If we have a dynamic class, then the destructor may be virtual, so we
3161 // have to declare the destructor immediately. This ensures that, e.g., it
3162 // shows up in the right place in the vtable and that we diagnose problems
3163 // with the implicit exception specification.
3164 if (ClassDecl->isDynamicClass())
3165 DeclareImplicitDestructor(ClassDecl);
3166 }
Douglas Gregor05379422008-11-03 17:51:48 +00003167}
3168
Francois Pichet1c229c02011-04-22 22:18:13 +00003169void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3170 if (!D)
3171 return;
3172
3173 int NumParamList = D->getNumTemplateParameterLists();
3174 for (int i = 0; i < NumParamList; i++) {
3175 TemplateParameterList* Params = D->getTemplateParameterList(i);
3176 for (TemplateParameterList::iterator Param = Params->begin(),
3177 ParamEnd = Params->end();
3178 Param != ParamEnd; ++Param) {
3179 NamedDecl *Named = cast<NamedDecl>(*Param);
3180 if (Named->getDeclName()) {
3181 S->AddDecl(Named);
3182 IdResolver.AddDecl(Named);
3183 }
3184 }
3185 }
3186}
3187
John McCall48871652010-08-21 09:40:31 +00003188void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003189 if (!D)
3190 return;
3191
3192 TemplateParameterList *Params = 0;
3193 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3194 Params = Template->getTemplateParameters();
3195 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3196 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3197 Params = PartialSpec->getTemplateParameters();
3198 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003199 return;
3200
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003201 for (TemplateParameterList::iterator Param = Params->begin(),
3202 ParamEnd = Params->end();
3203 Param != ParamEnd; ++Param) {
3204 NamedDecl *Named = cast<NamedDecl>(*Param);
3205 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003206 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003207 IdResolver.AddDecl(Named);
3208 }
3209 }
3210}
3211
John McCall48871652010-08-21 09:40:31 +00003212void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003213 if (!RecordD) return;
3214 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003215 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003216 PushDeclContext(S, Record);
3217}
3218
John McCall48871652010-08-21 09:40:31 +00003219void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003220 if (!RecordD) return;
3221 PopDeclContext();
3222}
3223
Douglas Gregor4d87df52008-12-16 21:30:33 +00003224/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3225/// parsing a top-level (non-nested) C++ class, and we are now
3226/// parsing those parts of the given Method declaration that could
3227/// not be parsed earlier (C++ [class.mem]p2), such as default
3228/// arguments. This action should enter the scope of the given
3229/// Method declaration as if we had just parsed the qualified method
3230/// name. However, it should not bring the parameters into scope;
3231/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003232void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003233}
3234
3235/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3236/// C++ method declaration. We're (re-)introducing the given
3237/// function parameter into scope for use in parsing later parts of
3238/// the method declaration. For example, we could see an
3239/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003240void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003241 if (!ParamD)
3242 return;
Mike Stump11289f42009-09-09 15:08:12 +00003243
John McCall48871652010-08-21 09:40:31 +00003244 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003245
3246 // If this parameter has an unparsed default argument, clear it out
3247 // to make way for the parsed default argument.
3248 if (Param->hasUnparsedDefaultArg())
3249 Param->setDefaultArg(0);
3250
John McCall48871652010-08-21 09:40:31 +00003251 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003252 if (Param->getDeclName())
3253 IdResolver.AddDecl(Param);
3254}
3255
3256/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3257/// processing the delayed method declaration for Method. The method
3258/// declaration is now considered finished. There may be a separate
3259/// ActOnStartOfFunctionDef action later (not necessarily
3260/// immediately!) for this method, if it was also defined inside the
3261/// class body.
John McCall48871652010-08-21 09:40:31 +00003262void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003263 if (!MethodD)
3264 return;
Mike Stump11289f42009-09-09 15:08:12 +00003265
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003266 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003267
John McCall48871652010-08-21 09:40:31 +00003268 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003269
3270 // Now that we have our default arguments, check the constructor
3271 // again. It could produce additional diagnostics or affect whether
3272 // the class has implicitly-declared destructors, among other
3273 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003274 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3275 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003276
3277 // Check the default arguments, which we may have added.
3278 if (!Method->isInvalidDecl())
3279 CheckCXXDefaultArguments(Method);
3280}
3281
Douglas Gregor831c93f2008-11-05 20:51:48 +00003282/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003283/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003284/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003285/// emit diagnostics and set the invalid bit to true. In any case, the type
3286/// will be updated to reflect a well-formed type for the constructor and
3287/// returned.
3288QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003289 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003290 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003291
3292 // C++ [class.ctor]p3:
3293 // A constructor shall not be virtual (10.3) or static (9.4). A
3294 // constructor can be invoked for a const, volatile or const
3295 // volatile object. A constructor shall not be declared const,
3296 // volatile, or const volatile (9.3.2).
3297 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003298 if (!D.isInvalidType())
3299 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3300 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3301 << SourceRange(D.getIdentifierLoc());
3302 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003303 }
John McCall8e7d6562010-08-26 03:08:43 +00003304 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003305 if (!D.isInvalidType())
3306 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3307 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3308 << SourceRange(D.getIdentifierLoc());
3309 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003310 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003311 }
Mike Stump11289f42009-09-09 15:08:12 +00003312
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003313 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003314 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003315 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3317 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003318 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003319 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3320 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003321 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003322 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3323 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003324 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003325 }
Mike Stump11289f42009-09-09 15:08:12 +00003326
Douglas Gregordb9d6642011-01-26 05:01:58 +00003327 // C++0x [class.ctor]p4:
3328 // A constructor shall not be declared with a ref-qualifier.
3329 if (FTI.hasRefQualifier()) {
3330 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3331 << FTI.RefQualifierIsLValueRef
3332 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3333 D.setInvalidType();
3334 }
3335
Douglas Gregor831c93f2008-11-05 20:51:48 +00003336 // Rebuild the function type "R" without any type qualifiers (in
3337 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003338 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003339 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003340 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3341 return R;
3342
3343 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3344 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003345 EPI.RefQualifier = RQ_None;
3346
Chris Lattner38378bf2009-04-25 08:28:21 +00003347 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003348 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003349}
3350
Douglas Gregor4d87df52008-12-16 21:30:33 +00003351/// CheckConstructor - Checks a fully-formed constructor for
3352/// well-formedness, issuing any diagnostics required. Returns true if
3353/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003354void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003355 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003356 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3357 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003358 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003359
3360 // C++ [class.copy]p3:
3361 // A declaration of a constructor for a class X is ill-formed if
3362 // its first parameter is of type (optionally cv-qualified) X and
3363 // either there are no other parameters or else all other
3364 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003365 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003366 ((Constructor->getNumParams() == 1) ||
3367 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003368 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3369 Constructor->getTemplateSpecializationKind()
3370 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003371 QualType ParamType = Constructor->getParamDecl(0)->getType();
3372 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3373 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003374 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003375 const char *ConstRef
3376 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3377 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003378 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003379 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003380
3381 // FIXME: Rather that making the constructor invalid, we should endeavor
3382 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003383 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003384 }
3385 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003386}
3387
John McCalldeb646e2010-08-04 01:04:25 +00003388/// CheckDestructor - Checks a fully-formed destructor definition for
3389/// well-formedness, issuing any diagnostics required. Returns true
3390/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003391bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003392 CXXRecordDecl *RD = Destructor->getParent();
3393
3394 if (Destructor->isVirtual()) {
3395 SourceLocation Loc;
3396
3397 if (!Destructor->isImplicit())
3398 Loc = Destructor->getLocation();
3399 else
3400 Loc = RD->getLocation();
3401
3402 // If we have a virtual destructor, look up the deallocation function
3403 FunctionDecl *OperatorDelete = 0;
3404 DeclarationName Name =
3405 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003406 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003407 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003408
3409 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003410
3411 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003412 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003413
3414 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003415}
3416
Mike Stump11289f42009-09-09 15:08:12 +00003417static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003418FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3419 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3420 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003421 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003422}
3423
Douglas Gregor831c93f2008-11-05 20:51:48 +00003424/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3425/// the well-formednes of the destructor declarator @p D with type @p
3426/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003427/// emit diagnostics and set the declarator to invalid. Even if this happens,
3428/// will be updated to reflect a well-formed type for the destructor and
3429/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003430QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003431 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003432 // C++ [class.dtor]p1:
3433 // [...] A typedef-name that names a class is a class-name
3434 // (7.1.3); however, a typedef-name that names a class shall not
3435 // be used as the identifier in the declarator for a destructor
3436 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003437 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00003438 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00003439 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00003440 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003441
3442 // C++ [class.dtor]p2:
3443 // A destructor is used to destroy objects of its class type. A
3444 // destructor takes no parameters, and no return type can be
3445 // specified for it (not even void). The address of a destructor
3446 // shall not be taken. A destructor shall not be static. A
3447 // destructor can be invoked for a const, volatile or const
3448 // volatile object. A destructor shall not be declared const,
3449 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003450 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003451 if (!D.isInvalidType())
3452 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3453 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003454 << SourceRange(D.getIdentifierLoc())
3455 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3456
John McCall8e7d6562010-08-26 03:08:43 +00003457 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003458 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003459 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003460 // Destructors don't have return types, but the parser will
3461 // happily parse something like:
3462 //
3463 // class X {
3464 // float ~X();
3465 // };
3466 //
3467 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003468 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3469 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3470 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003471 }
Mike Stump11289f42009-09-09 15:08:12 +00003472
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003473 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003474 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003475 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003476 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3477 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003478 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003479 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3480 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003481 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003482 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3483 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003484 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003485 }
3486
Douglas Gregordb9d6642011-01-26 05:01:58 +00003487 // C++0x [class.dtor]p2:
3488 // A destructor shall not be declared with a ref-qualifier.
3489 if (FTI.hasRefQualifier()) {
3490 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3491 << FTI.RefQualifierIsLValueRef
3492 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3493 D.setInvalidType();
3494 }
3495
Douglas Gregor831c93f2008-11-05 20:51:48 +00003496 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003497 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003498 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3499
3500 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003501 FTI.freeArgs();
3502 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003503 }
3504
Mike Stump11289f42009-09-09 15:08:12 +00003505 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003506 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003507 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003508 D.setInvalidType();
3509 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003510
3511 // Rebuild the function type "R" without any type qualifiers or
3512 // parameters (in case any of the errors above fired) and with
3513 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003514 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003515 if (!D.isInvalidType())
3516 return R;
3517
Douglas Gregor95755162010-07-01 05:10:53 +00003518 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003519 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3520 EPI.Variadic = false;
3521 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003522 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003523 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003524}
3525
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003526/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3527/// well-formednes of the conversion function declarator @p D with
3528/// type @p R. If there are any errors in the declarator, this routine
3529/// will emit diagnostics and return true. Otherwise, it will return
3530/// false. Either way, the type @p R will be updated to reflect a
3531/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003532void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003533 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003534 // C++ [class.conv.fct]p1:
3535 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003536 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003537 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003538 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003539 if (!D.isInvalidType())
3540 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3541 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3542 << SourceRange(D.getIdentifierLoc());
3543 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003544 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003545 }
John McCall212fa2e2010-04-13 00:04:31 +00003546
3547 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3548
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003549 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003550 // Conversion functions don't have return types, but the parser will
3551 // happily parse something like:
3552 //
3553 // class X {
3554 // float operator bool();
3555 // };
3556 //
3557 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003558 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3559 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3560 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003561 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003562 }
3563
John McCall212fa2e2010-04-13 00:04:31 +00003564 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3565
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003566 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003567 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003568 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3569
3570 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003571 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003572 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003573 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003574 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003575 D.setInvalidType();
3576 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003577
John McCall212fa2e2010-04-13 00:04:31 +00003578 // Diagnose "&operator bool()" and other such nonsense. This
3579 // is actually a gcc extension which we don't support.
3580 if (Proto->getResultType() != ConvType) {
3581 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3582 << Proto->getResultType();
3583 D.setInvalidType();
3584 ConvType = Proto->getResultType();
3585 }
3586
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003587 // C++ [class.conv.fct]p4:
3588 // The conversion-type-id shall not represent a function type nor
3589 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003590 if (ConvType->isArrayType()) {
3591 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3592 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003593 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003594 } else if (ConvType->isFunctionType()) {
3595 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3596 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003597 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003598 }
3599
3600 // Rebuild the function type "R" without any parameters (in case any
3601 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003602 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003603 if (D.isInvalidType())
3604 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003605
Douglas Gregor5fb53972009-01-14 15:45:31 +00003606 // C++0x explicit conversion operators.
3607 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003608 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003609 diag::warn_explicit_conversion_functions)
3610 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003611}
3612
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003613/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3614/// the declaration of the given C++ conversion function. This routine
3615/// is responsible for recording the conversion function in the C++
3616/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003617Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003618 assert(Conversion && "Expected to receive a conversion function declaration");
3619
Douglas Gregor4287b372008-12-12 08:25:50 +00003620 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003621
3622 // Make sure we aren't redeclaring the conversion function.
3623 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003624
3625 // C++ [class.conv.fct]p1:
3626 // [...] A conversion function is never used to convert a
3627 // (possibly cv-qualified) object to the (possibly cv-qualified)
3628 // same object type (or a reference to it), to a (possibly
3629 // cv-qualified) base class of that type (or a reference to it),
3630 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003631 // FIXME: Suppress this warning if the conversion function ends up being a
3632 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003633 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003634 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003635 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003636 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003637 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3638 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003639 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003640 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003641 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3642 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003643 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003644 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003645 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003646 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003647 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003648 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003649 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003650 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003651 }
3652
Douglas Gregor457104e2010-09-29 04:25:11 +00003653 if (FunctionTemplateDecl *ConversionTemplate
3654 = Conversion->getDescribedFunctionTemplate())
3655 return ConversionTemplate;
3656
John McCall48871652010-08-21 09:40:31 +00003657 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003658}
3659
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003660//===----------------------------------------------------------------------===//
3661// Namespace Handling
3662//===----------------------------------------------------------------------===//
3663
John McCallb1be5232010-08-26 09:15:37 +00003664
3665
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003666/// ActOnStartNamespaceDef - This is called at the start of a namespace
3667/// definition.
John McCall48871652010-08-21 09:40:31 +00003668Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003669 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003670 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00003671 SourceLocation IdentLoc,
3672 IdentifierInfo *II,
3673 SourceLocation LBrace,
3674 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003675 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3676 // For anonymous namespace, take the location of the left brace.
3677 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00003678 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003679 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003680 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003681
3682 Scope *DeclRegionScope = NamespcScope->getParent();
3683
Anders Carlssona7bcade2010-02-07 01:09:23 +00003684 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3685
John McCall2faf32c2010-12-10 02:59:44 +00003686 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3687 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003688
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003689 if (II) {
3690 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003691 // The identifier in an original-namespace-definition shall not
3692 // have been previously defined in the declarative region in
3693 // which the original-namespace-definition appears. The
3694 // identifier in an original-namespace-definition is the name of
3695 // the namespace. Subsequently in that declarative region, it is
3696 // treated as an original-namespace-name.
3697 //
3698 // Since namespace names are unique in their scope, and we don't
3699 // look through using directives, just
3700 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3701 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregor91f84212008-12-11 16:49:14 +00003703 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3704 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003705 if (Namespc->isInline() != OrigNS->isInline()) {
3706 // inline-ness must match
3707 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3708 << Namespc->isInline();
3709 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3710 Namespc->setInvalidDecl();
3711 // Recover by ignoring the new namespace's inline status.
3712 Namespc->setInline(OrigNS->isInline());
3713 }
3714
Douglas Gregor91f84212008-12-11 16:49:14 +00003715 // Attach this namespace decl to the chain of extended namespace
3716 // definitions.
3717 OrigNS->setNextNamespace(Namespc);
3718 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003719
Mike Stump11289f42009-09-09 15:08:12 +00003720 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003721 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003722 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003723 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003724 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003725 } else if (PrevDecl) {
3726 // This is an invalid name redefinition.
3727 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3728 << Namespc->getDeclName();
3729 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3730 Namespc->setInvalidDecl();
3731 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003732 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003733 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003734 // This is the first "real" definition of the namespace "std", so update
3735 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003736 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003737 // We had already defined a dummy namespace "std". Link this new
3738 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003739 StdNS->setNextNamespace(Namespc);
3740 StdNS->setLocation(IdentLoc);
3741 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003742 }
3743
3744 // Make our StdNamespace cache point at the first real definition of the
3745 // "std" namespace.
3746 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003747 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003748
3749 PushOnScopeChains(Namespc, DeclRegionScope);
3750 } else {
John McCall4fa53422009-10-01 00:25:31 +00003751 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003752 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003753
3754 // Link the anonymous namespace into its parent.
3755 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003756 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003757 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3758 PrevDecl = TU->getAnonymousNamespace();
3759 TU->setAnonymousNamespace(Namespc);
3760 } else {
3761 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3762 PrevDecl = ND->getAnonymousNamespace();
3763 ND->setAnonymousNamespace(Namespc);
3764 }
3765
3766 // Link the anonymous namespace with its previous declaration.
3767 if (PrevDecl) {
3768 assert(PrevDecl->isAnonymousNamespace());
3769 assert(!PrevDecl->getNextNamespace());
3770 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3771 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003772
3773 if (Namespc->isInline() != PrevDecl->isInline()) {
3774 // inline-ness must match
3775 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3776 << Namespc->isInline();
3777 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3778 Namespc->setInvalidDecl();
3779 // Recover by ignoring the new namespace's inline status.
3780 Namespc->setInline(PrevDecl->isInline());
3781 }
John McCall0db42252009-12-16 02:06:49 +00003782 }
John McCall4fa53422009-10-01 00:25:31 +00003783
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003784 CurContext->addDecl(Namespc);
3785
John McCall4fa53422009-10-01 00:25:31 +00003786 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3787 // behaves as if it were replaced by
3788 // namespace unique { /* empty body */ }
3789 // using namespace unique;
3790 // namespace unique { namespace-body }
3791 // where all occurrences of 'unique' in a translation unit are
3792 // replaced by the same identifier and this identifier differs
3793 // from all other identifiers in the entire program.
3794
3795 // We just create the namespace with an empty name and then add an
3796 // implicit using declaration, just like the standard suggests.
3797 //
3798 // CodeGen enforces the "universally unique" aspect by giving all
3799 // declarations semantically contained within an anonymous
3800 // namespace internal linkage.
3801
John McCall0db42252009-12-16 02:06:49 +00003802 if (!PrevDecl) {
3803 UsingDirectiveDecl* UD
3804 = UsingDirectiveDecl::Create(Context, CurContext,
3805 /* 'using' */ LBrace,
3806 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00003807 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00003808 /* identifier */ SourceLocation(),
3809 Namespc,
3810 /* Ancestor */ CurContext);
3811 UD->setImplicit();
3812 CurContext->addDecl(UD);
3813 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003814 }
3815
3816 // Although we could have an invalid decl (i.e. the namespace name is a
3817 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003818 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3819 // for the namespace has the declarations that showed up in that particular
3820 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003821 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003822 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003823}
3824
Sebastian Redla6602e92009-11-23 15:34:23 +00003825/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3826/// is a namespace alias, returns the namespace it points to.
3827static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3828 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3829 return AD->getNamespace();
3830 return dyn_cast_or_null<NamespaceDecl>(D);
3831}
3832
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003833/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3834/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003835void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003836 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3837 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003838 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003839 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003840 if (Namespc->hasAttr<VisibilityAttr>())
3841 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003842}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003843
John McCall28a0cf72010-08-25 07:42:41 +00003844CXXRecordDecl *Sema::getStdBadAlloc() const {
3845 return cast_or_null<CXXRecordDecl>(
3846 StdBadAlloc.get(Context.getExternalSource()));
3847}
3848
3849NamespaceDecl *Sema::getStdNamespace() const {
3850 return cast_or_null<NamespaceDecl>(
3851 StdNamespace.get(Context.getExternalSource()));
3852}
3853
Douglas Gregorcdf87022010-06-29 17:53:46 +00003854/// \brief Retrieve the special "std" namespace, which may require us to
3855/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003856NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003857 if (!StdNamespace) {
3858 // The "std" namespace has not yet been defined, so build one implicitly.
3859 StdNamespace = NamespaceDecl::Create(Context,
3860 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003861 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00003862 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003863 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003864 }
3865
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003866 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003867}
3868
Douglas Gregora172e082011-03-26 22:25:30 +00003869/// \brief Determine whether a using statement is in a context where it will be
3870/// apply in all contexts.
3871static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3872 switch (CurContext->getDeclKind()) {
3873 case Decl::TranslationUnit:
3874 return true;
3875 case Decl::LinkageSpec:
3876 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3877 default:
3878 return false;
3879 }
3880}
3881
John McCall48871652010-08-21 09:40:31 +00003882Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003883 SourceLocation UsingLoc,
3884 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003885 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003886 SourceLocation IdentLoc,
3887 IdentifierInfo *NamespcName,
3888 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003889 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3890 assert(NamespcName && "Invalid NamespcName.");
3891 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003892
3893 // This can only happen along a recovery path.
3894 while (S->getFlags() & Scope::TemplateParamScope)
3895 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003896 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003897
Douglas Gregor889ceb72009-02-03 19:21:40 +00003898 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003899 NestedNameSpecifier *Qualifier = 0;
3900 if (SS.isSet())
3901 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3902
Douglas Gregor34074322009-01-14 22:20:51 +00003903 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003904 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3905 LookupParsedName(R, S, &SS);
3906 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003907 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003908
Douglas Gregorcdf87022010-06-29 17:53:46 +00003909 if (R.empty()) {
3910 // Allow "using namespace std;" or "using namespace ::std;" even if
3911 // "std" hasn't been defined yet, for GCC compatibility.
3912 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3913 NamespcName->isStr("std")) {
3914 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003915 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003916 R.resolveKind();
3917 }
3918 // Otherwise, attempt typo correction.
3919 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3920 CTC_NoKeywords, 0)) {
3921 if (R.getAsSingle<NamespaceDecl>() ||
3922 R.getAsSingle<NamespaceAliasDecl>()) {
3923 if (DeclContext *DC = computeDeclContext(SS, false))
3924 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3925 << NamespcName << DC << Corrected << SS.getRange()
3926 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3927 else
3928 Diag(IdentLoc, diag::err_using_directive_suggest)
3929 << NamespcName << Corrected
3930 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3931 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3932 << Corrected;
3933
3934 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003935 } else {
3936 R.clear();
3937 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003938 }
3939 }
3940 }
3941
John McCall9f3059a2009-10-09 21:13:30 +00003942 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003943 NamedDecl *Named = R.getFoundDecl();
3944 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3945 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003946 // C++ [namespace.udir]p1:
3947 // A using-directive specifies that the names in the nominated
3948 // namespace can be used in the scope in which the
3949 // using-directive appears after the using-directive. During
3950 // unqualified name lookup (3.4.1), the names appear as if they
3951 // were declared in the nearest enclosing namespace which
3952 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003953 // namespace. [Note: in this context, "contains" means "contains
3954 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003955
3956 // Find enclosing context containing both using-directive and
3957 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003958 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003959 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3960 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3961 CommonAncestor = CommonAncestor->getParent();
3962
Sebastian Redla6602e92009-11-23 15:34:23 +00003963 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00003964 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00003965 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00003966
Douglas Gregora172e082011-03-26 22:25:30 +00003967 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00003968 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00003969 Diag(IdentLoc, diag::warn_using_directive_in_header);
3970 }
3971
Douglas Gregor889ceb72009-02-03 19:21:40 +00003972 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003973 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003974 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003975 }
3976
Douglas Gregor889ceb72009-02-03 19:21:40 +00003977 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003978 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003979}
3980
3981void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3982 // If scope has associated entity, then using directive is at namespace
3983 // or translation unit scope. We add UsingDirectiveDecls, into
3984 // it's lookup structure.
3985 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003986 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003987 else
3988 // Otherwise it is block-sope. using-directives will affect lookup
3989 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003990 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003991}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003992
Douglas Gregorfec52632009-06-20 00:51:54 +00003993
John McCall48871652010-08-21 09:40:31 +00003994Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003995 AccessSpecifier AS,
3996 bool HasUsingKeyword,
3997 SourceLocation UsingLoc,
3998 CXXScopeSpec &SS,
3999 UnqualifiedId &Name,
4000 AttributeList *AttrList,
4001 bool IsTypeName,
4002 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004003 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004004
Douglas Gregor220f4272009-11-04 16:30:06 +00004005 switch (Name.getKind()) {
4006 case UnqualifiedId::IK_Identifier:
4007 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004008 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004009 case UnqualifiedId::IK_ConversionFunctionId:
4010 break;
4011
4012 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004013 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004014 // C++0x inherited constructors.
4015 if (getLangOptions().CPlusPlus0x) break;
4016
Douglas Gregor220f4272009-11-04 16:30:06 +00004017 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4018 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004019 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004020
4021 case UnqualifiedId::IK_DestructorName:
4022 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4023 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004024 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004025
4026 case UnqualifiedId::IK_TemplateId:
4027 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4028 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00004029 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004030 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004031
4032 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4033 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00004034 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00004035 return 0;
John McCall3969e302009-12-08 07:46:18 +00004036
John McCalla0097262009-12-11 02:10:03 +00004037 // Warn about using declarations.
4038 // TODO: store that the declaration was written without 'using' and
4039 // talk about access decls instead of using decls in the
4040 // diagnostics.
4041 if (!HasUsingKeyword) {
4042 UsingLoc = Name.getSourceRange().getBegin();
4043
4044 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00004045 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00004046 }
4047
Douglas Gregorc4356532010-12-16 00:46:58 +00004048 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4049 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4050 return 0;
4051
John McCall3f746822009-11-17 05:59:44 +00004052 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004053 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004054 /* IsInstantiation */ false,
4055 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00004056 if (UD)
4057 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00004058
John McCall48871652010-08-21 09:40:31 +00004059 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00004060}
4061
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004062/// \brief Determine whether a using declaration considers the given
4063/// declarations as "equivalent", e.g., if they are redeclarations of
4064/// the same entity or are both typedefs of the same type.
4065static bool
4066IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4067 bool &SuppressRedeclaration) {
4068 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4069 SuppressRedeclaration = false;
4070 return true;
4071 }
4072
Richard Smithdda56e42011-04-15 14:24:37 +00004073 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4074 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004075 SuppressRedeclaration = true;
4076 return Context.hasSameType(TD1->getUnderlyingType(),
4077 TD2->getUnderlyingType());
4078 }
4079
4080 return false;
4081}
4082
4083
John McCall84d87672009-12-10 09:41:52 +00004084/// Determines whether to create a using shadow decl for a particular
4085/// decl, given the set of decls existing prior to this using lookup.
4086bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4087 const LookupResult &Previous) {
4088 // Diagnose finding a decl which is not from a base class of the
4089 // current class. We do this now because there are cases where this
4090 // function will silently decide not to build a shadow decl, which
4091 // will pre-empt further diagnostics.
4092 //
4093 // We don't need to do this in C++0x because we do the check once on
4094 // the qualifier.
4095 //
4096 // FIXME: diagnose the following if we care enough:
4097 // struct A { int foo; };
4098 // struct B : A { using A::foo; };
4099 // template <class T> struct C : A {};
4100 // template <class T> struct D : C<T> { using B::foo; } // <---
4101 // This is invalid (during instantiation) in C++03 because B::foo
4102 // resolves to the using decl in B, which is not a base class of D<T>.
4103 // We can't diagnose it immediately because C<T> is an unknown
4104 // specialization. The UsingShadowDecl in D<T> then points directly
4105 // to A::foo, which will look well-formed when we instantiate.
4106 // The right solution is to not collapse the shadow-decl chain.
4107 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4108 DeclContext *OrigDC = Orig->getDeclContext();
4109
4110 // Handle enums and anonymous structs.
4111 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4112 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4113 while (OrigRec->isAnonymousStructOrUnion())
4114 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4115
4116 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4117 if (OrigDC == CurContext) {
4118 Diag(Using->getLocation(),
4119 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004120 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004121 Diag(Orig->getLocation(), diag::note_using_decl_target);
4122 return true;
4123 }
4124
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004125 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00004126 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004127 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00004128 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004129 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004130 Diag(Orig->getLocation(), diag::note_using_decl_target);
4131 return true;
4132 }
4133 }
4134
4135 if (Previous.empty()) return false;
4136
4137 NamedDecl *Target = Orig;
4138 if (isa<UsingShadowDecl>(Target))
4139 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4140
John McCalla17e83e2009-12-11 02:33:26 +00004141 // If the target happens to be one of the previous declarations, we
4142 // don't have a conflict.
4143 //
4144 // FIXME: but we might be increasing its access, in which case we
4145 // should redeclare it.
4146 NamedDecl *NonTag = 0, *Tag = 0;
4147 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4148 I != E; ++I) {
4149 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004150 bool Result;
4151 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4152 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00004153
4154 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4155 }
4156
John McCall84d87672009-12-10 09:41:52 +00004157 if (Target->isFunctionOrFunctionTemplate()) {
4158 FunctionDecl *FD;
4159 if (isa<FunctionTemplateDecl>(Target))
4160 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4161 else
4162 FD = cast<FunctionDecl>(Target);
4163
4164 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00004165 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00004166 case Ovl_Overload:
4167 return false;
4168
4169 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00004170 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004171 break;
4172
4173 // We found a decl with the exact signature.
4174 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004175 // If we're in a record, we want to hide the target, so we
4176 // return true (without a diagnostic) to tell the caller not to
4177 // build a shadow decl.
4178 if (CurContext->isRecord())
4179 return true;
4180
4181 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00004182 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004183 break;
4184 }
4185
4186 Diag(Target->getLocation(), diag::note_using_decl_target);
4187 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4188 return true;
4189 }
4190
4191 // Target is not a function.
4192
John McCall84d87672009-12-10 09:41:52 +00004193 if (isa<TagDecl>(Target)) {
4194 // No conflict between a tag and a non-tag.
4195 if (!Tag) return false;
4196
John McCalle29c5cd2009-12-10 19:51:03 +00004197 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004198 Diag(Target->getLocation(), diag::note_using_decl_target);
4199 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4200 return true;
4201 }
4202
4203 // No conflict between a tag and a non-tag.
4204 if (!NonTag) return false;
4205
John McCalle29c5cd2009-12-10 19:51:03 +00004206 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004207 Diag(Target->getLocation(), diag::note_using_decl_target);
4208 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4209 return true;
4210}
4211
John McCall3f746822009-11-17 05:59:44 +00004212/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004213UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004214 UsingDecl *UD,
4215 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004216
4217 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004218 NamedDecl *Target = Orig;
4219 if (isa<UsingShadowDecl>(Target)) {
4220 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4221 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004222 }
4223
4224 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004225 = UsingShadowDecl::Create(Context, CurContext,
4226 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004227 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004228
4229 Shadow->setAccess(UD->getAccess());
4230 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4231 Shadow->setInvalidDecl();
4232
John McCall3f746822009-11-17 05:59:44 +00004233 if (S)
John McCall3969e302009-12-08 07:46:18 +00004234 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004235 else
John McCall3969e302009-12-08 07:46:18 +00004236 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004237
John McCall3969e302009-12-08 07:46:18 +00004238
John McCall84d87672009-12-10 09:41:52 +00004239 return Shadow;
4240}
John McCall3969e302009-12-08 07:46:18 +00004241
John McCall84d87672009-12-10 09:41:52 +00004242/// Hides a using shadow declaration. This is required by the current
4243/// using-decl implementation when a resolvable using declaration in a
4244/// class is followed by a declaration which would hide or override
4245/// one or more of the using decl's targets; for example:
4246///
4247/// struct Base { void foo(int); };
4248/// struct Derived : Base {
4249/// using Base::foo;
4250/// void foo(int);
4251/// };
4252///
4253/// The governing language is C++03 [namespace.udecl]p12:
4254///
4255/// When a using-declaration brings names from a base class into a
4256/// derived class scope, member functions in the derived class
4257/// override and/or hide member functions with the same name and
4258/// parameter types in a base class (rather than conflicting).
4259///
4260/// There are two ways to implement this:
4261/// (1) optimistically create shadow decls when they're not hidden
4262/// by existing declarations, or
4263/// (2) don't create any shadow decls (or at least don't make them
4264/// visible) until we've fully parsed/instantiated the class.
4265/// The problem with (1) is that we might have to retroactively remove
4266/// a shadow decl, which requires several O(n) operations because the
4267/// decl structures are (very reasonably) not designed for removal.
4268/// (2) avoids this but is very fiddly and phase-dependent.
4269void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004270 if (Shadow->getDeclName().getNameKind() ==
4271 DeclarationName::CXXConversionFunctionName)
4272 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4273
John McCall84d87672009-12-10 09:41:52 +00004274 // Remove it from the DeclContext...
4275 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004276
John McCall84d87672009-12-10 09:41:52 +00004277 // ...and the scope, if applicable...
4278 if (S) {
John McCall48871652010-08-21 09:40:31 +00004279 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004280 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004281 }
4282
John McCall84d87672009-12-10 09:41:52 +00004283 // ...and the using decl.
4284 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4285
4286 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004287 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004288}
4289
John McCalle61f2ba2009-11-18 02:36:19 +00004290/// Builds a using declaration.
4291///
4292/// \param IsInstantiation - Whether this call arises from an
4293/// instantiation of an unresolved using declaration. We treat
4294/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004295NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4296 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004297 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004298 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004299 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004300 bool IsInstantiation,
4301 bool IsTypeName,
4302 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004303 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004304 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004305 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004306
Anders Carlssonf038fc22009-08-28 05:49:21 +00004307 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004308
Anders Carlsson59140b32009-08-28 03:16:11 +00004309 if (SS.isEmpty()) {
4310 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004311 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004312 }
Mike Stump11289f42009-09-09 15:08:12 +00004313
John McCall84d87672009-12-10 09:41:52 +00004314 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004315 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004316 ForRedeclaration);
4317 Previous.setHideTags(false);
4318 if (S) {
4319 LookupName(Previous, S);
4320
4321 // It is really dumb that we have to do this.
4322 LookupResult::Filter F = Previous.makeFilter();
4323 while (F.hasNext()) {
4324 NamedDecl *D = F.next();
4325 if (!isDeclInScope(D, CurContext, S))
4326 F.erase();
4327 }
4328 F.done();
4329 } else {
4330 assert(IsInstantiation && "no scope in non-instantiation");
4331 assert(CurContext->isRecord() && "scope not record in instantiation");
4332 LookupQualifiedName(Previous, CurContext);
4333 }
4334
John McCall84d87672009-12-10 09:41:52 +00004335 // Check for invalid redeclarations.
4336 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4337 return 0;
4338
4339 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004340 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4341 return 0;
4342
John McCall84c16cf2009-11-12 03:15:40 +00004343 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004344 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004345 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004346 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004347 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004348 // FIXME: not all declaration name kinds are legal here
4349 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4350 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004351 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004352 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004353 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004354 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4355 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004356 }
John McCallb96ec562009-12-04 22:46:56 +00004357 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004358 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4359 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004360 }
John McCallb96ec562009-12-04 22:46:56 +00004361 D->setAccess(AS);
4362 CurContext->addDecl(D);
4363
4364 if (!LookupContext) return D;
4365 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004366
John McCall0b66eb32010-05-01 00:40:08 +00004367 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004368 UD->setInvalidDecl();
4369 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004370 }
4371
Sebastian Redl08905022011-02-05 19:23:19 +00004372 // Constructor inheriting using decls get special treatment.
4373 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00004374 if (CheckInheritedConstructorUsingDecl(UD))
4375 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00004376 return UD;
4377 }
4378
4379 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004380
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004381 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004382
John McCall3969e302009-12-08 07:46:18 +00004383 // Unlike most lookups, we don't always want to hide tag
4384 // declarations: tag names are visible through the using declaration
4385 // even if hidden by ordinary names, *except* in a dependent context
4386 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004387 if (!IsInstantiation)
4388 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004389
John McCall27b18f82009-11-17 02:14:36 +00004390 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004391
John McCall9f3059a2009-10-09 21:13:30 +00004392 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004393 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004394 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004395 UD->setInvalidDecl();
4396 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004397 }
4398
John McCallb96ec562009-12-04 22:46:56 +00004399 if (R.isAmbiguous()) {
4400 UD->setInvalidDecl();
4401 return UD;
4402 }
Mike Stump11289f42009-09-09 15:08:12 +00004403
John McCalle61f2ba2009-11-18 02:36:19 +00004404 if (IsTypeName) {
4405 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004406 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004407 Diag(IdentLoc, diag::err_using_typename_non_type);
4408 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4409 Diag((*I)->getUnderlyingDecl()->getLocation(),
4410 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004411 UD->setInvalidDecl();
4412 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004413 }
4414 } else {
4415 // If we asked for a non-typename and we got a type, error out,
4416 // but only if this is an instantiation of an unresolved using
4417 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004418 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004419 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4420 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004421 UD->setInvalidDecl();
4422 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004423 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004424 }
4425
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004426 // C++0x N2914 [namespace.udecl]p6:
4427 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004428 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004429 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4430 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004431 UD->setInvalidDecl();
4432 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004433 }
Mike Stump11289f42009-09-09 15:08:12 +00004434
John McCall84d87672009-12-10 09:41:52 +00004435 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4436 if (!CheckUsingShadowDecl(UD, *I, Previous))
4437 BuildUsingShadowDecl(S, UD, *I);
4438 }
John McCall3f746822009-11-17 05:59:44 +00004439
4440 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004441}
4442
Sebastian Redl08905022011-02-05 19:23:19 +00004443/// Additional checks for a using declaration referring to a constructor name.
4444bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4445 if (UD->isTypeName()) {
4446 // FIXME: Cannot specify typename when specifying constructor
4447 return true;
4448 }
4449
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004450 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004451 assert(SourceType &&
4452 "Using decl naming constructor doesn't have type in scope spec.");
4453 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4454
4455 // Check whether the named type is a direct base class.
4456 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4457 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4458 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4459 BaseIt != BaseE; ++BaseIt) {
4460 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4461 if (CanonicalSourceType == BaseType)
4462 break;
4463 }
4464
4465 if (BaseIt == BaseE) {
4466 // Did not find SourceType in the bases.
4467 Diag(UD->getUsingLocation(),
4468 diag::err_using_decl_constructor_not_in_direct_base)
4469 << UD->getNameInfo().getSourceRange()
4470 << QualType(SourceType, 0) << TargetClass;
4471 return true;
4472 }
4473
4474 BaseIt->setInheritConstructors();
4475
4476 return false;
4477}
4478
John McCall84d87672009-12-10 09:41:52 +00004479/// Checks that the given using declaration is not an invalid
4480/// redeclaration. Note that this is checking only for the using decl
4481/// itself, not for any ill-formedness among the UsingShadowDecls.
4482bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4483 bool isTypeName,
4484 const CXXScopeSpec &SS,
4485 SourceLocation NameLoc,
4486 const LookupResult &Prev) {
4487 // C++03 [namespace.udecl]p8:
4488 // C++0x [namespace.udecl]p10:
4489 // A using-declaration is a declaration and can therefore be used
4490 // repeatedly where (and only where) multiple declarations are
4491 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004492 //
John McCall032092f2010-11-29 18:01:58 +00004493 // That's in non-member contexts.
4494 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004495 return false;
4496
4497 NestedNameSpecifier *Qual
4498 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4499
4500 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4501 NamedDecl *D = *I;
4502
4503 bool DTypename;
4504 NestedNameSpecifier *DQual;
4505 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4506 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004507 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004508 } else if (UnresolvedUsingValueDecl *UD
4509 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4510 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004511 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004512 } else if (UnresolvedUsingTypenameDecl *UD
4513 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4514 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004515 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004516 } else continue;
4517
4518 // using decls differ if one says 'typename' and the other doesn't.
4519 // FIXME: non-dependent using decls?
4520 if (isTypeName != DTypename) continue;
4521
4522 // using decls differ if they name different scopes (but note that
4523 // template instantiation can cause this check to trigger when it
4524 // didn't before instantiation).
4525 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4526 Context.getCanonicalNestedNameSpecifier(DQual))
4527 continue;
4528
4529 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004530 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004531 return true;
4532 }
4533
4534 return false;
4535}
4536
John McCall3969e302009-12-08 07:46:18 +00004537
John McCallb96ec562009-12-04 22:46:56 +00004538/// Checks that the given nested-name qualifier used in a using decl
4539/// in the current context is appropriately related to the current
4540/// scope. If an error is found, diagnoses it and returns true.
4541bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4542 const CXXScopeSpec &SS,
4543 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004544 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004545
John McCall3969e302009-12-08 07:46:18 +00004546 if (!CurContext->isRecord()) {
4547 // C++03 [namespace.udecl]p3:
4548 // C++0x [namespace.udecl]p8:
4549 // A using-declaration for a class member shall be a member-declaration.
4550
4551 // If we weren't able to compute a valid scope, it must be a
4552 // dependent class scope.
4553 if (!NamedContext || NamedContext->isRecord()) {
4554 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4555 << SS.getRange();
4556 return true;
4557 }
4558
4559 // Otherwise, everything is known to be fine.
4560 return false;
4561 }
4562
4563 // The current scope is a record.
4564
4565 // If the named context is dependent, we can't decide much.
4566 if (!NamedContext) {
4567 // FIXME: in C++0x, we can diagnose if we can prove that the
4568 // nested-name-specifier does not refer to a base class, which is
4569 // still possible in some cases.
4570
4571 // Otherwise we have to conservatively report that things might be
4572 // okay.
4573 return false;
4574 }
4575
4576 if (!NamedContext->isRecord()) {
4577 // Ideally this would point at the last name in the specifier,
4578 // but we don't have that level of source info.
4579 Diag(SS.getRange().getBegin(),
4580 diag::err_using_decl_nested_name_specifier_is_not_class)
4581 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4582 return true;
4583 }
4584
Douglas Gregor7c842292010-12-21 07:41:49 +00004585 if (!NamedContext->isDependentContext() &&
4586 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4587 return true;
4588
John McCall3969e302009-12-08 07:46:18 +00004589 if (getLangOptions().CPlusPlus0x) {
4590 // C++0x [namespace.udecl]p3:
4591 // In a using-declaration used as a member-declaration, the
4592 // nested-name-specifier shall name a base class of the class
4593 // being defined.
4594
4595 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4596 cast<CXXRecordDecl>(NamedContext))) {
4597 if (CurContext == NamedContext) {
4598 Diag(NameLoc,
4599 diag::err_using_decl_nested_name_specifier_is_current_class)
4600 << SS.getRange();
4601 return true;
4602 }
4603
4604 Diag(SS.getRange().getBegin(),
4605 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4606 << (NestedNameSpecifier*) SS.getScopeRep()
4607 << cast<CXXRecordDecl>(CurContext)
4608 << SS.getRange();
4609 return true;
4610 }
4611
4612 return false;
4613 }
4614
4615 // C++03 [namespace.udecl]p4:
4616 // A using-declaration used as a member-declaration shall refer
4617 // to a member of a base class of the class being defined [etc.].
4618
4619 // Salient point: SS doesn't have to name a base class as long as
4620 // lookup only finds members from base classes. Therefore we can
4621 // diagnose here only if we can prove that that can't happen,
4622 // i.e. if the class hierarchies provably don't intersect.
4623
4624 // TODO: it would be nice if "definitely valid" results were cached
4625 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4626 // need to be repeated.
4627
4628 struct UserData {
4629 llvm::DenseSet<const CXXRecordDecl*> Bases;
4630
4631 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4632 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4633 Data->Bases.insert(Base);
4634 return true;
4635 }
4636
4637 bool hasDependentBases(const CXXRecordDecl *Class) {
4638 return !Class->forallBases(collect, this);
4639 }
4640
4641 /// Returns true if the base is dependent or is one of the
4642 /// accumulated base classes.
4643 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4644 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4645 return !Data->Bases.count(Base);
4646 }
4647
4648 bool mightShareBases(const CXXRecordDecl *Class) {
4649 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4650 }
4651 };
4652
4653 UserData Data;
4654
4655 // Returns false if we find a dependent base.
4656 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4657 return false;
4658
4659 // Returns false if the class has a dependent base or if it or one
4660 // of its bases is present in the base set of the current context.
4661 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4662 return false;
4663
4664 Diag(SS.getRange().getBegin(),
4665 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4666 << (NestedNameSpecifier*) SS.getScopeRep()
4667 << cast<CXXRecordDecl>(CurContext)
4668 << SS.getRange();
4669
4670 return true;
John McCallb96ec562009-12-04 22:46:56 +00004671}
4672
Richard Smithdda56e42011-04-15 14:24:37 +00004673Decl *Sema::ActOnAliasDeclaration(Scope *S,
4674 AccessSpecifier AS,
4675 SourceLocation UsingLoc,
4676 UnqualifiedId &Name,
4677 TypeResult Type) {
4678 assert((S->getFlags() & Scope::DeclScope) &&
4679 "got alias-declaration outside of declaration scope");
4680
4681 if (Type.isInvalid())
4682 return 0;
4683
4684 bool Invalid = false;
4685 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4686 TypeSourceInfo *TInfo = 0;
4687 QualType T = GetTypeFromParser(Type.get(), &TInfo);
4688
4689 if (DiagnoseClassNameShadow(CurContext, NameInfo))
4690 return 0;
4691
4692 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
4693 UPPC_DeclarationType))
4694 Invalid = true;
4695
4696 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4697 LookupName(Previous, S);
4698
4699 // Warn about shadowing the name of a template parameter.
4700 if (Previous.isSingleResult() &&
4701 Previous.getFoundDecl()->isTemplateParameter()) {
4702 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4703 Previous.getFoundDecl()))
4704 Invalid = true;
4705 Previous.clear();
4706 }
4707
4708 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4709 "name in alias declaration must be an identifier");
4710 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4711 Name.StartLocation,
4712 Name.Identifier, TInfo);
4713
4714 NewTD->setAccess(AS);
4715
4716 if (Invalid)
4717 NewTD->setInvalidDecl();
4718
4719 bool Redeclaration = false;
4720 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4721
4722 if (!Redeclaration)
4723 PushOnScopeChains(NewTD, S);
4724
4725 return NewTD;
4726}
4727
John McCall48871652010-08-21 09:40:31 +00004728Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004729 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004730 SourceLocation AliasLoc,
4731 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004732 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004733 SourceLocation IdentLoc,
4734 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004735
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004736 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004737 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4738 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004739
Anders Carlssondca83c42009-03-28 06:23:46 +00004740 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004741 NamedDecl *PrevDecl
4742 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4743 ForRedeclaration);
4744 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4745 PrevDecl = 0;
4746
4747 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004748 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004749 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004750 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004751 // FIXME: At some point, we'll want to create the (redundant)
4752 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004753 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004754 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004755 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004756 }
Mike Stump11289f42009-09-09 15:08:12 +00004757
Anders Carlssondca83c42009-03-28 06:23:46 +00004758 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4759 diag::err_redefinition_different_kind;
4760 Diag(AliasLoc, DiagID) << Alias;
4761 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004762 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004763 }
4764
John McCall27b18f82009-11-17 02:14:36 +00004765 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004766 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004767
John McCall9f3059a2009-10-09 21:13:30 +00004768 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004769 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4770 CTC_NoKeywords, 0)) {
4771 if (R.getAsSingle<NamespaceDecl>() ||
4772 R.getAsSingle<NamespaceAliasDecl>()) {
4773 if (DeclContext *DC = computeDeclContext(SS, false))
4774 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4775 << Ident << DC << Corrected << SS.getRange()
4776 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4777 else
4778 Diag(IdentLoc, diag::err_using_directive_suggest)
4779 << Ident << Corrected
4780 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4781
4782 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4783 << Corrected;
4784
4785 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004786 } else {
4787 R.clear();
4788 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004789 }
4790 }
4791
4792 if (R.empty()) {
4793 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004794 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004795 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004796 }
Mike Stump11289f42009-09-09 15:08:12 +00004797
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004798 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004799 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00004800 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00004801 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004802
John McCalld8d0d432010-02-16 06:53:13 +00004803 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004804 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004805}
4806
Douglas Gregora57478e2010-05-01 15:04:51 +00004807namespace {
4808 /// \brief Scoped object used to handle the state changes required in Sema
4809 /// to implicitly define the body of a C++ member function;
4810 class ImplicitlyDefinedFunctionScope {
4811 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00004812 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00004813
4814 public:
4815 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00004816 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00004817 {
Douglas Gregora57478e2010-05-01 15:04:51 +00004818 S.PushFunctionScope();
4819 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4820 }
4821
4822 ~ImplicitlyDefinedFunctionScope() {
4823 S.PopExpressionEvaluationContext();
4824 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00004825 }
4826 };
4827}
4828
Sebastian Redlc15c3262010-09-13 22:02:47 +00004829static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4830 CXXRecordDecl *D) {
4831 ASTContext &Context = Self.Context;
4832 QualType ClassType = Context.getTypeDeclType(D);
4833 DeclarationName ConstructorName
4834 = Context.DeclarationNames.getCXXConstructorName(
4835 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4836
4837 DeclContext::lookup_const_iterator Con, ConEnd;
4838 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4839 Con != ConEnd; ++Con) {
4840 // FIXME: In C++0x, a constructor template can be a default constructor.
4841 if (isa<FunctionTemplateDecl>(*Con))
4842 continue;
4843
4844 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4845 if (Constructor->isDefaultConstructor())
4846 return Constructor;
4847 }
4848 return 0;
4849}
4850
Douglas Gregor0be31a22010-07-02 17:43:08 +00004851CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4852 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004853 // C++ [class.ctor]p5:
4854 // A default constructor for a class X is a constructor of class X
4855 // that can be called without an argument. If there is no
4856 // user-declared constructor for class X, a default constructor is
4857 // implicitly declared. An implicitly-declared default constructor
4858 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004859 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4860 "Should not build implicit default constructor!");
4861
Douglas Gregor6d880b12010-07-01 22:31:05 +00004862 // C++ [except.spec]p14:
4863 // An implicitly declared special member function (Clause 12) shall have an
4864 // exception-specification. [...]
4865 ImplicitExceptionSpecification ExceptSpec(Context);
4866
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004867 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00004868 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4869 BEnd = ClassDecl->bases_end();
4870 B != BEnd; ++B) {
4871 if (B->isVirtual()) // Handled below.
4872 continue;
4873
Douglas Gregor9672f922010-07-03 00:47:00 +00004874 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4875 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4876 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4877 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004878 else if (CXXConstructorDecl *Constructor
4879 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004880 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004881 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004882 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004883
4884 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00004885 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4886 BEnd = ClassDecl->vbases_end();
4887 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004888 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4889 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4890 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4891 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4892 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004893 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004894 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004895 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004896 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004897
4898 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00004899 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4900 FEnd = ClassDecl->field_end();
4901 F != FEnd; ++F) {
4902 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004903 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4904 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4905 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4906 ExceptSpec.CalledDecl(
4907 DeclareImplicitDefaultConstructor(FieldClassDecl));
4908 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004909 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004910 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004911 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004912 }
John McCalldb40c7f2010-12-14 08:05:40 +00004913
4914 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004915 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00004916 EPI.NumExceptions = ExceptSpec.size();
4917 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004918
Douglas Gregor6d880b12010-07-01 22:31:05 +00004919 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004920 CanQualType ClassType
4921 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00004922 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004923 DeclarationName Name
4924 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004925 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004926 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00004927 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004928 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004929 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004930 /*TInfo=*/0,
4931 /*isExplicit=*/false,
4932 /*isInline=*/true,
4933 /*isImplicitlyDeclared=*/true);
4934 DefaultCon->setAccess(AS_public);
4935 DefaultCon->setImplicit();
4936 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004937
4938 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004939 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4940
Douglas Gregor0be31a22010-07-02 17:43:08 +00004941 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004942 PushOnScopeChains(DefaultCon, S, false);
4943 ClassDecl->addDecl(DefaultCon);
4944
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004945 return DefaultCon;
4946}
4947
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004948void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4949 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004950 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004951 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004952 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004953
Anders Carlsson423f5d82010-04-23 16:04:08 +00004954 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004955 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004956
Douglas Gregora57478e2010-05-01 15:04:51 +00004957 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004958 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004959 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004960 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004961 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004962 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004963 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004964 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004965 }
Douglas Gregor73193272010-09-20 16:48:21 +00004966
4967 SourceLocation Loc = Constructor->getLocation();
4968 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4969
4970 Constructor->setUsed();
4971 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004972}
4973
Sebastian Redl08905022011-02-05 19:23:19 +00004974void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4975 // We start with an initial pass over the base classes to collect those that
4976 // inherit constructors from. If there are none, we can forgo all further
4977 // processing.
4978 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4979 BasesVector BasesToInheritFrom;
4980 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4981 BaseE = ClassDecl->bases_end();
4982 BaseIt != BaseE; ++BaseIt) {
4983 if (BaseIt->getInheritConstructors()) {
4984 QualType Base = BaseIt->getType();
4985 if (Base->isDependentType()) {
4986 // If we inherit constructors from anything that is dependent, just
4987 // abort processing altogether. We'll get another chance for the
4988 // instantiations.
4989 return;
4990 }
4991 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4992 }
4993 }
4994 if (BasesToInheritFrom.empty())
4995 return;
4996
4997 // Now collect the constructors that we already have in the current class.
4998 // Those take precedence over inherited constructors.
4999 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5000 // unless there is a user-declared constructor with the same signature in
5001 // the class where the using-declaration appears.
5002 llvm::SmallSet<const Type *, 8> ExistingConstructors;
5003 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5004 CtorE = ClassDecl->ctor_end();
5005 CtorIt != CtorE; ++CtorIt) {
5006 ExistingConstructors.insert(
5007 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5008 }
5009
5010 Scope *S = getScopeForContext(ClassDecl);
5011 DeclarationName CreatedCtorName =
5012 Context.DeclarationNames.getCXXConstructorName(
5013 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5014
5015 // Now comes the true work.
5016 // First, we keep a map from constructor types to the base that introduced
5017 // them. Needed for finding conflicting constructors. We also keep the
5018 // actually inserted declarations in there, for pretty diagnostics.
5019 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5020 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5021 ConstructorToSourceMap InheritedConstructors;
5022 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5023 BaseE = BasesToInheritFrom.end();
5024 BaseIt != BaseE; ++BaseIt) {
5025 const RecordType *Base = *BaseIt;
5026 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5027 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5028 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5029 CtorE = BaseDecl->ctor_end();
5030 CtorIt != CtorE; ++CtorIt) {
5031 // Find the using declaration for inheriting this base's constructors.
5032 DeclarationName Name =
5033 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5034 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5035 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5036 SourceLocation UsingLoc = UD ? UD->getLocation() :
5037 ClassDecl->getLocation();
5038
5039 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5040 // from the class X named in the using-declaration consists of actual
5041 // constructors and notional constructors that result from the
5042 // transformation of defaulted parameters as follows:
5043 // - all non-template default constructors of X, and
5044 // - for each non-template constructor of X that has at least one
5045 // parameter with a default argument, the set of constructors that
5046 // results from omitting any ellipsis parameter specification and
5047 // successively omitting parameters with a default argument from the
5048 // end of the parameter-type-list.
5049 CXXConstructorDecl *BaseCtor = *CtorIt;
5050 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5051 const FunctionProtoType *BaseCtorType =
5052 BaseCtor->getType()->getAs<FunctionProtoType>();
5053
5054 for (unsigned params = BaseCtor->getMinRequiredArguments(),
5055 maxParams = BaseCtor->getNumParams();
5056 params <= maxParams; ++params) {
5057 // Skip default constructors. They're never inherited.
5058 if (params == 0)
5059 continue;
5060 // Skip copy and move constructors for the same reason.
5061 if (CanBeCopyOrMove && params == 1)
5062 continue;
5063
5064 // Build up a function type for this particular constructor.
5065 // FIXME: The working paper does not consider that the exception spec
5066 // for the inheriting constructor might be larger than that of the
5067 // source. This code doesn't yet, either.
5068 const Type *NewCtorType;
5069 if (params == maxParams)
5070 NewCtorType = BaseCtorType;
5071 else {
5072 llvm::SmallVector<QualType, 16> Args;
5073 for (unsigned i = 0; i < params; ++i) {
5074 Args.push_back(BaseCtorType->getArgType(i));
5075 }
5076 FunctionProtoType::ExtProtoInfo ExtInfo =
5077 BaseCtorType->getExtProtoInfo();
5078 ExtInfo.Variadic = false;
5079 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5080 Args.data(), params, ExtInfo)
5081 .getTypePtr();
5082 }
5083 const Type *CanonicalNewCtorType =
5084 Context.getCanonicalType(NewCtorType);
5085
5086 // Now that we have the type, first check if the class already has a
5087 // constructor with this signature.
5088 if (ExistingConstructors.count(CanonicalNewCtorType))
5089 continue;
5090
5091 // Then we check if we have already declared an inherited constructor
5092 // with this signature.
5093 std::pair<ConstructorToSourceMap::iterator, bool> result =
5094 InheritedConstructors.insert(std::make_pair(
5095 CanonicalNewCtorType,
5096 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5097 if (!result.second) {
5098 // Already in the map. If it came from a different class, that's an
5099 // error. Not if it's from the same.
5100 CanQualType PreviousBase = result.first->second.first;
5101 if (CanonicalBase != PreviousBase) {
5102 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5103 const CXXConstructorDecl *PrevBaseCtor =
5104 PrevCtor->getInheritedConstructor();
5105 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5106
5107 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5108 Diag(BaseCtor->getLocation(),
5109 diag::note_using_decl_constructor_conflict_current_ctor);
5110 Diag(PrevBaseCtor->getLocation(),
5111 diag::note_using_decl_constructor_conflict_previous_ctor);
5112 Diag(PrevCtor->getLocation(),
5113 diag::note_using_decl_constructor_conflict_previous_using);
5114 }
5115 continue;
5116 }
5117
5118 // OK, we're there, now add the constructor.
5119 // C++0x [class.inhctor]p8: [...] that would be performed by a
5120 // user-writtern inline constructor [...]
5121 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5122 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00005123 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5124 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redl08905022011-02-05 19:23:19 +00005125 /*ImplicitlyDeclared=*/true);
5126 NewCtor->setAccess(BaseCtor->getAccess());
5127
5128 // Build up the parameter decls and add them.
5129 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5130 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005131 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5132 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00005133 /*IdentifierInfo=*/0,
5134 BaseCtorType->getArgType(i),
5135 /*TInfo=*/0, SC_None,
5136 SC_None, /*DefaultArg=*/0));
5137 }
5138 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5139 NewCtor->setInheritedConstructor(BaseCtor);
5140
5141 PushOnScopeChains(NewCtor, S, false);
5142 ClassDecl->addDecl(NewCtor);
5143 result.first->second.second = NewCtor;
5144 }
5145 }
5146 }
5147}
5148
Douglas Gregor0be31a22010-07-02 17:43:08 +00005149CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00005150 // C++ [class.dtor]p2:
5151 // If a class has no user-declared destructor, a destructor is
5152 // declared implicitly. An implicitly-declared destructor is an
5153 // inline public member of its class.
5154
5155 // C++ [except.spec]p14:
5156 // An implicitly declared special member function (Clause 12) shall have
5157 // an exception-specification.
5158 ImplicitExceptionSpecification ExceptSpec(Context);
5159
5160 // Direct base-class destructors.
5161 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5162 BEnd = ClassDecl->bases_end();
5163 B != BEnd; ++B) {
5164 if (B->isVirtual()) // Handled below.
5165 continue;
5166
5167 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5168 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005169 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005170 }
5171
5172 // Virtual base-class destructors.
5173 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5174 BEnd = ClassDecl->vbases_end();
5175 B != BEnd; ++B) {
5176 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5177 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005178 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005179 }
5180
5181 // Field destructors.
5182 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5183 FEnd = ClassDecl->field_end();
5184 F != FEnd; ++F) {
5185 if (const RecordType *RecordTy
5186 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5187 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005188 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005189 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005190
Douglas Gregor7454c562010-07-02 20:37:36 +00005191 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00005192 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005193 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005194 EPI.NumExceptions = ExceptSpec.size();
5195 EPI.Exceptions = ExceptSpec.data();
5196 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005197
Douglas Gregorf1203042010-07-01 19:09:28 +00005198 CanQualType ClassType
5199 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005200 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00005201 DeclarationName Name
5202 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005203 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00005204 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005205 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5206 /*isInline=*/true,
5207 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00005208 Destructor->setAccess(AS_public);
5209 Destructor->setImplicit();
5210 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00005211
5212 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00005213 ++ASTContext::NumImplicitDestructorsDeclared;
5214
5215 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005216 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00005217 PushOnScopeChains(Destructor, S, false);
5218 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00005219
5220 // This could be uniqued if it ever proves significant.
5221 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5222
5223 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00005224
Douglas Gregorf1203042010-07-01 19:09:28 +00005225 return Destructor;
5226}
5227
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005228void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00005229 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00005230 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005231 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00005232 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005233 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005234
Douglas Gregor54818f02010-05-12 16:39:35 +00005235 if (Destructor->isInvalidDecl())
5236 return;
5237
Douglas Gregora57478e2010-05-01 15:04:51 +00005238 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005239
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005240 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00005241 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5242 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00005243
Douglas Gregor54818f02010-05-12 16:39:35 +00005244 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005245 Diag(CurrentLocation, diag::note_member_synthesized_at)
5246 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5247
5248 Destructor->setInvalidDecl();
5249 return;
5250 }
5251
Douglas Gregor73193272010-09-20 16:48:21 +00005252 SourceLocation Loc = Destructor->getLocation();
5253 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5254
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005255 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005256 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005257}
5258
Douglas Gregorb139cd52010-05-01 20:49:11 +00005259/// \brief Builds a statement that copies the given entity from \p From to
5260/// \c To.
5261///
5262/// This routine is used to copy the members of a class with an
5263/// implicitly-declared copy assignment operator. When the entities being
5264/// copied are arrays, this routine builds for loops to copy them.
5265///
5266/// \param S The Sema object used for type-checking.
5267///
5268/// \param Loc The location where the implicit copy is being generated.
5269///
5270/// \param T The type of the expressions being copied. Both expressions must
5271/// have this type.
5272///
5273/// \param To The expression we are copying to.
5274///
5275/// \param From The expression we are copying from.
5276///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005277/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5278/// Otherwise, it's a non-static member subobject.
5279///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005280/// \param Depth Internal parameter recording the depth of the recursion.
5281///
5282/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005283static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005284BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005285 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005286 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005287 // C++0x [class.copy]p30:
5288 // Each subobject is assigned in the manner appropriate to its type:
5289 //
5290 // - if the subobject is of class type, the copy assignment operator
5291 // for the class is used (as if by explicit qualification; that is,
5292 // ignoring any possible virtual overriding functions in more derived
5293 // classes);
5294 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5295 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5296
5297 // Look for operator=.
5298 DeclarationName Name
5299 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5300 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5301 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5302
5303 // Filter out any result that isn't a copy-assignment operator.
5304 LookupResult::Filter F = OpLookup.makeFilter();
5305 while (F.hasNext()) {
5306 NamedDecl *D = F.next();
5307 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5308 if (Method->isCopyAssignmentOperator())
5309 continue;
5310
5311 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005312 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005313 F.done();
5314
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005315 // Suppress the protected check (C++ [class.protected]) for each of the
5316 // assignment operators we found. This strange dance is required when
5317 // we're assigning via a base classes's copy-assignment operator. To
5318 // ensure that we're getting the right base class subobject (without
5319 // ambiguities), we need to cast "this" to that subobject type; to
5320 // ensure that we don't go through the virtual call mechanism, we need
5321 // to qualify the operator= name with the base class (see below). However,
5322 // this means that if the base class has a protected copy assignment
5323 // operator, the protected member access check will fail. So, we
5324 // rewrite "protected" access to "public" access in this case, since we
5325 // know by construction that we're calling from a derived class.
5326 if (CopyingBaseSubobject) {
5327 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5328 L != LEnd; ++L) {
5329 if (L.getAccess() == AS_protected)
5330 L.setAccess(AS_public);
5331 }
5332 }
5333
Douglas Gregorb139cd52010-05-01 20:49:11 +00005334 // Create the nested-name-specifier that will be used to qualify the
5335 // reference to operator=; this is required to suppress the virtual
5336 // call mechanism.
5337 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005338 SS.MakeTrivial(S.Context,
5339 NestedNameSpecifier::Create(S.Context, 0, false,
5340 T.getTypePtr()),
5341 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005342
5343 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005344 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005345 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005346 /*FirstQualifierInScope=*/0, OpLookup,
5347 /*TemplateArgs=*/0,
5348 /*SuppressQualifierCheck=*/true);
5349 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005350 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005351
5352 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005353
John McCalldadc5752010-08-24 06:29:42 +00005354 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005355 OpEqualRef.takeAs<Expr>(),
5356 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005357 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005358 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005359
5360 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005361 }
John McCallab8c2732010-03-16 06:11:48 +00005362
Douglas Gregorb139cd52010-05-01 20:49:11 +00005363 // - if the subobject is of scalar type, the built-in assignment
5364 // operator is used.
5365 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5366 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005367 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005368 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005369 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005370
5371 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005372 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005373
5374 // - if the subobject is an array, each element is assigned, in the
5375 // manner appropriate to the element type;
5376
5377 // Construct a loop over the array bounds, e.g.,
5378 //
5379 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5380 //
5381 // that will copy each of the array elements.
5382 QualType SizeType = S.Context.getSizeType();
5383
5384 // Create the iteration variable.
5385 IdentifierInfo *IterationVarName = 0;
5386 {
5387 llvm::SmallString<8> Str;
5388 llvm::raw_svector_ostream OS(Str);
5389 OS << "__i" << Depth;
5390 IterationVarName = &S.Context.Idents.get(OS.str());
5391 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00005392 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005393 IterationVarName, SizeType,
5394 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005395 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005396
5397 // Initialize the iteration variable to zero.
5398 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005399 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005400
5401 // Create a reference to the iteration variable; we'll use this several
5402 // times throughout.
5403 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005404 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005405 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5406
5407 // Create the DeclStmt that holds the iteration variable.
5408 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5409
5410 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005411 llvm::APInt Upper
5412 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005413 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005414 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005415 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5416 BO_NE, S.Context.BoolTy,
5417 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005418
5419 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005420 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005421 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5422 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005423
5424 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005425 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5426 IterationVarRef, Loc));
5427 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5428 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005429
5430 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005431 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5432 To, From, CopyingBaseSubobject,
5433 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005434 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005435 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005436
5437 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005438 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005439 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005440 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005441 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005442}
5443
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005444/// \brief Determine whether the given class has a copy assignment operator
5445/// that accepts a const-qualified argument.
5446static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5447 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5448
5449 if (!Class->hasDeclaredCopyAssignment())
5450 S.DeclareImplicitCopyAssignment(Class);
5451
5452 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5453 DeclarationName OpName
5454 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5455
5456 DeclContext::lookup_const_iterator Op, OpEnd;
5457 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5458 // C++ [class.copy]p9:
5459 // A user-declared copy assignment operator is a non-static non-template
5460 // member function of class X with exactly one parameter of type X, X&,
5461 // const X&, volatile X& or const volatile X&.
5462 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5463 if (!Method)
5464 continue;
5465
5466 if (Method->isStatic())
5467 continue;
5468 if (Method->getPrimaryTemplate())
5469 continue;
5470 const FunctionProtoType *FnType =
5471 Method->getType()->getAs<FunctionProtoType>();
5472 assert(FnType && "Overloaded operator has no prototype.");
5473 // Don't assert on this; an invalid decl might have been left in the AST.
5474 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5475 continue;
5476 bool AcceptsConst = true;
5477 QualType ArgType = FnType->getArgType(0);
5478 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5479 ArgType = Ref->getPointeeType();
5480 // Is it a non-const lvalue reference?
5481 if (!ArgType.isConstQualified())
5482 AcceptsConst = false;
5483 }
5484 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5485 continue;
5486
5487 // We have a single argument of type cv X or cv X&, i.e. we've found the
5488 // copy assignment operator. Return whether it accepts const arguments.
5489 return AcceptsConst;
5490 }
5491 assert(Class->isInvalidDecl() &&
5492 "No copy assignment operator declared in valid code.");
5493 return false;
5494}
5495
Douglas Gregor0be31a22010-07-02 17:43:08 +00005496CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005497 // Note: The following rules are largely analoguous to the copy
5498 // constructor rules. Note that virtual bases are not taken into account
5499 // for determining the argument type of the operator. Note also that
5500 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005501
5502
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005503 // C++ [class.copy]p10:
5504 // If the class definition does not explicitly declare a copy
5505 // assignment operator, one is declared implicitly.
5506 // The implicitly-defined copy assignment operator for a class X
5507 // will have the form
5508 //
5509 // X& X::operator=(const X&)
5510 //
5511 // if
5512 bool HasConstCopyAssignment = true;
5513
5514 // -- each direct base class B of X has a copy assignment operator
5515 // whose parameter is of type const B&, const volatile B& or B,
5516 // and
5517 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5518 BaseEnd = ClassDecl->bases_end();
5519 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5520 assert(!Base->getType()->isDependentType() &&
5521 "Cannot generate implicit members for class with dependent bases.");
5522 const CXXRecordDecl *BaseClassDecl
5523 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005524 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005525 }
5526
5527 // -- for all the nonstatic data members of X that are of a class
5528 // type M (or array thereof), each such class type has a copy
5529 // assignment operator whose parameter is of type const M&,
5530 // const volatile M& or M.
5531 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5532 FieldEnd = ClassDecl->field_end();
5533 HasConstCopyAssignment && Field != FieldEnd;
5534 ++Field) {
5535 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5536 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5537 const CXXRecordDecl *FieldClassDecl
5538 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005539 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005540 }
5541 }
5542
5543 // Otherwise, the implicitly declared copy assignment operator will
5544 // have the form
5545 //
5546 // X& X::operator=(X&)
5547 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5548 QualType RetType = Context.getLValueReferenceType(ArgType);
5549 if (HasConstCopyAssignment)
5550 ArgType = ArgType.withConst();
5551 ArgType = Context.getLValueReferenceType(ArgType);
5552
Douglas Gregor68e11362010-07-01 17:48:08 +00005553 // C++ [except.spec]p14:
5554 // An implicitly declared special member function (Clause 12) shall have an
5555 // exception-specification. [...]
5556 ImplicitExceptionSpecification ExceptSpec(Context);
5557 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5558 BaseEnd = ClassDecl->bases_end();
5559 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005560 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005561 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005562
5563 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5564 DeclareImplicitCopyAssignment(BaseClassDecl);
5565
Douglas Gregor68e11362010-07-01 17:48:08 +00005566 if (CXXMethodDecl *CopyAssign
5567 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5568 ExceptSpec.CalledDecl(CopyAssign);
5569 }
5570 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5571 FieldEnd = ClassDecl->field_end();
5572 Field != FieldEnd;
5573 ++Field) {
5574 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5575 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005576 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005577 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005578
5579 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5580 DeclareImplicitCopyAssignment(FieldClassDecl);
5581
Douglas Gregor68e11362010-07-01 17:48:08 +00005582 if (CXXMethodDecl *CopyAssign
5583 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5584 ExceptSpec.CalledDecl(CopyAssign);
5585 }
5586 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005587
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005588 // An implicitly-declared copy assignment operator is an inline public
5589 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005590 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005591 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005592 EPI.NumExceptions = ExceptSpec.size();
5593 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005594 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005595 SourceLocation ClassLoc = ClassDecl->getLocation();
5596 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005597 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00005598 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005599 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005600 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005601 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00005602 /*isInline=*/true,
5603 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005604 CopyAssignment->setAccess(AS_public);
5605 CopyAssignment->setImplicit();
5606 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005607
5608 // Add the parameter to the operator.
5609 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005610 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005611 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005612 SC_None,
5613 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005614 CopyAssignment->setParams(&FromParam, 1);
5615
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005616 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005617 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5618
Douglas Gregor0be31a22010-07-02 17:43:08 +00005619 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005620 PushOnScopeChains(CopyAssignment, S, false);
5621 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005622
5623 AddOverriddenMethods(ClassDecl, CopyAssignment);
5624 return CopyAssignment;
5625}
5626
Douglas Gregorb139cd52010-05-01 20:49:11 +00005627void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5628 CXXMethodDecl *CopyAssignOperator) {
5629 assert((CopyAssignOperator->isImplicit() &&
5630 CopyAssignOperator->isOverloadedOperator() &&
5631 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005632 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005633 "DefineImplicitCopyAssignment called for wrong function");
5634
5635 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5636
5637 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5638 CopyAssignOperator->setInvalidDecl();
5639 return;
5640 }
5641
5642 CopyAssignOperator->setUsed();
5643
5644 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005645 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005646
5647 // C++0x [class.copy]p30:
5648 // The implicitly-defined or explicitly-defaulted copy assignment operator
5649 // for a non-union class X performs memberwise copy assignment of its
5650 // subobjects. The direct base classes of X are assigned first, in the
5651 // order of their declaration in the base-specifier-list, and then the
5652 // immediate non-static data members of X are assigned, in the order in
5653 // which they were declared in the class definition.
5654
5655 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005656 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005657
5658 // The parameter for the "other" object, which we are copying from.
5659 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5660 Qualifiers OtherQuals = Other->getType().getQualifiers();
5661 QualType OtherRefType = Other->getType();
5662 if (const LValueReferenceType *OtherRef
5663 = OtherRefType->getAs<LValueReferenceType>()) {
5664 OtherRefType = OtherRef->getPointeeType();
5665 OtherQuals = OtherRefType.getQualifiers();
5666 }
5667
5668 // Our location for everything implicitly-generated.
5669 SourceLocation Loc = CopyAssignOperator->getLocation();
5670
5671 // Construct a reference to the "other" object. We'll be using this
5672 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005673 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005674 assert(OtherRef && "Reference to parameter cannot fail!");
5675
5676 // Construct the "this" pointer. We'll be using this throughout the generated
5677 // ASTs.
5678 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5679 assert(This && "Reference to this cannot fail!");
5680
5681 // Assign base classes.
5682 bool Invalid = false;
5683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5684 E = ClassDecl->bases_end(); Base != E; ++Base) {
5685 // Form the assignment:
5686 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5687 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005688 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005689 Invalid = true;
5690 continue;
5691 }
5692
John McCallcf142162010-08-07 06:22:56 +00005693 CXXCastPath BasePath;
5694 BasePath.push_back(Base);
5695
Douglas Gregorb139cd52010-05-01 20:49:11 +00005696 // Construct the "from" expression, which is an implicit cast to the
5697 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005698 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00005699 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5700 CK_UncheckedDerivedToBase,
5701 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005702
5703 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005704 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005705
5706 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00005707 To = ImpCastExprToType(To.take(),
5708 Context.getCVRQualifiedType(BaseType,
5709 CopyAssignOperator->getTypeQualifiers()),
5710 CK_UncheckedDerivedToBase,
5711 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005712
5713 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005714 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005715 To.get(), From,
5716 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005717 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005718 Diag(CurrentLocation, diag::note_member_synthesized_at)
5719 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5720 CopyAssignOperator->setInvalidDecl();
5721 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005722 }
5723
5724 // Success! Record the copy.
5725 Statements.push_back(Copy.takeAs<Expr>());
5726 }
5727
5728 // \brief Reference to the __builtin_memcpy function.
5729 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005730 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005731 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005732
5733 // Assign non-static members.
5734 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5735 FieldEnd = ClassDecl->field_end();
5736 Field != FieldEnd; ++Field) {
5737 // Check for members of reference type; we can't copy those.
5738 if (Field->getType()->isReferenceType()) {
5739 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5740 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5741 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005742 Diag(CurrentLocation, diag::note_member_synthesized_at)
5743 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005744 Invalid = true;
5745 continue;
5746 }
5747
5748 // Check for members of const-qualified, non-class type.
5749 QualType BaseType = Context.getBaseElementType(Field->getType());
5750 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5751 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5752 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5753 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005754 Diag(CurrentLocation, diag::note_member_synthesized_at)
5755 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005756 Invalid = true;
5757 continue;
5758 }
5759
5760 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005761 if (FieldType->isIncompleteArrayType()) {
5762 assert(ClassDecl->hasFlexibleArrayMember() &&
5763 "Incomplete array type is not valid");
5764 continue;
5765 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005766
5767 // Build references to the field in the object we're copying from and to.
5768 CXXScopeSpec SS; // Intentionally empty
5769 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5770 LookupMemberName);
5771 MemberLookup.addDecl(*Field);
5772 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005773 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005774 Loc, /*IsArrow=*/false,
5775 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005776 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005777 Loc, /*IsArrow=*/true,
5778 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005779 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5780 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5781
5782 // If the field should be copied with __builtin_memcpy rather than via
5783 // explicit assignments, do so. This optimization only applies for arrays
5784 // of scalars and arrays of class type with trivial copy-assignment
5785 // operators.
5786 if (FieldType->isArrayType() &&
5787 (!BaseType->isRecordType() ||
5788 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5789 ->hasTrivialCopyAssignment())) {
5790 // Compute the size of the memory buffer to be copied.
5791 QualType SizeType = Context.getSizeType();
5792 llvm::APInt Size(Context.getTypeSize(SizeType),
5793 Context.getTypeSizeInChars(BaseType).getQuantity());
5794 for (const ConstantArrayType *Array
5795 = Context.getAsConstantArrayType(FieldType);
5796 Array;
5797 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005798 llvm::APInt ArraySize
5799 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005800 Size *= ArraySize;
5801 }
5802
5803 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005804 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5805 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005806
5807 bool NeedsCollectableMemCpy =
5808 (BaseType->isRecordType() &&
5809 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5810
5811 if (NeedsCollectableMemCpy) {
5812 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005813 // Create a reference to the __builtin_objc_memmove_collectable function.
5814 LookupResult R(*this,
5815 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005816 Loc, LookupOrdinaryName);
5817 LookupName(R, TUScope, true);
5818
5819 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5820 if (!CollectableMemCpy) {
5821 // Something went horribly wrong earlier, and we will have
5822 // complained about it.
5823 Invalid = true;
5824 continue;
5825 }
5826
5827 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5828 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005829 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005830 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5831 }
5832 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005833 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005834 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005835 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5836 LookupOrdinaryName);
5837 LookupName(R, TUScope, true);
5838
5839 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5840 if (!BuiltinMemCpy) {
5841 // Something went horribly wrong earlier, and we will have complained
5842 // about it.
5843 Invalid = true;
5844 continue;
5845 }
5846
5847 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5848 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005849 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005850 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5851 }
5852
John McCall37ad5512010-08-23 06:44:23 +00005853 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005854 CallArgs.push_back(To.takeAs<Expr>());
5855 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005856 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005857 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005858 if (NeedsCollectableMemCpy)
5859 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005860 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005861 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005862 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005863 else
5864 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005865 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005866 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005867 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005868
Douglas Gregorb139cd52010-05-01 20:49:11 +00005869 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5870 Statements.push_back(Call.takeAs<Expr>());
5871 continue;
5872 }
5873
5874 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005875 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005876 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005877 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005878 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005879 Diag(CurrentLocation, diag::note_member_synthesized_at)
5880 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5881 CopyAssignOperator->setInvalidDecl();
5882 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005883 }
5884
5885 // Success! Record the copy.
5886 Statements.push_back(Copy.takeAs<Stmt>());
5887 }
5888
5889 if (!Invalid) {
5890 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005891 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005892
John McCalldadc5752010-08-24 06:29:42 +00005893 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005894 if (Return.isInvalid())
5895 Invalid = true;
5896 else {
5897 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005898
5899 if (Trap.hasErrorOccurred()) {
5900 Diag(CurrentLocation, diag::note_member_synthesized_at)
5901 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5902 Invalid = true;
5903 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005904 }
5905 }
5906
5907 if (Invalid) {
5908 CopyAssignOperator->setInvalidDecl();
5909 return;
5910 }
5911
John McCalldadc5752010-08-24 06:29:42 +00005912 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005913 /*isStmtExpr=*/false);
5914 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5915 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005916}
5917
Douglas Gregor0be31a22010-07-02 17:43:08 +00005918CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5919 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005920 // C++ [class.copy]p4:
5921 // If the class definition does not explicitly declare a copy
5922 // constructor, one is declared implicitly.
5923
Douglas Gregor54be3392010-07-01 17:57:27 +00005924 // C++ [class.copy]p5:
5925 // The implicitly-declared copy constructor for a class X will
5926 // have the form
5927 //
5928 // X::X(const X&)
5929 //
5930 // if
5931 bool HasConstCopyConstructor = true;
5932
5933 // -- each direct or virtual base class B of X has a copy
5934 // constructor whose first parameter is of type const B& or
5935 // const volatile B&, and
5936 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5937 BaseEnd = ClassDecl->bases_end();
5938 HasConstCopyConstructor && Base != BaseEnd;
5939 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005940 // Virtual bases are handled below.
5941 if (Base->isVirtual())
5942 continue;
5943
Douglas Gregora6d69502010-07-02 23:41:54 +00005944 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005945 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005946 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5947 DeclareImplicitCopyConstructor(BaseClassDecl);
5948
Douglas Gregorcfe68222010-07-01 18:27:03 +00005949 HasConstCopyConstructor
5950 = BaseClassDecl->hasConstCopyConstructor(Context);
5951 }
5952
5953 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5954 BaseEnd = ClassDecl->vbases_end();
5955 HasConstCopyConstructor && Base != BaseEnd;
5956 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005957 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005958 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005959 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5960 DeclareImplicitCopyConstructor(BaseClassDecl);
5961
Douglas Gregor54be3392010-07-01 17:57:27 +00005962 HasConstCopyConstructor
5963 = BaseClassDecl->hasConstCopyConstructor(Context);
5964 }
5965
5966 // -- for all the nonstatic data members of X that are of a
5967 // class type M (or array thereof), each such class type
5968 // has a copy constructor whose first parameter is of type
5969 // const M& or const volatile M&.
5970 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5971 FieldEnd = ClassDecl->field_end();
5972 HasConstCopyConstructor && Field != FieldEnd;
5973 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005974 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005975 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005976 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005977 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005978 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5979 DeclareImplicitCopyConstructor(FieldClassDecl);
5980
Douglas Gregor54be3392010-07-01 17:57:27 +00005981 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005982 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005983 }
5984 }
5985
5986 // Otherwise, the implicitly declared copy constructor will have
5987 // the form
5988 //
5989 // X::X(X&)
5990 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5991 QualType ArgType = ClassType;
5992 if (HasConstCopyConstructor)
5993 ArgType = ArgType.withConst();
5994 ArgType = Context.getLValueReferenceType(ArgType);
5995
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005996 // C++ [except.spec]p14:
5997 // An implicitly declared special member function (Clause 12) shall have an
5998 // exception-specification. [...]
5999 ImplicitExceptionSpecification ExceptSpec(Context);
6000 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6001 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6002 BaseEnd = ClassDecl->bases_end();
6003 Base != BaseEnd;
6004 ++Base) {
6005 // Virtual bases are handled below.
6006 if (Base->isVirtual())
6007 continue;
6008
Douglas Gregora6d69502010-07-02 23:41:54 +00006009 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006010 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006011 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6012 DeclareImplicitCopyConstructor(BaseClassDecl);
6013
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006014 if (CXXConstructorDecl *CopyConstructor
6015 = BaseClassDecl->getCopyConstructor(Context, Quals))
6016 ExceptSpec.CalledDecl(CopyConstructor);
6017 }
6018 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6019 BaseEnd = ClassDecl->vbases_end();
6020 Base != BaseEnd;
6021 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006022 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006023 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006024 if (!BaseClassDecl->hasDeclaredCopyConstructor())
6025 DeclareImplicitCopyConstructor(BaseClassDecl);
6026
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006027 if (CXXConstructorDecl *CopyConstructor
6028 = BaseClassDecl->getCopyConstructor(Context, Quals))
6029 ExceptSpec.CalledDecl(CopyConstructor);
6030 }
6031 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6032 FieldEnd = ClassDecl->field_end();
6033 Field != FieldEnd;
6034 ++Field) {
6035 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6036 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006037 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006038 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00006039 if (!FieldClassDecl->hasDeclaredCopyConstructor())
6040 DeclareImplicitCopyConstructor(FieldClassDecl);
6041
Douglas Gregor8453ddb2010-07-01 20:59:04 +00006042 if (CXXConstructorDecl *CopyConstructor
6043 = FieldClassDecl->getCopyConstructor(Context, Quals))
6044 ExceptSpec.CalledDecl(CopyConstructor);
6045 }
6046 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006047
Douglas Gregor54be3392010-07-01 17:57:27 +00006048 // An implicitly-declared copy constructor is an inline public
6049 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00006050 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006051 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00006052 EPI.NumExceptions = ExceptSpec.size();
6053 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00006054 DeclarationName Name
6055 = Context.DeclarationNames.getCXXConstructorName(
6056 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006057 SourceLocation ClassLoc = ClassDecl->getLocation();
6058 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor54be3392010-07-01 17:57:27 +00006059 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00006060 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00006061 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006062 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00006063 /*TInfo=*/0,
6064 /*isExplicit=*/false,
6065 /*isInline=*/true,
6066 /*isImplicitlyDeclared=*/true);
6067 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00006068 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6069
Douglas Gregora6d69502010-07-02 23:41:54 +00006070 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00006071 ++ASTContext::NumImplicitCopyConstructorsDeclared;
6072
Douglas Gregor54be3392010-07-01 17:57:27 +00006073 // Add the parameter to the constructor.
6074 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006075 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00006076 /*IdentifierInfo=*/0,
6077 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006078 SC_None,
6079 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00006080 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00006081 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00006082 PushOnScopeChains(CopyConstructor, S, false);
6083 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00006084
6085 return CopyConstructor;
6086}
6087
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006088void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6089 CXXConstructorDecl *CopyConstructor,
6090 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00006091 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00006092 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00006093 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006094 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006095
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00006096 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006097 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006098
Douglas Gregora57478e2010-05-01 15:04:51 +00006099 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006100 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006101
Alexis Hunt1d792652011-01-08 20:30:50 +00006102 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006103 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00006104 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00006105 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00006106 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00006107 } else {
6108 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6109 CopyConstructor->getLocation(),
6110 MultiStmtArg(*this, 0, 0),
6111 /*isStmtExpr=*/false)
6112 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00006113 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00006114
6115 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006116}
6117
John McCalldadc5752010-08-24 06:29:42 +00006118ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006119Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00006120 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006121 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006122 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006123 unsigned ConstructKind,
6124 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00006125 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00006126
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006127 // C++0x [class.copy]p34:
6128 // When certain criteria are met, an implementation is allowed to
6129 // omit the copy/move construction of a class object, even if the
6130 // copy/move constructor and/or destructor for the object have
6131 // side effects. [...]
6132 // - when a temporary class object that has not been bound to a
6133 // reference (12.2) would be copied/moved to a class object
6134 // with the same cv-unqualified type, the copy/move operation
6135 // can be omitted by constructing the temporary object
6136 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00006137 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00006138 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006139 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00006140 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00006141 }
Mike Stump11289f42009-09-09 15:08:12 +00006142
6143 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006144 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006145 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00006146}
6147
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006148/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6149/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00006150ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006151Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6152 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006153 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006154 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006155 unsigned ConstructKind,
6156 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006157 unsigned NumExprs = ExprArgs.size();
6158 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00006159
Nick Lewyckyd4693212011-03-25 01:44:32 +00006160 for (specific_attr_iterator<NonNullAttr>
6161 i = Constructor->specific_attr_begin<NonNullAttr>(),
6162 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6163 const NonNullAttr *NonNull = *i;
6164 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6165 }
6166
Douglas Gregor27381f32009-11-23 12:27:39 +00006167 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00006168 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006169 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00006170 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006171 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6172 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006173}
6174
Mike Stump11289f42009-09-09 15:08:12 +00006175bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006176 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006177 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00006178 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00006179 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00006180 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00006181 move(Exprs), false, CXXConstructExpr::CK_Complete,
6182 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006183 if (TempResult.isInvalid())
6184 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006185
Anders Carlsson6eb55572009-08-25 05:12:04 +00006186 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00006187 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00006188 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00006189 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00006190 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00006191
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006192 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00006193}
6194
John McCall03c48482010-02-02 09:10:11 +00006195void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00006196 if (VD->isInvalidDecl()) return;
6197
John McCall03c48482010-02-02 09:10:11 +00006198 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00006199 if (ClassDecl->isInvalidDecl()) return;
6200 if (ClassDecl->hasTrivialDestructor()) return;
6201 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00006202
Chandler Carruth86d17d32011-03-27 21:26:48 +00006203 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6204 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6205 CheckDestructorAccess(VD->getLocation(), Destructor,
6206 PDiag(diag::err_access_dtor_var)
6207 << VD->getDeclName()
6208 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00006209
Chandler Carruth86d17d32011-03-27 21:26:48 +00006210 if (!VD->hasGlobalStorage()) return;
6211
6212 // Emit warning for non-trivial dtor in global scope (a real global,
6213 // class-static, function-static).
6214 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6215
6216 // TODO: this should be re-enabled for static locals by !CXAAtExit
6217 if (!VD->isStaticLocal())
6218 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006219}
6220
Mike Stump11289f42009-09-09 15:08:12 +00006221/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006222/// ActOnDeclarator, when a C++ direct initializer is present.
6223/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00006224void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00006225 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006226 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00006227 SourceLocation RParenLoc,
6228 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00006229 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006230
6231 // If there is no declaration, there was an error parsing it. Just ignore
6232 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00006233 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006234 return;
Mike Stump11289f42009-09-09 15:08:12 +00006235
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006236 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6237 if (!VDecl) {
6238 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6239 RealDecl->setInvalidDecl();
6240 return;
6241 }
6242
Richard Smith30482bc2011-02-20 03:19:35 +00006243 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6244 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00006245 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6246 if (Exprs.size() > 1) {
6247 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6248 diag::err_auto_var_init_multiple_expressions)
6249 << VDecl->getDeclName() << VDecl->getType()
6250 << VDecl->getSourceRange();
6251 RealDecl->setInvalidDecl();
6252 return;
6253 }
6254
6255 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00006256 TypeSourceInfo *DeducedType = 0;
6257 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00006258 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6259 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6260 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00006261 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006262 RealDecl->setInvalidDecl();
6263 return;
6264 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006265 VDecl->setTypeSourceInfo(DeducedType);
6266 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00006267
6268 // If this is a redeclaration, check that the type we just deduced matches
6269 // the previously declared type.
6270 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6271 MergeVarDeclTypes(VDecl, Old);
6272 }
6273
Douglas Gregor402250f2009-08-26 21:14:46 +00006274 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006275 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006276 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6277 //
6278 // Clients that want to distinguish between the two forms, can check for
6279 // direct initializer using VarDecl::hasCXXDirectInitializer().
6280 // A major benefit is that clients that don't particularly care about which
6281 // exactly form was it (like the CodeGen) can handle both cases without
6282 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006283
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006284 // C++ 8.5p11:
6285 // The form of initialization (using parentheses or '=') is generally
6286 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006287 // class type.
6288
Douglas Gregor50dc2192010-02-11 22:55:30 +00006289 if (!VDecl->getType()->isDependentType() &&
6290 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006291 diag::err_typecheck_decl_incomplete_type)) {
6292 VDecl->setInvalidDecl();
6293 return;
6294 }
6295
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006296 // The variable can not have an abstract class type.
6297 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6298 diag::err_abstract_type_in_decl,
6299 AbstractVariableType))
6300 VDecl->setInvalidDecl();
6301
Sebastian Redl5ca79842010-02-01 20:16:42 +00006302 const VarDecl *Def;
6303 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006304 Diag(VDecl->getLocation(), diag::err_redefinition)
6305 << VDecl->getDeclName();
6306 Diag(Def->getLocation(), diag::note_previous_definition);
6307 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006308 return;
6309 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006310
Douglas Gregorf0f83692010-08-24 05:27:49 +00006311 // C++ [class.static.data]p4
6312 // If a static data member is of const integral or const
6313 // enumeration type, its declaration in the class definition can
6314 // specify a constant-initializer which shall be an integral
6315 // constant expression (5.19). In that case, the member can appear
6316 // in integral constant expressions. The member shall still be
6317 // defined in a namespace scope if it is used in the program and the
6318 // namespace scope definition shall not contain an initializer.
6319 //
6320 // We already performed a redefinition check above, but for static
6321 // data members we also need to check whether there was an in-class
6322 // declaration with an initializer.
6323 const VarDecl* PrevInit = 0;
6324 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6325 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6326 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6327 return;
6328 }
6329
Douglas Gregor71f39c92010-12-16 01:31:22 +00006330 bool IsDependent = false;
6331 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6332 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6333 VDecl->setInvalidDecl();
6334 return;
6335 }
6336
6337 if (Exprs.get()[I]->isTypeDependent())
6338 IsDependent = true;
6339 }
6340
Douglas Gregor50dc2192010-02-11 22:55:30 +00006341 // If either the declaration has a dependent type or if any of the
6342 // expressions is type-dependent, we represent the initialization
6343 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006344 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006345 // Let clients know that initialization was done with a direct initializer.
6346 VDecl->setCXXDirectInitializer(true);
6347
6348 // Store the initialization expressions as a ParenListExpr.
6349 unsigned NumExprs = Exprs.size();
6350 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6351 (Expr **)Exprs.release(),
6352 NumExprs, RParenLoc));
6353 return;
6354 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006355
6356 // Capture the variable that is being initialized and the style of
6357 // initialization.
6358 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6359
6360 // FIXME: Poor source location information.
6361 InitializationKind Kind
6362 = InitializationKind::CreateDirect(VDecl->getLocation(),
6363 LParenLoc, RParenLoc);
6364
6365 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006366 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006367 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006368 if (Result.isInvalid()) {
6369 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006370 return;
6371 }
John McCallacf0ee52010-10-08 02:01:28 +00006372
6373 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006374
Douglas Gregora40433a2010-12-07 00:41:46 +00006375 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006376 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006377 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006378
John McCall8b7fd8f12011-01-19 11:48:09 +00006379 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006380}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006381
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006382/// \brief Given a constructor and the set of arguments provided for the
6383/// constructor, convert the arguments and add any required default arguments
6384/// to form a proper call to this constructor.
6385///
6386/// \returns true if an error occurred, false otherwise.
6387bool
6388Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6389 MultiExprArg ArgsPtr,
6390 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006391 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006392 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6393 unsigned NumArgs = ArgsPtr.size();
6394 Expr **Args = (Expr **)ArgsPtr.get();
6395
6396 const FunctionProtoType *Proto
6397 = Constructor->getType()->getAs<FunctionProtoType>();
6398 assert(Proto && "Constructor without a prototype?");
6399 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006400
6401 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006402 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006403 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006404 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006405 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006406
6407 VariadicCallType CallType =
6408 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6409 llvm::SmallVector<Expr *, 8> AllArgs;
6410 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6411 Proto, 0, Args, NumArgs, AllArgs,
6412 CallType);
6413 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6414 ConvertedArgs.push_back(AllArgs[i]);
6415 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006416}
6417
Anders Carlssone363c8e2009-12-12 00:32:00 +00006418static inline bool
6419CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6420 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006421 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006422 if (isa<NamespaceDecl>(DC)) {
6423 return SemaRef.Diag(FnDecl->getLocation(),
6424 diag::err_operator_new_delete_declared_in_namespace)
6425 << FnDecl->getDeclName();
6426 }
6427
6428 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006429 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006430 return SemaRef.Diag(FnDecl->getLocation(),
6431 diag::err_operator_new_delete_declared_static)
6432 << FnDecl->getDeclName();
6433 }
6434
Anders Carlsson60659a82009-12-12 02:43:16 +00006435 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006436}
6437
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006438static inline bool
6439CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6440 CanQualType ExpectedResultType,
6441 CanQualType ExpectedFirstParamType,
6442 unsigned DependentParamTypeDiag,
6443 unsigned InvalidParamTypeDiag) {
6444 QualType ResultType =
6445 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6446
6447 // Check that the result type is not dependent.
6448 if (ResultType->isDependentType())
6449 return SemaRef.Diag(FnDecl->getLocation(),
6450 diag::err_operator_new_delete_dependent_result_type)
6451 << FnDecl->getDeclName() << ExpectedResultType;
6452
6453 // Check that the result type is what we expect.
6454 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6455 return SemaRef.Diag(FnDecl->getLocation(),
6456 diag::err_operator_new_delete_invalid_result_type)
6457 << FnDecl->getDeclName() << ExpectedResultType;
6458
6459 // A function template must have at least 2 parameters.
6460 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6461 return SemaRef.Diag(FnDecl->getLocation(),
6462 diag::err_operator_new_delete_template_too_few_parameters)
6463 << FnDecl->getDeclName();
6464
6465 // The function decl must have at least 1 parameter.
6466 if (FnDecl->getNumParams() == 0)
6467 return SemaRef.Diag(FnDecl->getLocation(),
6468 diag::err_operator_new_delete_too_few_parameters)
6469 << FnDecl->getDeclName();
6470
6471 // Check the the first parameter type is not dependent.
6472 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6473 if (FirstParamType->isDependentType())
6474 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6475 << FnDecl->getDeclName() << ExpectedFirstParamType;
6476
6477 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006478 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006479 ExpectedFirstParamType)
6480 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6481 << FnDecl->getDeclName() << ExpectedFirstParamType;
6482
6483 return false;
6484}
6485
Anders Carlsson12308f42009-12-11 23:23:22 +00006486static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006487CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006488 // C++ [basic.stc.dynamic.allocation]p1:
6489 // A program is ill-formed if an allocation function is declared in a
6490 // namespace scope other than global scope or declared static in global
6491 // scope.
6492 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6493 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006494
6495 CanQualType SizeTy =
6496 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6497
6498 // C++ [basic.stc.dynamic.allocation]p1:
6499 // The return type shall be void*. The first parameter shall have type
6500 // std::size_t.
6501 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6502 SizeTy,
6503 diag::err_operator_new_dependent_param_type,
6504 diag::err_operator_new_param_type))
6505 return true;
6506
6507 // C++ [basic.stc.dynamic.allocation]p1:
6508 // The first parameter shall not have an associated default argument.
6509 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006510 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006511 diag::err_operator_new_default_arg)
6512 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6513
6514 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006515}
6516
6517static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006518CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6519 // C++ [basic.stc.dynamic.deallocation]p1:
6520 // A program is ill-formed if deallocation functions are declared in a
6521 // namespace scope other than global scope or declared static in global
6522 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006523 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6524 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006525
6526 // C++ [basic.stc.dynamic.deallocation]p2:
6527 // Each deallocation function shall return void and its first parameter
6528 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006529 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6530 SemaRef.Context.VoidPtrTy,
6531 diag::err_operator_delete_dependent_param_type,
6532 diag::err_operator_delete_param_type))
6533 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006534
Anders Carlsson12308f42009-12-11 23:23:22 +00006535 return false;
6536}
6537
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006538/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6539/// of this overloaded operator is well-formed. If so, returns false;
6540/// otherwise, emits appropriate diagnostics and returns true.
6541bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006542 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006543 "Expected an overloaded operator declaration");
6544
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006545 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6546
Mike Stump11289f42009-09-09 15:08:12 +00006547 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006548 // The allocation and deallocation functions, operator new,
6549 // operator new[], operator delete and operator delete[], are
6550 // described completely in 3.7.3. The attributes and restrictions
6551 // found in the rest of this subclause do not apply to them unless
6552 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006553 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006554 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006555
Anders Carlsson22f443f2009-12-12 00:26:23 +00006556 if (Op == OO_New || Op == OO_Array_New)
6557 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006558
6559 // C++ [over.oper]p6:
6560 // An operator function shall either be a non-static member
6561 // function or be a non-member function and have at least one
6562 // parameter whose type is a class, a reference to a class, an
6563 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006564 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6565 if (MethodDecl->isStatic())
6566 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006567 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006568 } else {
6569 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006570 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6571 ParamEnd = FnDecl->param_end();
6572 Param != ParamEnd; ++Param) {
6573 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006574 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6575 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006576 ClassOrEnumParam = true;
6577 break;
6578 }
6579 }
6580
Douglas Gregord69246b2008-11-17 16:14:12 +00006581 if (!ClassOrEnumParam)
6582 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006583 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006584 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006585 }
6586
6587 // C++ [over.oper]p8:
6588 // An operator function cannot have default arguments (8.3.6),
6589 // except where explicitly stated below.
6590 //
Mike Stump11289f42009-09-09 15:08:12 +00006591 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006592 // (C++ [over.call]p1).
6593 if (Op != OO_Call) {
6594 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6595 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006596 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006597 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006598 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006599 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006600 }
6601 }
6602
Douglas Gregor6cf08062008-11-10 13:38:07 +00006603 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6604 { false, false, false }
6605#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6606 , { Unary, Binary, MemberOnly }
6607#include "clang/Basic/OperatorKinds.def"
6608 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006609
Douglas Gregor6cf08062008-11-10 13:38:07 +00006610 bool CanBeUnaryOperator = OperatorUses[Op][0];
6611 bool CanBeBinaryOperator = OperatorUses[Op][1];
6612 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006613
6614 // C++ [over.oper]p8:
6615 // [...] Operator functions cannot have more or fewer parameters
6616 // than the number required for the corresponding operator, as
6617 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006618 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006619 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006620 if (Op != OO_Call &&
6621 ((NumParams == 1 && !CanBeUnaryOperator) ||
6622 (NumParams == 2 && !CanBeBinaryOperator) ||
6623 (NumParams < 1) || (NumParams > 2))) {
6624 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006625 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006626 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006627 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006628 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006629 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006630 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006631 assert(CanBeBinaryOperator &&
6632 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006633 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006634 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006635
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006636 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006637 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006638 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006639
Douglas Gregord69246b2008-11-17 16:14:12 +00006640 // Overloaded operators other than operator() cannot be variadic.
6641 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006642 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006643 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006644 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006645 }
6646
6647 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006648 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6649 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006650 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006651 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006652 }
6653
6654 // C++ [over.inc]p1:
6655 // The user-defined function called operator++ implements the
6656 // prefix and postfix ++ operator. If this function is a member
6657 // function with no parameters, or a non-member function with one
6658 // parameter of class or enumeration type, it defines the prefix
6659 // increment operator ++ for objects of that type. If the function
6660 // is a member function with one parameter (which shall be of type
6661 // int) or a non-member function with two parameters (the second
6662 // of which shall be of type int), it defines the postfix
6663 // increment operator ++ for objects of that type.
6664 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6665 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6666 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006667 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006668 ParamIsInt = BT->getKind() == BuiltinType::Int;
6669
Chris Lattner2b786902008-11-21 07:50:02 +00006670 if (!ParamIsInt)
6671 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006672 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006673 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006674 }
6675
Douglas Gregord69246b2008-11-17 16:14:12 +00006676 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006677}
Chris Lattner3b024a32008-12-17 07:09:26 +00006678
Alexis Huntc88db062010-01-13 09:01:02 +00006679/// CheckLiteralOperatorDeclaration - Check whether the declaration
6680/// of this literal operator function is well-formed. If so, returns
6681/// false; otherwise, emits appropriate diagnostics and returns true.
6682bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6683 DeclContext *DC = FnDecl->getDeclContext();
6684 Decl::Kind Kind = DC->getDeclKind();
6685 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6686 Kind != Decl::LinkageSpec) {
6687 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6688 << FnDecl->getDeclName();
6689 return true;
6690 }
6691
6692 bool Valid = false;
6693
Alexis Hunt7dd26172010-04-07 23:11:06 +00006694 // template <char...> type operator "" name() is the only valid template
6695 // signature, and the only valid signature with no parameters.
6696 if (FnDecl->param_size() == 0) {
6697 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6698 // Must have only one template parameter
6699 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6700 if (Params->size() == 1) {
6701 NonTypeTemplateParmDecl *PmDecl =
6702 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006703
Alexis Hunt7dd26172010-04-07 23:11:06 +00006704 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006705 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6706 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6707 Valid = true;
6708 }
6709 }
6710 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006711 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006712 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6713
Alexis Huntc88db062010-01-13 09:01:02 +00006714 QualType T = (*Param)->getType();
6715
Alexis Hunt079a6f72010-04-07 22:57:35 +00006716 // unsigned long long int, long double, and any character type are allowed
6717 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006718 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6719 Context.hasSameType(T, Context.LongDoubleTy) ||
6720 Context.hasSameType(T, Context.CharTy) ||
6721 Context.hasSameType(T, Context.WCharTy) ||
6722 Context.hasSameType(T, Context.Char16Ty) ||
6723 Context.hasSameType(T, Context.Char32Ty)) {
6724 if (++Param == FnDecl->param_end())
6725 Valid = true;
6726 goto FinishedParams;
6727 }
6728
Alexis Hunt079a6f72010-04-07 22:57:35 +00006729 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006730 const PointerType *PT = T->getAs<PointerType>();
6731 if (!PT)
6732 goto FinishedParams;
6733 T = PT->getPointeeType();
6734 if (!T.isConstQualified())
6735 goto FinishedParams;
6736 T = T.getUnqualifiedType();
6737
6738 // Move on to the second parameter;
6739 ++Param;
6740
6741 // If there is no second parameter, the first must be a const char *
6742 if (Param == FnDecl->param_end()) {
6743 if (Context.hasSameType(T, Context.CharTy))
6744 Valid = true;
6745 goto FinishedParams;
6746 }
6747
6748 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6749 // are allowed as the first parameter to a two-parameter function
6750 if (!(Context.hasSameType(T, Context.CharTy) ||
6751 Context.hasSameType(T, Context.WCharTy) ||
6752 Context.hasSameType(T, Context.Char16Ty) ||
6753 Context.hasSameType(T, Context.Char32Ty)))
6754 goto FinishedParams;
6755
6756 // The second and final parameter must be an std::size_t
6757 T = (*Param)->getType().getUnqualifiedType();
6758 if (Context.hasSameType(T, Context.getSizeType()) &&
6759 ++Param == FnDecl->param_end())
6760 Valid = true;
6761 }
6762
6763 // FIXME: This diagnostic is absolutely terrible.
6764FinishedParams:
6765 if (!Valid) {
6766 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6767 << FnDecl->getDeclName();
6768 return true;
6769 }
6770
6771 return false;
6772}
6773
Douglas Gregor07665a62009-01-05 19:45:36 +00006774/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6775/// linkage specification, including the language and (if present)
6776/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6777/// the location of the language string literal, which is provided
6778/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6779/// the '{' brace. Otherwise, this linkage specification does not
6780/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006781Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6782 SourceLocation LangLoc,
6783 llvm::StringRef Lang,
6784 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006785 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006786 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006787 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006788 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006789 Language = LinkageSpecDecl::lang_cxx;
6790 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006791 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006792 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006793 }
Mike Stump11289f42009-09-09 15:08:12 +00006794
Chris Lattner438e5012008-12-17 07:13:27 +00006795 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006796
Douglas Gregor07665a62009-01-05 19:45:36 +00006797 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006798 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006799 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006800 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006801 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006802}
6803
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006804/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006805/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6806/// valid, it's the position of the closing '}' brace in a linkage
6807/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006808Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006809 Decl *LinkageSpec,
6810 SourceLocation RBraceLoc) {
6811 if (LinkageSpec) {
6812 if (RBraceLoc.isValid()) {
6813 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6814 LSDecl->setRBraceLoc(RBraceLoc);
6815 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006816 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006817 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006818 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006819}
6820
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006821/// \brief Perform semantic analysis for the variable declaration that
6822/// occurs within a C++ catch clause, returning the newly-created
6823/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00006824VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006825 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006826 SourceLocation StartLoc,
6827 SourceLocation Loc,
6828 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006829 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006830 QualType ExDeclType = TInfo->getType();
6831
Sebastian Redl54c04d42008-12-22 19:15:10 +00006832 // Arrays and functions decay.
6833 if (ExDeclType->isArrayType())
6834 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6835 else if (ExDeclType->isFunctionType())
6836 ExDeclType = Context.getPointerType(ExDeclType);
6837
6838 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6839 // The exception-declaration shall not denote a pointer or reference to an
6840 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006841 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006842 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006843 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006844 Invalid = true;
6845 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006846
Douglas Gregor104ee002010-03-08 01:47:36 +00006847 // GCC allows catching pointers and references to incomplete types
6848 // as an extension; so do we, but we warn by default.
6849
Sebastian Redl54c04d42008-12-22 19:15:10 +00006850 QualType BaseType = ExDeclType;
6851 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006852 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006853 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006854 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006855 BaseType = Ptr->getPointeeType();
6856 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006857 DK = diag::ext_catch_incomplete_ptr;
6858 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006859 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006860 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006861 BaseType = Ref->getPointeeType();
6862 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006863 DK = diag::ext_catch_incomplete_ref;
6864 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006865 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006866 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006867 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6868 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006869 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006870
Mike Stump11289f42009-09-09 15:08:12 +00006871 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006872 RequireNonAbstractType(Loc, ExDeclType,
6873 diag::err_abstract_type_in_decl,
6874 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006875 Invalid = true;
6876
John McCall2ca705e2010-07-24 00:37:23 +00006877 // Only the non-fragile NeXT runtime currently supports C++ catches
6878 // of ObjC types, and no runtime supports catching ObjC types by value.
6879 if (!Invalid && getLangOptions().ObjC1) {
6880 QualType T = ExDeclType;
6881 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6882 T = RT->getPointeeType();
6883
6884 if (T->isObjCObjectType()) {
6885 Diag(Loc, diag::err_objc_object_catch);
6886 Invalid = true;
6887 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00006888 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00006889 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6890 Invalid = true;
6891 }
6892 }
6893 }
6894
Abramo Bagnaradff19302011-03-08 08:55:46 +00006895 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6896 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006897 ExDecl->setExceptionVariable(true);
6898
Douglas Gregor6de584c2010-03-05 23:38:39 +00006899 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00006900 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00006901 // C++ [except.handle]p16:
6902 // The object declared in an exception-declaration or, if the
6903 // exception-declaration does not specify a name, a temporary (12.2) is
6904 // copy-initialized (8.5) from the exception object. [...]
6905 // The object is destroyed when the handler exits, after the destruction
6906 // of any automatic objects initialized within the handler.
6907 //
6908 // We just pretend to initialize the object with itself, then make sure
6909 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00006910 QualType initType = ExDeclType;
6911
6912 InitializedEntity entity =
6913 InitializedEntity::InitializeVariable(ExDecl);
6914 InitializationKind initKind =
6915 InitializationKind::CreateCopy(Loc, SourceLocation());
6916
6917 Expr *opaqueValue =
6918 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6919 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6920 ExprResult result = sequence.Perform(*this, entity, initKind,
6921 MultiExprArg(&opaqueValue, 1));
6922 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00006923 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00006924 else {
6925 // If the constructor used was non-trivial, set this as the
6926 // "initializer".
6927 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6928 if (!construct->getConstructor()->isTrivial()) {
6929 Expr *init = MaybeCreateExprWithCleanups(construct);
6930 ExDecl->setInit(init);
6931 }
6932
6933 // And make sure it's destructable.
6934 FinalizeVarWithDestructor(ExDecl, recordType);
6935 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00006936 }
6937 }
6938
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006939 if (Invalid)
6940 ExDecl->setInvalidDecl();
6941
6942 return ExDecl;
6943}
6944
6945/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6946/// handler.
John McCall48871652010-08-21 09:40:31 +00006947Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006948 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006949 bool Invalid = D.isInvalidType();
6950
6951 // Check for unexpanded parameter packs.
6952 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6953 UPPC_ExceptionType)) {
6954 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6955 D.getIdentifierLoc());
6956 Invalid = true;
6957 }
6958
Sebastian Redl54c04d42008-12-22 19:15:10 +00006959 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006960 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006961 LookupOrdinaryName,
6962 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006963 // The scope should be freshly made just for us. There is just no way
6964 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006965 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006966 if (PrevDecl->isTemplateParameter()) {
6967 // Maybe we will complain about the shadowed template parameter.
6968 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006969 }
6970 }
6971
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006972 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006973 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6974 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006975 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006976 }
6977
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006978 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006979 D.getSourceRange().getBegin(),
6980 D.getIdentifierLoc(),
6981 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006982 if (Invalid)
6983 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006984
Sebastian Redl54c04d42008-12-22 19:15:10 +00006985 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006986 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006987 PushOnScopeChains(ExDecl, S);
6988 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006989 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006990
Douglas Gregor758a8692009-06-17 21:51:59 +00006991 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006992 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006993}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006994
Abramo Bagnaraea947882011-03-08 16:41:52 +00006995Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006996 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006997 Expr *AssertMessageExpr_,
6998 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00006999 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007000
Anders Carlsson54b26982009-03-14 00:33:21 +00007001 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7002 llvm::APSInt Value(32);
7003 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00007004 Diag(StaticAssertLoc,
7005 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00007006 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007007 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00007008 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007009
Anders Carlsson54b26982009-03-14 00:33:21 +00007010 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00007011 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00007012 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00007013 }
7014 }
Mike Stump11289f42009-09-09 15:08:12 +00007015
Douglas Gregoref68fee2010-12-15 23:55:21 +00007016 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7017 return 0;
7018
Abramo Bagnaraea947882011-03-08 16:41:52 +00007019 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7020 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00007021
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007022 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00007023 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00007024}
Sebastian Redlf769df52009-03-24 22:27:57 +00007025
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007026/// \brief Perform semantic analysis of the given friend type declaration.
7027///
7028/// \returns A friend declaration that.
7029FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7030 TypeSourceInfo *TSInfo) {
7031 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7032
7033 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007034 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007035
Douglas Gregor3b4abb62010-04-07 17:57:12 +00007036 if (!getLangOptions().CPlusPlus0x) {
7037 // C++03 [class.friend]p2:
7038 // An elaborated-type-specifier shall be used in a friend declaration
7039 // for a class.*
7040 //
7041 // * The class-key of the elaborated-type-specifier is required.
7042 if (!ActiveTemplateInstantiations.empty()) {
7043 // Do not complain about the form of friend template types during
7044 // template instantiation; we will already have complained when the
7045 // template was declared.
7046 } else if (!T->isElaboratedTypeSpecifier()) {
7047 // If we evaluated the type to a record type, suggest putting
7048 // a tag in front.
7049 if (const RecordType *RT = T->getAs<RecordType>()) {
7050 RecordDecl *RD = RT->getDecl();
7051
7052 std::string InsertionText = std::string(" ") + RD->getKindName();
7053
7054 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7055 << (unsigned) RD->getTagKind()
7056 << T
7057 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7058 InsertionText);
7059 } else {
7060 Diag(FriendLoc, diag::ext_nonclass_type_friend)
7061 << T
7062 << SourceRange(FriendLoc, TypeRange.getEnd());
7063 }
7064 } else if (T->getAs<EnumType>()) {
7065 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007066 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007067 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007068 }
7069 }
7070
Douglas Gregor3b4abb62010-04-07 17:57:12 +00007071 // C++0x [class.friend]p3:
7072 // If the type specifier in a friend declaration designates a (possibly
7073 // cv-qualified) class type, that class is declared as a friend; otherwise,
7074 // the friend declaration is ignored.
7075
7076 // FIXME: C++0x has some syntactic restrictions on friend type declarations
7077 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007078
7079 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7080}
7081
John McCallace48cd2010-10-19 01:40:49 +00007082/// Handle a friend tag declaration where the scope specifier was
7083/// templated.
7084Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7085 unsigned TagSpec, SourceLocation TagLoc,
7086 CXXScopeSpec &SS,
7087 IdentifierInfo *Name, SourceLocation NameLoc,
7088 AttributeList *Attr,
7089 MultiTemplateParamsArg TempParamLists) {
7090 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7091
7092 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00007093 bool Invalid = false;
7094
7095 if (TemplateParameterList *TemplateParams
7096 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7097 TempParamLists.get(),
7098 TempParamLists.size(),
7099 /*friend*/ true,
7100 isExplicitSpecialization,
7101 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00007102 if (TemplateParams->size() > 0) {
7103 // This is a declaration of a class template.
7104 if (Invalid)
7105 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007106
John McCallace48cd2010-10-19 01:40:49 +00007107 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7108 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007109 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007110 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007111 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00007112 } else {
7113 // The "template<>" header is extraneous.
7114 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7115 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7116 isExplicitSpecialization = true;
7117 }
7118 }
7119
7120 if (Invalid) return 0;
7121
7122 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7123
7124 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007125 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00007126 if (TempParamLists.get()[I]->size()) {
7127 isAllExplicitSpecializations = false;
7128 break;
7129 }
7130 }
7131
7132 // FIXME: don't ignore attributes.
7133
7134 // If it's explicit specializations all the way down, just forget
7135 // about the template header and build an appropriate non-templated
7136 // friend. TODO: for source fidelity, remember the headers.
7137 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007138 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00007139 ElaboratedTypeKeyword Keyword
7140 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007141 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007142 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00007143 if (T.isNull())
7144 return 0;
7145
7146 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7147 if (isa<DependentNameType>(T)) {
7148 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7149 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007150 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007151 TL.setNameLoc(NameLoc);
7152 } else {
7153 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7154 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007155 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007156 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7157 }
7158
7159 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7160 TSI, FriendLoc);
7161 Friend->setAccess(AS_public);
7162 CurContext->addDecl(Friend);
7163 return Friend;
7164 }
7165
7166 // Handle the case of a templated-scope friend class. e.g.
7167 // template <class T> class A<T>::B;
7168 // FIXME: we don't support these right now.
7169 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7170 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7171 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7172 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7173 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007174 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00007175 TL.setNameLoc(NameLoc);
7176
7177 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7178 TSI, FriendLoc);
7179 Friend->setAccess(AS_public);
7180 Friend->setUnsupportedFriend(true);
7181 CurContext->addDecl(Friend);
7182 return Friend;
7183}
7184
7185
John McCall11083da2009-09-16 22:47:08 +00007186/// Handle a friend type declaration. This works in tandem with
7187/// ActOnTag.
7188///
7189/// Notes on friend class templates:
7190///
7191/// We generally treat friend class declarations as if they were
7192/// declaring a class. So, for example, the elaborated type specifier
7193/// in a friend declaration is required to obey the restrictions of a
7194/// class-head (i.e. no typedefs in the scope chain), template
7195/// parameters are required to match up with simple template-ids, &c.
7196/// However, unlike when declaring a template specialization, it's
7197/// okay to refer to a template specialization without an empty
7198/// template parameter declaration, e.g.
7199/// friend class A<T>::B<unsigned>;
7200/// We permit this as a special case; if there are any template
7201/// parameters present at all, require proper matching, i.e.
7202/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00007203Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00007204 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007205 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00007206
7207 assert(DS.isFriendSpecified());
7208 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7209
John McCall11083da2009-09-16 22:47:08 +00007210 // Try to convert the decl specifier to a type. This works for
7211 // friend templates because ActOnTag never produces a ClassTemplateDecl
7212 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00007213 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00007214 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7215 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00007216 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00007217 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007218
Douglas Gregor6c110f32010-12-16 01:14:37 +00007219 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7220 return 0;
7221
John McCall11083da2009-09-16 22:47:08 +00007222 // This is definitely an error in C++98. It's probably meant to
7223 // be forbidden in C++0x, too, but the specification is just
7224 // poorly written.
7225 //
7226 // The problem is with declarations like the following:
7227 // template <T> friend A<T>::foo;
7228 // where deciding whether a class C is a friend or not now hinges
7229 // on whether there exists an instantiation of A that causes
7230 // 'foo' to equal C. There are restrictions on class-heads
7231 // (which we declare (by fiat) elaborated friend declarations to
7232 // be) that makes this tractable.
7233 //
7234 // FIXME: handle "template <> friend class A<T>;", which
7235 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00007236 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00007237 Diag(Loc, diag::err_tagless_friend_type_template)
7238 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007239 return 0;
John McCall11083da2009-09-16 22:47:08 +00007240 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007241
John McCallaa74a0c2009-08-28 07:59:38 +00007242 // C++98 [class.friend]p1: A friend of a class is a function
7243 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00007244 // This is fixed in DR77, which just barely didn't make the C++03
7245 // deadline. It's also a very silly restriction that seriously
7246 // affects inner classes and which nobody else seems to implement;
7247 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00007248 //
7249 // But note that we could warn about it: it's always useless to
7250 // friend one of your own members (it's not, however, worthless to
7251 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00007252
John McCall11083da2009-09-16 22:47:08 +00007253 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007254 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00007255 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007256 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00007257 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00007258 TSI,
John McCall11083da2009-09-16 22:47:08 +00007259 DS.getFriendSpecLoc());
7260 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007261 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7262
7263 if (!D)
John McCall48871652010-08-21 09:40:31 +00007264 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007265
John McCall11083da2009-09-16 22:47:08 +00007266 D->setAccess(AS_public);
7267 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00007268
John McCall48871652010-08-21 09:40:31 +00007269 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00007270}
7271
John McCallde3fd222010-10-12 23:13:28 +00007272Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7273 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007274 const DeclSpec &DS = D.getDeclSpec();
7275
7276 assert(DS.isFriendSpecified());
7277 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7278
7279 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007280 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7281 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007282
7283 // C++ [class.friend]p1
7284 // A friend of a class is a function or class....
7285 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007286 // It *doesn't* see through dependent types, which is correct
7287 // according to [temp.arg.type]p3:
7288 // If a declaration acquires a function type through a
7289 // type dependent on a template-parameter and this causes
7290 // a declaration that does not use the syntactic form of a
7291 // function declarator to have a function type, the program
7292 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007293 if (!T->isFunctionType()) {
7294 Diag(Loc, diag::err_unexpected_friend);
7295
7296 // It might be worthwhile to try to recover by creating an
7297 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007298 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007299 }
7300
7301 // C++ [namespace.memdef]p3
7302 // - If a friend declaration in a non-local class first declares a
7303 // class or function, the friend class or function is a member
7304 // of the innermost enclosing namespace.
7305 // - The name of the friend is not found by simple name lookup
7306 // until a matching declaration is provided in that namespace
7307 // scope (either before or after the class declaration granting
7308 // friendship).
7309 // - If a friend function is called, its name may be found by the
7310 // name lookup that considers functions from namespaces and
7311 // classes associated with the types of the function arguments.
7312 // - When looking for a prior declaration of a class or a function
7313 // declared as a friend, scopes outside the innermost enclosing
7314 // namespace scope are not considered.
7315
John McCallde3fd222010-10-12 23:13:28 +00007316 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007317 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7318 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007319 assert(Name);
7320
Douglas Gregor6c110f32010-12-16 01:14:37 +00007321 // Check for unexpanded parameter packs.
7322 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7323 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7324 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7325 return 0;
7326
John McCall07e91c02009-08-06 02:15:43 +00007327 // The context we found the declaration in, or in which we should
7328 // create the declaration.
7329 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007330 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007331 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007332 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007333
John McCallde3fd222010-10-12 23:13:28 +00007334 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007335
John McCallde3fd222010-10-12 23:13:28 +00007336 // There are four cases here.
7337 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007338 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007339 // there as appropriate.
7340 // Recover from invalid scope qualifiers as if they just weren't there.
7341 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007342 // C++0x [namespace.memdef]p3:
7343 // If the name in a friend declaration is neither qualified nor
7344 // a template-id and the declaration is a function or an
7345 // elaborated-type-specifier, the lookup to determine whether
7346 // the entity has been previously declared shall not consider
7347 // any scopes outside the innermost enclosing namespace.
7348 // C++0x [class.friend]p11:
7349 // If a friend declaration appears in a local class and the name
7350 // specified is an unqualified name, a prior declaration is
7351 // looked up without considering scopes that are outside the
7352 // innermost enclosing non-class scope. For a friend function
7353 // declaration, if there is no prior declaration, the program is
7354 // ill-formed.
7355 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007356 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007357
John McCallf7cfb222010-10-13 05:45:15 +00007358 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007359 DC = CurContext;
7360 while (true) {
7361 // Skip class contexts. If someone can cite chapter and verse
7362 // for this behavior, that would be nice --- it's what GCC and
7363 // EDG do, and it seems like a reasonable intent, but the spec
7364 // really only says that checks for unqualified existing
7365 // declarations should stop at the nearest enclosing namespace,
7366 // not that they should only consider the nearest enclosing
7367 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007368 while (DC->isRecord())
7369 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007370
John McCall1f82f242009-11-18 22:49:29 +00007371 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007372
7373 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007374 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007375 break;
John McCallf7cfb222010-10-13 05:45:15 +00007376
John McCallf4776592010-10-14 22:22:28 +00007377 if (isTemplateId) {
7378 if (isa<TranslationUnitDecl>(DC)) break;
7379 } else {
7380 if (DC->isFileContext()) break;
7381 }
John McCall07e91c02009-08-06 02:15:43 +00007382 DC = DC->getParent();
7383 }
7384
7385 // C++ [class.friend]p1: A friend of a class is a function or
7386 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007387 // C++0x changes this for both friend types and functions.
7388 // Most C++ 98 compilers do seem to give an error here, so
7389 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007390 if (!Previous.empty() && DC->Equals(CurContext)
7391 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007392 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007393
John McCallccbc0322010-10-13 06:22:15 +00007394 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007395
John McCallde3fd222010-10-12 23:13:28 +00007396 // - There's a non-dependent scope specifier, in which case we
7397 // compute it and do a previous lookup there for a function
7398 // or function template.
7399 } else if (!SS.getScopeRep()->isDependent()) {
7400 DC = computeDeclContext(SS);
7401 if (!DC) return 0;
7402
7403 if (RequireCompleteDeclContext(SS, DC)) return 0;
7404
7405 LookupQualifiedName(Previous, DC);
7406
7407 // Ignore things found implicitly in the wrong scope.
7408 // TODO: better diagnostics for this case. Suggesting the right
7409 // qualified scope would be nice...
7410 LookupResult::Filter F = Previous.makeFilter();
7411 while (F.hasNext()) {
7412 NamedDecl *D = F.next();
7413 if (!DC->InEnclosingNamespaceSetOf(
7414 D->getDeclContext()->getRedeclContext()))
7415 F.erase();
7416 }
7417 F.done();
7418
7419 if (Previous.empty()) {
7420 D.setInvalidType();
7421 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7422 return 0;
7423 }
7424
7425 // C++ [class.friend]p1: A friend of a class is a function or
7426 // class that is not a member of the class . . .
7427 if (DC->Equals(CurContext))
7428 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7429
7430 // - There's a scope specifier that does not match any template
7431 // parameter lists, in which case we use some arbitrary context,
7432 // create a method or method template, and wait for instantiation.
7433 // - There's a scope specifier that does match some template
7434 // parameter lists, which we don't handle right now.
7435 } else {
7436 DC = CurContext;
7437 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007438 }
7439
John McCallf7cfb222010-10-13 05:45:15 +00007440 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007441 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007442 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7443 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7444 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007445 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007446 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7447 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007448 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007449 }
John McCall07e91c02009-08-06 02:15:43 +00007450 }
7451
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007452 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007453 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007454 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007455 IsDefinition,
7456 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007457 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007458
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007459 assert(ND->getDeclContext() == DC);
7460 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007461
John McCall759e32b2009-08-31 22:39:49 +00007462 // Add the function declaration to the appropriate lookup tables,
7463 // adjusting the redeclarations list as necessary. We don't
7464 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007465 //
John McCall759e32b2009-08-31 22:39:49 +00007466 // Also update the scope-based lookup if the target context's
7467 // lookup context is in lexical scope.
7468 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007469 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007470 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007471 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007472 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007473 }
John McCallaa74a0c2009-08-28 07:59:38 +00007474
7475 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007476 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007477 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007478 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007479 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007480
John McCallde3fd222010-10-12 23:13:28 +00007481 if (ND->isInvalidDecl())
7482 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007483 else {
7484 FunctionDecl *FD;
7485 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7486 FD = FTD->getTemplatedDecl();
7487 else
7488 FD = cast<FunctionDecl>(ND);
7489
7490 // Mark templated-scope function declarations as unsupported.
7491 if (FD->getNumTemplateParameterLists())
7492 FrD->setUnsupportedFriend(true);
7493 }
John McCallde3fd222010-10-12 23:13:28 +00007494
John McCall48871652010-08-21 09:40:31 +00007495 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007496}
7497
John McCall48871652010-08-21 09:40:31 +00007498void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7499 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007500
Sebastian Redlf769df52009-03-24 22:27:57 +00007501 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7502 if (!Fn) {
7503 Diag(DelLoc, diag::err_deleted_non_function);
7504 return;
7505 }
7506 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7507 Diag(DelLoc, diag::err_deleted_decl_not_first);
7508 Diag(Prev->getLocation(), diag::note_previous_declaration);
7509 // If the declaration wasn't the first, we delete the function anyway for
7510 // recovery.
7511 }
7512 Fn->setDeleted();
7513}
Sebastian Redl4c018662009-04-27 21:33:24 +00007514
7515static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007516 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007517 Stmt *SubStmt = *CI;
7518 if (!SubStmt)
7519 continue;
7520 if (isa<ReturnStmt>(SubStmt))
7521 Self.Diag(SubStmt->getSourceRange().getBegin(),
7522 diag::err_return_in_constructor_handler);
7523 if (!isa<Expr>(SubStmt))
7524 SearchForReturnInStmt(Self, SubStmt);
7525 }
7526}
7527
7528void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7529 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7530 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7531 SearchForReturnInStmt(*this, Handler);
7532 }
7533}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007534
Mike Stump11289f42009-09-09 15:08:12 +00007535bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007536 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007537 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7538 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007539
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007540 if (Context.hasSameType(NewTy, OldTy) ||
7541 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007542 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007543
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007544 // Check if the return types are covariant
7545 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007546
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007547 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007548 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7549 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007550 NewClassTy = NewPT->getPointeeType();
7551 OldClassTy = OldPT->getPointeeType();
7552 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007553 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7554 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7555 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7556 NewClassTy = NewRT->getPointeeType();
7557 OldClassTy = OldRT->getPointeeType();
7558 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007559 }
7560 }
Mike Stump11289f42009-09-09 15:08:12 +00007561
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007562 // The return types aren't either both pointers or references to a class type.
7563 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007564 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007565 diag::err_different_return_type_for_overriding_virtual_function)
7566 << New->getDeclName() << NewTy << OldTy;
7567 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007568
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007569 return true;
7570 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007571
Anders Carlssone60365b2009-12-31 18:34:24 +00007572 // C++ [class.virtual]p6:
7573 // If the return type of D::f differs from the return type of B::f, the
7574 // class type in the return type of D::f shall be complete at the point of
7575 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007576 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7577 if (!RT->isBeingDefined() &&
7578 RequireCompleteType(New->getLocation(), NewClassTy,
7579 PDiag(diag::err_covariant_return_incomplete)
7580 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007581 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007582 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007583
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007584 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007585 // Check if the new class derives from the old class.
7586 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7587 Diag(New->getLocation(),
7588 diag::err_covariant_return_not_derived)
7589 << New->getDeclName() << NewTy << OldTy;
7590 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7591 return true;
7592 }
Mike Stump11289f42009-09-09 15:08:12 +00007593
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007594 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007595 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007596 diag::err_covariant_return_inaccessible_base,
7597 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7598 // FIXME: Should this point to the return type?
7599 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007600 // FIXME: this note won't trigger for delayed access control
7601 // diagnostics, and it's impossible to get an undelayed error
7602 // here from access control during the original parse because
7603 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007604 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7605 return true;
7606 }
7607 }
Mike Stump11289f42009-09-09 15:08:12 +00007608
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007609 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007610 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007611 Diag(New->getLocation(),
7612 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007613 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007614 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7615 return true;
7616 };
Mike Stump11289f42009-09-09 15:08:12 +00007617
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007618
7619 // The new class type must have the same or less qualifiers as the old type.
7620 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7621 Diag(New->getLocation(),
7622 diag::err_covariant_return_type_class_type_more_qualified)
7623 << New->getDeclName() << NewTy << OldTy;
7624 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7625 return true;
7626 };
Mike Stump11289f42009-09-09 15:08:12 +00007627
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007628 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007629}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007630
Douglas Gregor21920e372009-12-01 17:24:26 +00007631/// \brief Mark the given method pure.
7632///
7633/// \param Method the method to be marked pure.
7634///
7635/// \param InitRange the source range that covers the "0" initializer.
7636bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00007637 SourceLocation EndLoc = InitRange.getEnd();
7638 if (EndLoc.isValid())
7639 Method->setRangeEnd(EndLoc);
7640
Douglas Gregor21920e372009-12-01 17:24:26 +00007641 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7642 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007643 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00007644 }
Douglas Gregor21920e372009-12-01 17:24:26 +00007645
7646 if (!Method->isInvalidDecl())
7647 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7648 << Method->getDeclName() << InitRange;
7649 return true;
7650}
7651
John McCall1f4ee7b2009-12-19 09:28:58 +00007652/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7653/// an initializer for the out-of-line declaration 'Dcl'. The scope
7654/// is a fresh scope pushed for just this purpose.
7655///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007656/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7657/// static data member of class X, names should be looked up in the scope of
7658/// class X.
John McCall48871652010-08-21 09:40:31 +00007659void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007660 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00007661 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007662
John McCall1f4ee7b2009-12-19 09:28:58 +00007663 // We should only get called for declarations with scope specifiers, like:
7664 // int foo::bar;
7665 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007666 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007667}
7668
7669/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007670/// initializer for the out-of-line declaration 'D'.
7671void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007672 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00007673 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007674
John McCall1f4ee7b2009-12-19 09:28:58 +00007675 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007676 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007677}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007678
7679/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7680/// C++ if/switch/while/for statement.
7681/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007682DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007683 // C++ 6.4p2:
7684 // The declarator shall not specify a function or an array.
7685 // The type-specifier-seq shall not contain typedef and shall not declare a
7686 // new class or enumeration.
7687 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7688 "Parser allowed 'typedef' as storage class of condition decl.");
7689
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007690 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007691 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7692 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007693
7694 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7695 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7696 // would be created and CXXConditionDeclExpr wants a VarDecl.
7697 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7698 << D.getSourceRange();
7699 return DeclResult();
7700 } else if (OwnedTag && OwnedTag->isDefinition()) {
7701 // The type-specifier-seq shall not declare a new class or enumeration.
7702 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7703 }
7704
John McCall48871652010-08-21 09:40:31 +00007705 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007706 if (!Dcl)
7707 return DeclResult();
7708
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007709 return Dcl;
7710}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007711
Douglas Gregor88d292c2010-05-13 16:44:06 +00007712void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7713 bool DefinitionRequired) {
7714 // Ignore any vtable uses in unevaluated operands or for classes that do
7715 // not have a vtable.
7716 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7717 CurContext->isDependentContext() ||
7718 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007719 return;
7720
Douglas Gregor88d292c2010-05-13 16:44:06 +00007721 // Try to insert this class into the map.
7722 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7723 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7724 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7725 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007726 // If we already had an entry, check to see if we are promoting this vtable
7727 // to required a definition. If so, we need to reappend to the VTableUses
7728 // list, since we may have already processed the first entry.
7729 if (DefinitionRequired && !Pos.first->second) {
7730 Pos.first->second = true;
7731 } else {
7732 // Otherwise, we can early exit.
7733 return;
7734 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007735 }
7736
7737 // Local classes need to have their virtual members marked
7738 // immediately. For all other classes, we mark their virtual members
7739 // at the end of the translation unit.
7740 if (Class->isLocalClass())
7741 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007742 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007743 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007744}
7745
Douglas Gregor88d292c2010-05-13 16:44:06 +00007746bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007747 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007748 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007749
Douglas Gregor88d292c2010-05-13 16:44:06 +00007750 // Note: The VTableUses vector could grow as a result of marking
7751 // the members of a class as "used", so we check the size each
7752 // time through the loop and prefer indices (with are stable) to
7753 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00007754 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00007755 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007756 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007757 if (!Class)
7758 continue;
7759
7760 SourceLocation Loc = VTableUses[I].second;
7761
7762 // If this class has a key function, but that key function is
7763 // defined in another translation unit, we don't need to emit the
7764 // vtable even though we're using it.
7765 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007766 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007767 switch (KeyFunction->getTemplateSpecializationKind()) {
7768 case TSK_Undeclared:
7769 case TSK_ExplicitSpecialization:
7770 case TSK_ExplicitInstantiationDeclaration:
7771 // The key function is in another translation unit.
7772 continue;
7773
7774 case TSK_ExplicitInstantiationDefinition:
7775 case TSK_ImplicitInstantiation:
7776 // We will be instantiating the key function.
7777 break;
7778 }
7779 } else if (!KeyFunction) {
7780 // If we have a class with no key function that is the subject
7781 // of an explicit instantiation declaration, suppress the
7782 // vtable; it will live with the explicit instantiation
7783 // definition.
7784 bool IsExplicitInstantiationDeclaration
7785 = Class->getTemplateSpecializationKind()
7786 == TSK_ExplicitInstantiationDeclaration;
7787 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7788 REnd = Class->redecls_end();
7789 R != REnd; ++R) {
7790 TemplateSpecializationKind TSK
7791 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7792 if (TSK == TSK_ExplicitInstantiationDeclaration)
7793 IsExplicitInstantiationDeclaration = true;
7794 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7795 IsExplicitInstantiationDeclaration = false;
7796 break;
7797 }
7798 }
7799
7800 if (IsExplicitInstantiationDeclaration)
7801 continue;
7802 }
7803
7804 // Mark all of the virtual members of this class as referenced, so
7805 // that we can build a vtable. Then, tell the AST consumer that a
7806 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00007807 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00007808 MarkVirtualMembersReferenced(Loc, Class);
7809 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7810 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7811
7812 // Optionally warn if we're emitting a weak vtable.
7813 if (Class->getLinkage() == ExternalLinkage &&
7814 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007815 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007816 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7817 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007818 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007819 VTableUses.clear();
7820
Douglas Gregor97509692011-04-22 22:25:37 +00007821 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007822}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007823
Rafael Espindola5b334082010-03-26 00:36:59 +00007824void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7825 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007826 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7827 e = RD->method_end(); i != e; ++i) {
7828 CXXMethodDecl *MD = *i;
7829
7830 // C++ [basic.def.odr]p2:
7831 // [...] A virtual member function is used if it is not pure. [...]
7832 if (MD->isVirtual() && !MD->isPure())
7833 MarkDeclarationReferenced(Loc, MD);
7834 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007835
7836 // Only classes that have virtual bases need a VTT.
7837 if (RD->getNumVBases() == 0)
7838 return;
7839
7840 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7841 e = RD->bases_end(); i != e; ++i) {
7842 const CXXRecordDecl *Base =
7843 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007844 if (Base->getNumVBases() == 0)
7845 continue;
7846 MarkVirtualMembersReferenced(Loc, Base);
7847 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007848}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007849
7850/// SetIvarInitializers - This routine builds initialization ASTs for the
7851/// Objective-C implementation whose ivars need be initialized.
7852void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7853 if (!getLangOptions().CPlusPlus)
7854 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007855 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007856 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7857 CollectIvarsToConstructOrDestruct(OID, ivars);
7858 if (ivars.empty())
7859 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007860 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007861 for (unsigned i = 0; i < ivars.size(); i++) {
7862 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007863 if (Field->isInvalidDecl())
7864 continue;
7865
Alexis Hunt1d792652011-01-08 20:30:50 +00007866 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007867 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7868 InitializationKind InitKind =
7869 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7870
7871 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007872 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007873 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007874 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007875 // Note, MemberInit could actually come back empty if no initialization
7876 // is required (e.g., because it would call a trivial default constructor)
7877 if (!MemberInit.get() || MemberInit.isInvalid())
7878 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007879
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007880 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007881 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7882 SourceLocation(),
7883 MemberInit.takeAs<Expr>(),
7884 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007885 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007886
7887 // Be sure that the destructor is accessible and is marked as referenced.
7888 if (const RecordType *RecordTy
7889 = Context.getBaseElementType(Field->getType())
7890 ->getAs<RecordType>()) {
7891 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007892 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007893 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7894 CheckDestructorAccess(Field->getLocation(), Destructor,
7895 PDiag(diag::err_access_dtor_ivar)
7896 << Context.getBaseElementType(Field->getType()));
7897 }
7898 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007899 }
7900 ObjCImplementation->setIvarInitializers(Context,
7901 AllToInit.data(), AllToInit.size());
7902 }
7903}